You can subscribe to this list here.
2005 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
(233) |
Sep
(199) |
Oct
(206) |
Nov
(185) |
Dec
(270) |
---|---|---|---|---|---|---|---|---|---|---|---|---|
2006 |
Jan
(232) |
Feb
(426) |
Mar
(623) |
Apr
(592) |
May
(506) |
Jun
(389) |
Jul
(160) |
Aug
(3) |
Sep
(1) |
Oct
(1) |
Nov
(2) |
Dec
(5) |
2007 |
Jan
(1) |
Feb
(1) |
Mar
(2) |
Apr
(2) |
May
(4) |
Jun
(2) |
Jul
|
Aug
(3) |
Sep
(5) |
Oct
(9) |
Nov
(6) |
Dec
(6) |
2008 |
Jan
(3) |
Feb
|
Mar
(1) |
Apr
(3) |
May
(3) |
Jun
(5) |
Jul
(10) |
Aug
(2) |
Sep
(12) |
Oct
(10) |
Nov
(54) |
Dec
(49) |
2009 |
Jan
(19) |
Feb
(13) |
Mar
(20) |
Apr
(24) |
May
(44) |
Jun
(29) |
Jul
(32) |
Aug
(10) |
Sep
(7) |
Oct
(10) |
Nov
(4) |
Dec
(17) |
2010 |
Jan
(14) |
Feb
(5) |
Mar
(23) |
Apr
(50) |
May
(31) |
Jun
(9) |
Jul
(5) |
Aug
(4) |
Sep
(7) |
Oct
(5) |
Nov
(2) |
Dec
(3) |
2011 |
Jan
(12) |
Feb
(5) |
Mar
(5) |
Apr
(3) |
May
(4) |
Jun
(3) |
Jul
(2) |
Aug
|
Sep
|
Oct
|
Nov
(1) |
Dec
|
2012 |
Jan
(1) |
Feb
(2) |
Mar
|
Apr
(1) |
May
(1) |
Jun
(2) |
Jul
(4) |
Aug
(1) |
Sep
|
Oct
(1) |
Nov
|
Dec
|
2013 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
(2) |
Aug
(1) |
Sep
|
Oct
|
Nov
|
Dec
|
2014 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
(3) |
Sep
|
Oct
|
Nov
|
Dec
(1) |
2015 |
Jan
|
Feb
|
Mar
(2) |
Apr
|
May
|
Jun
(1) |
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
|
2016 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
(1) |
Jul
(1) |
Aug
|
Sep
|
Oct
|
Nov
|
Dec
|
From: <jbo...@li...> - 2006-02-02 18:23:43
|
Author: szimano Date: 2006-02-02 13:23:30 -0500 (Thu, 02 Feb 2006) New Revision: 2234 Modified: trunk/forge/portal-extensions/shotoku/shotoku-files/src/java/org/jboss/shotoku/files/FileContentManager.java trunk/forge/portal-extensions/shotoku/shotoku-files/src/java/org/jboss/shotoku/files/FileDirectory.java trunk/forge/portal-extensions/shotoku/shotoku-files/src/java/org/jboss/shotoku/files/FileNode.java trunk/forge/portal-extensions/shotoku/shotoku-files/src/java/org/jboss/shotoku/files/FileTools.java Log: chcnges to files cm JBSHOTOKU-53 Modified: trunk/forge/portal-extensions/shotoku/shotoku-files/src/java/org/jboss/shotoku/files/FileContentManager.java =================================================================== --- trunk/forge/portal-extensions/shotoku/shotoku-files/src/java/org/jboss/shotoku/files/FileContentManager.java 2006-02-01 14:15:20 UTC (rev 2233) +++ trunk/forge/portal-extensions/shotoku/shotoku-files/src/java/org/jboss/shotoku/files/FileContentManager.java 2006-02-02 18:23:30 UTC (rev 2234) @@ -51,14 +51,14 @@ public FileContentManager(String id, String prefix, Configuration conf) throws RepositoryException { super(id, prefix); - + // add separator at the end and at the begginig if (!prefix.startsWith("/")) { - prefix = "/" + prefix; + prefix = prefix.substring(1); } - if (!prefix.endsWith("/")) { - prefix += "/"; + if (prefix.endsWith("/")) { + prefix = prefix.substring(0, prefix.length() - 1); } pathToRepo = getProperty("shotoku.default.localpath"); @@ -130,11 +130,11 @@ } public String getPathToRepoCurrent() { - return pathToRepoCurrent + prefix; + return pathToRepoCurrent + File.pathSeparator + prefix; } public String getPathToRepoHistory() { - return pathToRepoHistory + prefix; + return pathToRepoHistory + File.pathSeparator + prefix; } public String getPrefix() { Modified: trunk/forge/portal-extensions/shotoku/shotoku-files/src/java/org/jboss/shotoku/files/FileDirectory.java =================================================================== --- trunk/forge/portal-extensions/shotoku/shotoku-files/src/java/org/jboss/shotoku/files/FileDirectory.java 2006-02-01 14:15:20 UTC (rev 2233) +++ trunk/forge/portal-extensions/shotoku/shotoku-files/src/java/org/jboss/shotoku/files/FileDirectory.java 2006-02-02 18:23:30 UTC (rev 2234) @@ -31,6 +31,7 @@ import java.util.Map; import java.util.Properties; +import org.jboss.logging.Logger; import org.jboss.shotoku.ContentManager; import org.jboss.shotoku.Directory; import org.jboss.shotoku.Node; @@ -48,40 +49,37 @@ private File directory; private FileContentManager manager; - + private String dirFullPath; - - private String dirPath; - + + private String dirPath; + private Properties props; - + private boolean dirChanged = false; - + + private Logger log = Logger.getLogger(this.getClass()); /** * */ private static final long serialVersionUID = 1L; - public FileDirectory(String directory, FileContentManager manager) throws RepositoryException { - while (directory.startsWith("/")) { - directory = directory.substring(1); - } - - while(directory.endsWith("/")) { - directory = directory.substring(0, directory.length()-2); - } - - dirFullPath = manager.getPathToRepoCurrent()+File.pathSeparator+directory; - + public FileDirectory(String directory, FileContentManager manager) + throws RepositoryException { + directory = FileTools.normalizeName(directory); + + dirFullPath = manager.getPathToRepoCurrent() + File.pathSeparator + + directory; + dirPath = directory; - + File dir = new File(dirFullPath); - + this.manager = manager; if (!dir.exists()) dirChanged = true; - + if (dir.exists() && !dir.isDirectory()) { throw new RepositoryException(directory + " is not a directory"); } @@ -98,12 +96,14 @@ for (File file : children) { if (file.isFile()) { try { - list.add(new FileNode(this, file.getName(), false, manager)); + list + .add(new FileNode(this, file.getName(), false, + manager)); } catch (ResourceAlreadyExists e) { - //shouldn't happen + // shouldn't happen new RepositoryException(e); } catch (ResourceDoesNotExist e) { - //shouldn't happen + // shouldn't happen new RepositoryException(e); } } @@ -120,7 +120,8 @@ // get all children for (File directory : children) { if (directory.isDirectory()) { - list.add(new FileDirectory(dirFullPath + File.pathSeparator + directory.getName(), manager)); + list.add(new FileDirectory(dirFullPath + File.pathSeparator + + directory.getName(), manager)); } } @@ -129,8 +130,13 @@ public Node getNode(String name) throws RepositoryException, ResourceDoesNotExist { - File file = new File(this.directory.getAbsolutePath() + name); + name = FileTools.normalizeName(name); + File file = new File(this.directory.getAbsolutePath() + + File.pathSeparator + name); + + log.info(file.getAbsoluteFile()); + if (!file.exists()) { throw new ResourceDoesNotExist("File " + file.getAbsolutePath() + " doesn't exists"); @@ -145,19 +151,28 @@ public Directory getDirectory(String name) throws RepositoryException, ResourceDoesNotExist { - File dir = new File(this.directory.getAbsolutePath() + name); + name = FileTools.normalizeName(name); + + File dir = new File(this.directory.getAbsolutePath() + + File.pathSeparator + name); + if (!dir.exists()) { throw new RepositoryException("Directory " + dir.getAbsolutePath() + " doesn't exists"); } - return new FileDirectory(dirFullPath + File.pathSeparator + name, manager); + return new FileDirectory(dirFullPath + File.pathSeparator + name, + manager); } public Node newNode(String name) throws ResourceAlreadyExists, RepositoryException { - File file = new File(this.directory.getAbsolutePath() + File.pathSeparator + name); + + name = FileTools.normalizeName(name); + + File file = new File(this.directory.getAbsolutePath() + + File.pathSeparator + name); if (file.exists()) { throw new ResourceAlreadyExists("File " + file.getAbsolutePath() @@ -195,7 +210,8 @@ } } - return new FileDirectory(dirFullPath + File.pathSeparator + name, manager); + return new FileDirectory(dirFullPath + File.pathSeparator + name, + manager); } public boolean hasIndex(String arg0) throws RepositoryException { @@ -214,19 +230,19 @@ // create new directory Directory newDir = dir.newDirectory(newName); List<Directory> dirs = getDirectories(); - + // copy all subdirectories for (Directory subDir : dirs) { subDir.copyTo(newDir, subDir.getName(), logMessage); } - + NodeList nodes = getNodes(); - - //copy all nodes inside directory + + // copy all nodes inside directory for (Node node : nodes.toList()) { node.copyTo(newDir, node.getName(), logMessage); } - + } catch (RepositoryException e) { throw new CopyException(e); } catch (ResourceAlreadyExists e) { @@ -239,35 +255,36 @@ try { // create new directory Directory newDir = dir.newDirectory(getName()); - + // set it's properties refreshProps(); - + for (Object key : props.keySet()) { - newDir.setProperty((String)key, props.getProperty((String)key)); + newDir.setProperty((String) key, props + .getProperty((String) key)); } - + // save dir with props newDir.save(logMessage); - + List<Directory> dirs = getDirectories(); - + // move all subdirectories for (Directory subDir : dirs) { subDir.moveTo(newDir, logMessage); } - + NodeList nodes = getNodes(); - + // move all nodes inside directory for (Node node : nodes.toList()) { node.moveTo(newDir, logMessage); } - + // delete this dir history File hisDir = FileTools.getHistoryDir(this, manager); hisDir.delete(); - + } catch (Exception e) { throw new MoveException(e); } @@ -279,13 +296,13 @@ } catch (IOException e) { throw new RepositoryException(e); } - - Map<String, String> map = new HashMap<String,String>(); - + + Map<String, String> map = new HashMap<String, String>(); + for (Object key : props.keySet()) { - map.put((String)key, props.getProperty((String)key)); + map.put((String) key, props.getProperty((String) key)); } - + return map; } @@ -301,7 +318,7 @@ } catch (IOException e) { throw new RepositoryException(e); } - + return props.getProperty(name); } @@ -311,9 +328,9 @@ } catch (IOException e) { throw new RepositoryException(e); } - + dirChanged = true; - + props.remove(name); } @@ -323,32 +340,35 @@ } catch (IOException e) { throw new RepositoryException(e); } - + dirChanged = true; - + props.setProperty(name, value); } - public void save(String logMessage) throws SaveException, RepositoryException { + public void save(String logMessage) throws SaveException, + RepositoryException { if (!directory.exists()) if (!directory.mkdirs()) { - throw new SaveException("Couldn't create directory: "+getFullName()); + throw new SaveException("Couldn't create directory: " + + getFullName()); } - + if (dirChanged) { try { - File propFile = FileTools.getPropertiesFileForDirectory(this, manager); - + File propFile = FileTools.getPropertiesFileForDirectory(this, + manager); + OutputStream os = new FileOutputStream(propFile); - + props.store(os, FileTools.STORE_TEXT); - + os.close(); } catch (IOException e) { throw new SaveException(e); } } - + } public String getLogMessage() throws RepositoryException { @@ -365,14 +385,15 @@ public void delete() throws DeleteException, RepositoryException { if (!directory.delete()) { - throw new DeleteException("Couldn't delete directory: "+dirFullPath); + throw new DeleteException("Couldn't delete directory: " + + dirFullPath); } } public String getName() { return directory.getName(); } - + public String toString() { return directory.getAbsolutePath(); } Modified: trunk/forge/portal-extensions/shotoku/shotoku-files/src/java/org/jboss/shotoku/files/FileNode.java =================================================================== --- trunk/forge/portal-extensions/shotoku/shotoku-files/src/java/org/jboss/shotoku/files/FileNode.java 2006-02-01 14:15:20 UTC (rev 2233) +++ trunk/forge/portal-extensions/shotoku/shotoku-files/src/java/org/jboss/shotoku/files/FileNode.java 2006-02-02 18:23:30 UTC (rev 2234) @@ -74,6 +74,9 @@ public FileNode(Directory directory, String node, boolean newFile, FileContentManager manager) throws RepositoryException, ResourceAlreadyExists, ResourceDoesNotExist { + + node = FileTools.normalizeName(node); + File fil = new File(directory + File.pathSeparator + node); this.manager = manager; @@ -89,17 +92,21 @@ } if (newFile && fil.exists()) { - throw new ResourceAlreadyExists(directory + File.pathSeparator - + node + " already exists"); + throw new ResourceAlreadyExists(fil.getAbsolutePath() + " already exists"); } else if (!newFile && !fil.exists()) { - throw new ResourceDoesNotExist(directory + File.pathSeparator - + node + " doesn't exist"); + throw new ResourceDoesNotExist(fil.getAbsolutePath() + " doesn't exists"); } this.file = fil; + String suffix = node.substring(node.lastIndexOf("."), node.length()); + + if (suffix.length() == 0) { + suffix = ".bin"; + } + try { - tmpFile = File.createTempFile("shotoku-file", node); + tmpFile = File.createTempFile("shotoku-file", suffix); } catch (IOException e) { throw new RepositoryException(e); } Modified: trunk/forge/portal-extensions/shotoku/shotoku-files/src/java/org/jboss/shotoku/files/FileTools.java =================================================================== --- trunk/forge/portal-extensions/shotoku/shotoku-files/src/java/org/jboss/shotoku/files/FileTools.java 2006-02-01 14:15:20 UTC (rev 2233) +++ trunk/forge/portal-extensions/shotoku/shotoku-files/src/java/org/jboss/shotoku/files/FileTools.java 2006-02-02 18:23:30 UTC (rev 2234) @@ -273,4 +273,16 @@ return props; } + + public static String normalizeName(String name) { + if (name.startsWith("/")) { + name = name.substring(1); + } + + if (name.endsWith("/")) { + name = name.substring(0, name.length()-1); + } + + return name; + } } |
From: <jbo...@li...> - 2006-02-01 14:15:26
|
Author: rem...@jb... Date: 2006-02-01 09:15:20 -0500 (Wed, 01 Feb 2006) New Revision: 2233 Modified: trunk/labs/jbossweb/src/share/classes/org/apache/catalina/realm/RealmBase.java Log: - Remove container log. - Port patch: no port when using the default one. Modified: trunk/labs/jbossweb/src/share/classes/org/apache/catalina/realm/RealmBase.java =================================================================== --- trunk/labs/jbossweb/src/share/classes/org/apache/catalina/realm/RealmBase.java 2006-02-01 11:34:15 UTC (rev 2232) +++ trunk/labs/jbossweb/src/share/classes/org/apache/catalina/realm/RealmBase.java 2006-02-01 14:15:20 UTC (rev 2233) @@ -78,12 +78,6 @@ /** - * Container log - */ - protected Log containerLog = null; - - - /** * Digest algorithm used in storing passwords in a non-plaintext format. * Valid values are those accepted for the algorithm name by the * MessageDigest class, or <code>null</code> if no digesting should @@ -175,7 +169,6 @@ Container oldContainer = this.container; this.container = container; - this.containerLog = container.getLogger(); support.firePropertyChange("container", oldContainer, this.container); } @@ -290,14 +283,14 @@ validated = serverCredentials.equals(credentials); } if(! validated ) { - if (containerLog.isTraceEnabled()) { - containerLog.trace(sm.getString("realmBase.authenticateFailure", + if (container.getLogger().isTraceEnabled()) { + container.getLogger().trace(sm.getString("realmBase.authenticateFailure", username)); } return null; } - if (containerLog.isTraceEnabled()) { - containerLog.trace(sm.getString("realmBase.authenticateSuccess", + if (container.getLogger().isTraceEnabled()) { + container.getLogger().trace(sm.getString("realmBase.authenticateSuccess", username)); } @@ -876,10 +869,12 @@ StringBuffer file = new StringBuffer(); String protocol = "https"; String host = request.getServerName(); - // Protocol - file.append(protocol).append("://"); - // Host with port - file.append(host).append(":").append(redirectPort); + // Protocol and host + file.append(protocol).append("://").append(host); + // Port + if (redirectPort != 443) { + file.append(":").append(redirectPort); + } // URI file.append(request.getRequestURI()); String requestedSessionId = request.getRequestedSessionId(); |
From: <jbo...@li...> - 2006-02-01 11:35:14
|
Author: mic...@jb... Date: 2006-02-01 06:34:15 -0500 (Wed, 01 Feb 2006) New Revision: 2232 Added: trunk/labs/jbossrules/drools-core/src/main/java/org/drools/lang/dsl/template/RegexTemplate.java trunk/labs/jbossrules/drools-core/src/main/java/org/drools/lang/dsl/template/Template.java Removed: trunk/labs/jbossrules/drools-core/src/main/java/org/drools/lang/dsl/template/TemplateContext.java Modified: trunk/labs/jbossrules/drools-core/src/main/java/org/drools/lang/ParseException.java trunk/labs/jbossrules/drools-core/src/main/java/org/drools/lang/Parser.java trunk/labs/jbossrules/drools-core/src/main/java/org/drools/lang/dsl/template/NLExpressionCompiler.java trunk/labs/jbossrules/drools-core/src/main/java/org/drools/lang/dsl/template/NLMappingItem.java trunk/labs/jbossrules/drools-core/src/main/java/org/drools/lang/dsl/template/TemplateFactory.java trunk/labs/jbossrules/drools-core/src/main/java/org/drools/rule/EvaluatorFactory.java trunk/labs/jbossrules/drools-core/src/main/java/org/drools/spi/Evaluator.java trunk/labs/jbossrules/drools-core/src/test/java/org/drools/examples/manners/MannersTest.java trunk/labs/jbossrules/drools-core/src/test/java/org/drools/lang/ParserTest.java trunk/labs/jbossrules/drools-core/src/test/java/org/drools/lang/dsl/template/NLExpressionCompilerTest.java trunk/labs/jbossrules/drools-core/src/test/java/org/drools/lang/dsl/template/TemplateContextTest.java trunk/labs/jbossrules/drools-core/src/test/java/org/drools/lang/dsl/template/TemplateFactoryTest.java trunk/labs/jbossrules/drools-core/src/test/java/org/drools/lang/one-rule.drl Log: parser added noloop etc Modified: trunk/labs/jbossrules/drools-core/src/main/java/org/drools/lang/ParseException.java =================================================================== --- trunk/labs/jbossrules/drools-core/src/main/java/org/drools/lang/ParseException.java 2006-01-31 23:00:16 UTC (rev 2231) +++ trunk/labs/jbossrules/drools-core/src/main/java/org/drools/lang/ParseException.java 2006-02-01 11:34:15 UTC (rev 2232) @@ -8,6 +8,8 @@ private static final long serialVersionUID = -7500818890340701977L; private int lineNumber; + + private Throwable cause; /** * Thrown if there is an exception related to parsing a line in a drl file. @@ -19,18 +21,40 @@ } /** + * Allows nesting of misc exceptions, yet preserving the line number + * that triggered the error. + */ + public ParseException(String message, int lineNumber, Throwable cause) { + super(message); + this.lineNumber = lineNumber; + this.cause = cause; + } + + /** * The line number on which the error occurred. */ public int getLineNumber() { return this.lineNumber; } + /** + * This will print out a summary, including the line number. + * It will also print out the cause message if applicable. + */ public String getMessage() { - return super.getMessage() + " Line number: " + lineNumber; + if (cause == null) { + return super.getMessage() + " Line number: " + lineNumber; + } else { + return super.getMessage() + " Line number: " + lineNumber + ". Caused by: " + cause.getMessage(); + } } public String toString() { return getMessage(); } + public Throwable getCause() { + return cause; + } + } Modified: trunk/labs/jbossrules/drools-core/src/main/java/org/drools/lang/Parser.java =================================================================== --- trunk/labs/jbossrules/drools-core/src/main/java/org/drools/lang/Parser.java 2006-01-31 23:00:16 UTC (rev 2231) +++ trunk/labs/jbossrules/drools-core/src/main/java/org/drools/lang/Parser.java 2006-02-01 11:34:15 UTC (rev 2232) @@ -39,7 +39,10 @@ static Pattern EXPANDER_STATEMENT = Pattern.compile("\\s*use\\s*expander\\s([^;]+);?\\s*"); static Pattern FACT_BINDING = Pattern.compile( "\\s*(\\w+)\\s*=>\\s*(.*)" ); static Pattern FIELD_BINDING = Pattern.compile( "\\s*(\\w+):(\\w+)\\s*" ); - + static Pattern SALIENCE_STATEMENT = Pattern.compile("\\s*salience\\s*([^;]+)\\s*"); + static Pattern NOLOOP_STATEMENT = Pattern.compile("\\s*no-loop\\s*([^;]+)\\s*"); + + //---------------------------------------- // Consequence handling patterns //---------------------------------------- @@ -100,9 +103,16 @@ } public void parse() throws IOException, RuleConstructionException { - prolog(); - rules(); - + try { + prolog(); + rules(); + } catch (Exception e) { //for misc exceptions. Stil want the line number. + if (e instanceof ParseException) { + throw (ParseException) e; + } else { + throw new ParseException("Parse error", this.lineNumber, e); + } + } } protected void prolog() throws IOException { @@ -253,12 +263,15 @@ throw new DuplicateRuleNameException( null, rule, null ); } } - rules.add( new Rule( ruleName ) ); - } + Rule rule = new Rule( ruleName ); + rules.add( rule ); + + ruleAttributes(rule); + ruleConditions(); + ruleConsequence(); + + } - ruleConditions(); - ruleConsequence(); - line = laDiscard(); if ( ! line.trim().equals( "end" ) ) { @@ -270,6 +283,46 @@ return true; } + /** For rule attributes like salience, etc */ + protected void ruleAttributes(Rule rule) throws IOException { + String line = laDiscard(); + + if ( line == null ) { return; } + + while ( ruleAttribute(rule) ) { + + } + } + + protected boolean ruleAttribute(Rule rule) throws IOException { + String line = laDiscard(); + if ( line == null ) { + return false; + } + + line = line.trim(); + + if ( line.equals( "when" ) || line.equals( "then" ) ) { + return false; + } + + line = consume(); + + Matcher matcher = SALIENCE_STATEMENT.matcher(line); + if (matcher.matches()) { + rule.setSalience(Integer.parseInt(matcher.group(1))); + return true; + } + matcher = NOLOOP_STATEMENT.matcher(line); + if (matcher.matches()) { + rule.setNoLoop(Boolean.parseBoolean(matcher.group(1))); + return true; + } + + + return true; + } + protected void ruleConditions() throws IOException { String line = laDiscard(); Modified: trunk/labs/jbossrules/drools-core/src/main/java/org/drools/lang/dsl/template/NLExpressionCompiler.java =================================================================== --- trunk/labs/jbossrules/drools-core/src/main/java/org/drools/lang/dsl/template/NLExpressionCompiler.java 2006-01-31 23:00:16 UTC (rev 2231) +++ trunk/labs/jbossrules/drools-core/src/main/java/org/drools/lang/dsl/template/NLExpressionCompiler.java 2006-02-01 11:34:15 UTC (rev 2232) @@ -38,8 +38,8 @@ TemplateFactory factory = new TemplateFactory(); for ( Iterator iter = grammarItems.iterator(); iter.hasNext(); ) { NLMappingItem mapping = (NLMappingItem) iter.next(); - TemplateContext ctx = factory.getContext(mapping.getNaturalTemplate()); - templateCache.put(mapping, ctx); + Template template = factory.getTemplate(mapping.getNaturalTemplate()); + templateCache.put(mapping, template); } } @@ -49,14 +49,14 @@ * the original, and then move on to the next item from the grammar/dictionary. */ public String compile(String expression) { - String nl = expression; + String expanded = expression; for ( Iterator iter = templateCache.entrySet().iterator(); iter.hasNext(); ) { Map.Entry entry = (Map.Entry) iter.next(); NLMappingItem mapping = (NLMappingItem) entry.getKey(); - TemplateContext ctx = (TemplateContext) entry.getValue(); - nl = ctx.processAllInstances(nl, mapping.getGrammarTemplate()); + Template template = (Template) entry.getValue(); + expanded = template.expandAll(expanded, mapping.getTargetTemplate()); } - return nl; + return expanded; } Modified: trunk/labs/jbossrules/drools-core/src/main/java/org/drools/lang/dsl/template/NLMappingItem.java =================================================================== --- trunk/labs/jbossrules/drools-core/src/main/java/org/drools/lang/dsl/template/NLMappingItem.java 2006-01-31 23:00:16 UTC (rev 2231) +++ trunk/labs/jbossrules/drools-core/src/main/java/org/drools/lang/dsl/template/NLMappingItem.java 2006-02-01 11:34:15 UTC (rev 2232) @@ -18,22 +18,22 @@ private int priority = 0; private String naturalTemplate; - private String grammarTemplate; + private String targetTemplate; public NLMappingItem(int priority, String naturalTemplate, - String grammarTemplate) { + String targetTemplate) { this.priority = priority; this.naturalTemplate = naturalTemplate; - this.grammarTemplate = grammarTemplate; + this.targetTemplate = targetTemplate; } public String getNaturalTemplate() { return naturalTemplate; } - public String getGrammarTemplate() { - return grammarTemplate; + public String getTargetTemplate() { + return targetTemplate; } public int compareTo(Object arg) { Added: trunk/labs/jbossrules/drools-core/src/main/java/org/drools/lang/dsl/template/RegexTemplate.java =================================================================== --- trunk/labs/jbossrules/drools-core/src/main/java/org/drools/lang/dsl/template/RegexTemplate.java 2006-01-31 23:00:16 UTC (rev 2231) +++ trunk/labs/jbossrules/drools-core/src/main/java/org/drools/lang/dsl/template/RegexTemplate.java 2006-02-01 11:34:15 UTC (rev 2232) @@ -0,0 +1,181 @@ +package org.drools.lang.dsl.template; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.apache.commons.lang.StringUtils; + +/** + * Experimental... seeing how far I can take dynamically generated regex... + * its a bit of a nightmare to escape everything though... + * + * @author Michael + * + */ +public class RegexTemplate { + + + private Pattern templatePattern; + private List holes; + private String template; + + public static void main(String[] args) { + + RegexTemplate regTemplate = new RegexTemplate("the date between {before} and {after}"); + regTemplate.compile(); + + String out = regTemplate.populate("the date between date1 and date2", "dateBetween({before},{after})"); + + perfRegex( regTemplate, + out ); + + regTemplate = new RegexTemplate("date of '{date}'"); + regTemplate.compile(); + + + + System.out.println(regTemplate.populate("date of 'today' and date of 'tomorrow'", "dateOf({date})")); + + + perfTemplate(); + + + + } + + + private static void perfRegex(RegexTemplate regTemplate, + String out) { + long start = System.currentTimeMillis(); + for (int i = 0; i < 100000; i++) { + regTemplate.populate("the date between date1 and date2", "dateBetween({before},{after})"); + } + System.out.println("time for regex " + (System.currentTimeMillis() - start)); + System.out.println(out); + } + + + private static void perfTemplate() { + long start; + TemplateFactory factory = new TemplateFactory(); + Template template = factory.getTemplate("the date between {before} and {after}"); + + start = System.currentTimeMillis(); + for (int i = 0; i < 100000; i++) { + template.expandAll("the date between date1 and date2", "dateBetween({before},{after})" ); + } + System.out.println("time for non " + (System.currentTimeMillis() - start)); + } + + + List lex() { + ChunkLexer lex = new ChunkLexer(); + List chunks = lex.lex(template); + return chunks; + + } + + + public String populate(String source, String targetTemplate) { + Matcher matcher = templatePattern.matcher(source); + if (!matcher.matches()) return source; + + String result = targetTemplate; + if (matcher.groupCount() != holes.size()) { + throw new IllegalArgumentException("Unable to match up holes in template with source."); + } + + for (int i = 0; i < matcher.groupCount(); i++ ) { + String val = matcher.group(i + 1); + String hole = (String) holes.get(i); + result = replace(result, hole, val.trim());// result.replace(hole, val); + } + return result; + } + + public void compile() { + List chunks = lex(); + + StringBuffer regex = new StringBuffer(); + List holes = new ArrayList(); + for ( Iterator iter = chunks.iterator(); iter.hasNext(); ) { + String chunk = (String) iter.next(); + if (chunk.startsWith("{")) { + holes.add(chunk); + regex.append("\\b(.*)\\b"); + } else { + regex.append(replace(chunk, " ", "\\s"));//chunk.replace(" ", "\\s")); + } + } + this.holes = holes; + this.templatePattern = Pattern.compile("\\s*" + regex.toString() + "\\s*"); + } + + public RegexTemplate(String grammarTemplate) { + this.template = grammarTemplate; + } + + private String replace(String str, String find, String replace) { + return StringUtils.replace(str, find, replace); + } + + /** + * Lex out chunks. + * @author <a href="mailto:mic...@gm..."> Michael Neale</a> + */ + static class ChunkLexer { + + private List chunks = new ArrayList(); + + private StringBuffer buffer = new StringBuffer(); + + public List lex(String grammarTemplate) { + + char[] chars = grammarTemplate.toCharArray(); + + for ( int i = 0; i < chars.length; i++ ) { + switch ( chars[i] ) { + case '{' : + startHole(); + break; + case '}' : + endHole(); + break; + default : + buffer.append(chars[i]); + break; + } + } + String buf = this.buffer.toString(); + if (!buf.equals("")) addChunk( buf ); + return this.chunks; + + } + + private boolean addChunk(String buf) { + return this.chunks.add( buf.trim() ); + } + + private void endHole() { + String buf = this.buffer.toString(); + chunks.add("{" + buf + "}"); + this.buffer = new StringBuffer(); + } + + private void startHole() { + String buf = this.buffer.toString(); + if (!buf.equals("")) { + addChunk( buf ); + } + this.buffer = new StringBuffer(); + } + + + } +} Property changes on: trunk/labs/jbossrules/drools-core/src/main/java/org/drools/lang/dsl/template/RegexTemplate.java ___________________________________________________________________ Name: svn:eol-style + native Added: trunk/labs/jbossrules/drools-core/src/main/java/org/drools/lang/dsl/template/Template.java =================================================================== --- trunk/labs/jbossrules/drools-core/src/main/java/org/drools/lang/dsl/template/Template.java 2006-01-31 23:00:16 UTC (rev 2231) +++ trunk/labs/jbossrules/drools-core/src/main/java/org/drools/lang/dsl/template/Template.java 2006-02-01 11:34:15 UTC (rev 2232) @@ -0,0 +1,130 @@ +package org.drools.lang.dsl.template; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +import org.apache.commons.lang.StringUtils; + + +/** + * This class takes a linked list of Chunk objects, and will replace what the chunks represent + * in an nl string with a interpolated grammar template. + * The values are obtained by matching the chunks with the nl. + * + * @author <a href="mailto:mic...@gm..."> Michael Neale</a> + * This is an alternative approach to the infix parser. + */ +class Template { + + //the start of the linked list. + Chunk start; + + /** + * Ad a chunk from the dictionary expression. + * A chunk is a piece of nl, or a hole. + * nl & holes must not be mixed. + */ + Template addChunk(String chunkText) { + Chunk chunk = new Chunk(chunkText); + if (start == null) { + start = chunk; + } else { + start.addToEnd(chunk); + } + return this; + } + + /** + * This will parse the input nl expression, and build a map of values for the "holes" + * in the grammar expression. + * It does this by getting the Chunks of the grammar to parse themselves. + */ + void processNL(String nl, Map map) { + start.clearValues(); + start.process(nl); + start.buildValueMap(map); + } + + /** + * This builds a fragment of the nl expression which can be used + * to swap out a piece of the original with the target expression. + * + * The target expression is the "right hand side" of the grammar map. + */ + String getSubstitutionKey() { + StringBuffer buffer = new StringBuffer(); + start.buildSubtitutionKey(buffer); + return buffer.toString().trim(); //trim so we don't get any erroneous spaces to stop replacing. + } + + /** + * This will build the target string that you can use to substitute the original with. + * @param map The map of values to hole keys. + * @param grammar_r The grammar item which will have the values plugged into the "holes". + * @return The final expression ready for substitution. + */ + String populateTargetString(Map map, + String grammar_r) { + for ( Iterator iter = map.keySet().iterator(); iter.hasNext(); ) { + String key = (String) iter.next(); + grammar_r = StringUtils.replace(grammar_r, key, (String) map.get(key)); + } + return grammar_r; + } + + /** + * @param nl The natural language expression. + * @param subKey The part of the nl expression to be swapped out. + * @param target The chunk to be swapped in to the nl + * @return The nl with the chunk replaced with the target. + */ + String interpolate(String nl, String subKey, String target) { + return StringUtils.replace(nl, subKey, target); + } + + /** + * This does it all as one call. Requires that chunks have been setup. + * @param nl The nl expression to process. + * @param targetTemplate The target grammar expression that will be interpolated (with the values from the original chunks), + * and then inserted in to the nl. + * @return the NL with the populated grammarRHS replacing the original pattern (from the chunks). + */ + public String expandOnce(String nl, String targetTemplate) { + Map values = new HashMap(); + this.processNL(nl, values); + String subKey = this.getSubstitutionKey(); + String target = this.populateTargetString(values, targetTemplate); + return this.interpolate(nl, subKey, target); + } + + + /** + * Similar to expandOnce, but processes iteratively until there is + * no change in the output. This allows for stuff to be repeated in an NL expression. + */ + public String expandAll(String nl, String targetTemplate) { + String result = nl; + + //put an upper limit + int i = 0; + while (i < 10) { + String newResult = expandOnce(result, targetTemplate); + if (newResult.equals(result)) { + break; + } + result = newResult; + + i++; + if (i == 10) { + throw new IllegalArgumentException("To many iterations in processing the expression: [" + + nl + + "] with target template: [" + + targetTemplate + "]"); + } + } + return result; + } + + +} Property changes on: trunk/labs/jbossrules/drools-core/src/main/java/org/drools/lang/dsl/template/Template.java ___________________________________________________________________ Name: svn:eol-style + native Deleted: trunk/labs/jbossrules/drools-core/src/main/java/org/drools/lang/dsl/template/TemplateContext.java =================================================================== --- trunk/labs/jbossrules/drools-core/src/main/java/org/drools/lang/dsl/template/TemplateContext.java 2006-01-31 23:00:16 UTC (rev 2231) +++ trunk/labs/jbossrules/drools-core/src/main/java/org/drools/lang/dsl/template/TemplateContext.java 2006-02-01 11:34:15 UTC (rev 2232) @@ -1,130 +0,0 @@ -package org.drools.lang.dsl.template; - -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - -import org.apache.commons.lang.StringUtils; - - -/** - * This class takes a linked list of Chunk objects, and will replace what the chunks represent - * in an nl string with a interpolated grammar template. - * The values are obtained by matching the chunks with the nl. - * - * @author <a href="mailto:mic...@gm..."> Michael Neale</a> - * This is an alternative approach to the infix parser. - */ -class TemplateContext { - - //the start of the linked list. - Chunk start; - - /** - * Ad a chunk from the dictionary expression. - * A chunk is a piece of nl, or a hole. - * nl & holes must not be mixed. - */ - TemplateContext addChunk(String chunkText) { - Chunk chunk = new Chunk(chunkText); - if (start == null) { - start = chunk; - } else { - start.addToEnd(chunk); - } - return this; - } - - /** - * This will parse the input nl expression, and build a map of values for the "holes" - * in the grammar expression. - * It does this by getting the Chunks of the grammar to parse themselves. - */ - void processNL(String nl, Map map) { - start.clearValues(); - start.process(nl); - start.buildValueMap(map); - } - - /** - * This builds a fragment of the nl expression which can be used - * to swap out a piece of the original with the target expression. - * - * The target expression is the "right hand side" of the grammar map. - */ - String getSubstitutionKey() { - StringBuffer buffer = new StringBuffer(); - start.buildSubtitutionKey(buffer); - return buffer.toString().trim(); //trim so we don't get any erroneous spaces to stop replacing. - } - - /** - * This will build the target string that you can use to substitute the original with. - * @param map The map of values to hole keys. - * @param grammar_r The grammar item which will have the values plugged into the "holes". - * @return The final expression ready for substitution. - */ - String populateTargetString(Map map, - String grammar_r) { - for ( Iterator iter = map.keySet().iterator(); iter.hasNext(); ) { - String key = (String) iter.next(); - grammar_r = StringUtils.replace(grammar_r, key, (String) map.get(key)); - } - return grammar_r; - } - - /** - * @param nl The natural language expression. - * @param subKey The part of the nl expression to be swapped out. - * @param target The chunk to be swapped in to the nl - * @return The nl with the chunk replaced with the target. - */ - String interpolate(String nl, String subKey, String target) { - return StringUtils.replace(nl, subKey, target); - } - - /** - * This does it all as one call. Requires that chunks have been setup. - * @param nl The nl expression to process. - * @param grammarTemplate The grammar expression that will be interpolated (with the values from the original chunks), - * and then inserted in to the nl. - * @return the NL with the populated grammarRHS replacing the original pattern (from the chunks). - */ - public String process(String nl, String grammarTemplate) { - Map values = new HashMap(); - this.processNL(nl, values); - String subKey = this.getSubstitutionKey(); - String target = this.populateTargetString(values, grammarTemplate); - return this.interpolate(nl, subKey, target); - } - - - /** - * Similar to process, but processes iteratively until there is - * no change in the output. This allows for stuff to be repeated in an NL expression. - */ - public String processAllInstances(String nl, String grammarTemplate) { - String result = nl; - - //put an upper limit - int i = 0; - while (i < 10) { - String newResult = process(result, grammarTemplate); - if (newResult.equals(result)) { - break; - } - result = newResult; - - i++; - if (i == 10) { - throw new IllegalArgumentException("To many iterations in processing the expression: [" + - nl + - "] with target template: [" + - grammarTemplate + "]"); - } - } - return result; - } - - -} Modified: trunk/labs/jbossrules/drools-core/src/main/java/org/drools/lang/dsl/template/TemplateFactory.java =================================================================== --- trunk/labs/jbossrules/drools-core/src/main/java/org/drools/lang/dsl/template/TemplateFactory.java 2006-01-31 23:00:16 UTC (rev 2231) +++ trunk/labs/jbossrules/drools-core/src/main/java/org/drools/lang/dsl/template/TemplateFactory.java 2006-02-01 11:34:15 UTC (rev 2232) @@ -5,7 +5,7 @@ import java.util.List; /** - * This takes a grammar template (the left hand side of a grammar mapping table) + * This takes a natural grammar template (the left hand side of a grammar mapping table) * and builds a TemplateContext for it. * * Uses a built in lexer. @@ -16,19 +16,19 @@ /** * This will lex the template string into chunks. - * @param template From the grammar. eg "{0} likes cheese" is a template. + * @param naturalTemplate From the grammar. eg "{0} likes cheese" is a template. * @return A template context ready to apply to a nl expression. */ - public TemplateContext getContext(String template) { + public Template getTemplate(String naturalTemplate) { - TemplateContext ctx = new TemplateContext(); + Template template = new Template(); - List chunkList = lexChunks(template); + List chunkList = lexChunks(naturalTemplate); for ( Iterator iter = chunkList.iterator(); iter.hasNext(); ) { - ctx.addChunk((String) iter.next()); + template.addChunk((String) iter.next()); } - return ctx; + return template; } Modified: trunk/labs/jbossrules/drools-core/src/main/java/org/drools/rule/EvaluatorFactory.java =================================================================== --- trunk/labs/jbossrules/drools-core/src/main/java/org/drools/rule/EvaluatorFactory.java 2006-01-31 23:00:16 UTC (rev 2231) +++ trunk/labs/jbossrules/drools-core/src/main/java/org/drools/rule/EvaluatorFactory.java 2006-02-01 11:34:15 UTC (rev 2232) @@ -343,6 +343,8 @@ static class IntegerEqualEvaluator extends BaseEvaluator { private static Evaluator INSTANCE; + public static long count = 0; + public static Evaluator getInstance() { if ( INSTANCE == null ) { INSTANCE = new IntegerEqualEvaluator(); @@ -357,6 +359,7 @@ public boolean evaluate(Object object1, Object object2) { + count++; return ((Number) object1).intValue() == ((Number) object2).intValue(); } @@ -489,4 +492,8 @@ return "Integer >="; } } + + public static long getIntEqEvalCount() { + return IntegerEqualEvaluator.count; + } } Modified: trunk/labs/jbossrules/drools-core/src/main/java/org/drools/spi/Evaluator.java =================================================================== --- trunk/labs/jbossrules/drools-core/src/main/java/org/drools/spi/Evaluator.java 2006-01-31 23:00:16 UTC (rev 2231) +++ trunk/labs/jbossrules/drools-core/src/main/java/org/drools/spi/Evaluator.java 2006-02-01 11:34:15 UTC (rev 2232) @@ -30,4 +30,6 @@ public boolean evaluate(Object object1, Object object2); + + } Modified: trunk/labs/jbossrules/drools-core/src/test/java/org/drools/examples/manners/MannersTest.java =================================================================== --- trunk/labs/jbossrules/drools-core/src/test/java/org/drools/examples/manners/MannersTest.java 2006-01-31 23:00:16 UTC (rev 2231) +++ trunk/labs/jbossrules/drools-core/src/test/java/org/drools/examples/manners/MannersTest.java 2006-02-01 11:34:15 UTC (rev 2232) @@ -196,6 +196,7 @@ // Thread.sleep( 1000 ); // } + System.out.println("Integer evals:" + EvaluatorFactory.getIntEqEvalCount()); } /** Modified: trunk/labs/jbossrules/drools-core/src/test/java/org/drools/lang/ParserTest.java =================================================================== --- trunk/labs/jbossrules/drools-core/src/test/java/org/drools/lang/ParserTest.java 2006-01-31 23:00:16 UTC (rev 2231) +++ trunk/labs/jbossrules/drools-core/src/test/java/org/drools/lang/ParserTest.java 2006-02-01 11:34:15 UTC (rev 2232) @@ -49,8 +49,10 @@ assertEquals( "java.util.ArrayList", parser.getImports().get( 1 ) ); assertEquals( 1, parser.getRules().size() ); - assertEquals( "find seating", ((Rule)parser.getRules().get(0)).getName() ); - + Rule rule = (Rule)parser.getRules().get(0); + assertEquals( "find seating", rule.getName() ); + assertEquals( 30, rule.getSalience()); + assertEquals( true, rule.getNoLoop()); assertEquals(null, parser.getExpander()); } Modified: trunk/labs/jbossrules/drools-core/src/test/java/org/drools/lang/dsl/template/NLExpressionCompilerTest.java =================================================================== --- trunk/labs/jbossrules/drools-core/src/test/java/org/drools/lang/dsl/template/NLExpressionCompilerTest.java 2006-01-31 23:00:16 UTC (rev 2231) +++ trunk/labs/jbossrules/drools-core/src/test/java/org/drools/lang/dsl/template/NLExpressionCompilerTest.java 2006-02-01 11:34:15 UTC (rev 2232) @@ -82,7 +82,7 @@ grammar = new NLGrammar(); grammar.addNLItem(new NLMappingItem(1, "date of '{0}'", "dateOf({0})")); - grammar.addNLItem(new NLMappingItem(2, "age of [ {0} ]", "{0}.getAge()")); + grammar.addNLItem(new NLMappingItem(2, "age of [{0}]", "{0}.getAge()")); grammar.addNLItem(new NLMappingItem(3, "Today", "new java.util.Date()")); grammar.addNLItem(new NLMappingItem(4, "{0} is before {1}", "({0}).compareTo({1}) > 0")); @@ -92,11 +92,16 @@ expected = "(dateOf(10-jul-2006)).compareTo(new java.util.Date()) > 0"; assertEquals(expected, compiler.compile(nl)); - nl = "age of [ bob ] < age of [ michael ]"; + //test repeating... + nl = "age of [bob] < age of [michael]"; expected = "bob.getAge() < michael.getAge()"; assertEquals(expected, compiler.compile(nl)); + //test no change to output + nl = "nothing relevant here... move along"; + expected = nl; + assertEquals(expected, compiler.compile(nl)); } Modified: trunk/labs/jbossrules/drools-core/src/test/java/org/drools/lang/dsl/template/TemplateContextTest.java =================================================================== --- trunk/labs/jbossrules/drools-core/src/test/java/org/drools/lang/dsl/template/TemplateContextTest.java 2006-01-31 23:00:16 UTC (rev 2231) +++ trunk/labs/jbossrules/drools-core/src/test/java/org/drools/lang/dsl/template/TemplateContextTest.java 2006-02-01 11:34:15 UTC (rev 2232) @@ -12,25 +12,25 @@ public void testAllInOne() { - TemplateContext ctx = new TemplateContext(); + Template ctx = new Template(); //chunks represent a lexed grammar "left hand side" ctx.addChunk("baby on board") .addChunk("{0}") .addChunk("and") .addChunk("{1}") .addChunk("burt ward"); - String result = ctx.process("yeah this is an expression baby on board exp1 and exp2 burt ward end.", "something({0}, {1})"); + String result = ctx.expandOnce("yeah this is an expression baby on board exp1 and exp2 burt ward end.", "something({0}, {1})"); assertEquals("yeah this is an expression something(exp1, exp2) end.", result); //and check that the iterative one is OK. - result = ctx.process("yeah this is an expression baby on board exp1 and exp2 burt ward end.", "something({0}, {1})"); + result = ctx.expandOnce("yeah this is an expression baby on board exp1 and exp2 burt ward end.", "something({0}, {1})"); assertEquals("yeah this is an expression something(exp1, exp2) end.", result); } public void testBuildStrings() { - TemplateContext ctx = new TemplateContext(); + Template ctx = new Template(); //chunks represent a lexed grammar "left hand side" ctx.addChunk("baby on board") @@ -67,7 +67,7 @@ public void testMultipleReplacement() { - TemplateContext ctx = new TemplateContext(); + Template ctx = new Template(); //chunks represent a lexed grammar "left hand side" ctx.addChunk("{0}") @@ -78,7 +78,7 @@ String expected = "bob.likesCheese() and michael.likesCheese() conan.likesCheese()"; - String result = ctx.processAllInstances(nl, grammarTemplate); + String result = ctx.expandAll(nl, grammarTemplate); assertEquals(expected, result); } Modified: trunk/labs/jbossrules/drools-core/src/test/java/org/drools/lang/dsl/template/TemplateFactoryTest.java =================================================================== --- trunk/labs/jbossrules/drools-core/src/test/java/org/drools/lang/dsl/template/TemplateFactoryTest.java 2006-01-31 23:00:16 UTC (rev 2231) +++ trunk/labs/jbossrules/drools-core/src/test/java/org/drools/lang/dsl/template/TemplateFactoryTest.java 2006-02-01 11:34:15 UTC (rev 2232) @@ -8,7 +8,7 @@ public void testMake() { TemplateFactory factory = new TemplateFactory(); - TemplateContext ctx = factory.getContext("something {0} going {1} on."); + Template ctx = factory.getTemplate("something {0} going {1} on."); assertNotNull(ctx); } Modified: trunk/labs/jbossrules/drools-core/src/test/java/org/drools/lang/one-rule.drl =================================================================== --- trunk/labs/jbossrules/drools-core/src/test/java/org/drools/lang/one-rule.drl 2006-01-31 23:00:16 UTC (rev 2231) +++ trunk/labs/jbossrules/drools-core/src/test/java/org/drools/lang/one-rule.drl 2006-02-01 11:34:15 UTC (rev 2232) @@ -15,6 +15,10 @@ rule find seating + + salience 30 + no-loop true + when context => Context( state == Context.ASSIGN_SEATS ) Seating( seatingId:id, seatingPid:pid, pathDone == true, seatingRightSeat:rightSeat, seatingRightGuestName:rightGuestName ) |
From: <jbo...@li...> - 2006-01-31 07:22:27
|
Author: mic...@jb... Date: 2006-01-31 02:22:09 -0500 (Tue, 31 Jan 2006) New Revision: 2229 Added: trunk/labs/jbossrules/drools-core/src/main/java/org/drools/lang/ConsequenceExpander.java trunk/labs/jbossrules/drools-core/src/test/java/org/drools/lang/ConsequenceExpanderTest.java Modified: trunk/labs/jbossrules/drools-core/src/main/java/org/drools/lang/Parser.java trunk/labs/jbossrules/drools-core/src/test/java/org/drools/lang/one-rule.drl Log: KnowledgeHelper stuff Added: trunk/labs/jbossrules/drools-core/src/main/java/org/drools/lang/ConsequenceExpander.java =================================================================== --- trunk/labs/jbossrules/drools-core/src/main/java/org/drools/lang/ConsequenceExpander.java 2006-01-31 00:06:25 UTC (rev 2228) +++ trunk/labs/jbossrules/drools-core/src/main/java/org/drools/lang/ConsequenceExpander.java 2006-01-31 07:22:09 UTC (rev 2229) @@ -0,0 +1,65 @@ +package org.drools.lang; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * This is a utility class for dealing with consequence block specific stuff. + * It is pre compilation thing. + * + * This should be used before and non built in expanders are called. + * + * @author Michael Neale + */ +class ConsequenceExpander implements Expander { + + /** + * This takes a raw consequence, and fixes up the KnowledegeHelper references + * to be what SMF requires. + * + * eg: modify( myObject ); --> drools.modify( myObjectHandle, myObject ); + * + * (can adjust the PREFIX if needed). + * + * Uses some non-tail recursion to ensure that all parts are "expanded". + */ + String knowledgeHelperFixer(String raw) { + String result = knowledgeHelperFixer(raw, Parser.MODIFY, "modify"); + result = knowledgeHelperFixer(result, Parser.ASSERT, "assert"); + result = knowledgeHelperFixer(result, Parser.RETRACT, "retract"); + return result; + } + + + /** + * Recursively apply the pattern, replace the guts of what is matched. + */ + String knowledgeHelperFixer(String raw, Pattern pattern, String action) { + Matcher matcher = pattern.matcher(raw); + + if (matcher.matches()) { + String pre = matcher.group(1); + if (matcher.group(1) != null) { + pre = knowledgeHelperFixer(pre, pattern, action); + } + String obj = matcher.group(2).trim(); + String post = matcher.group(3); + if (post != null) { + post = knowledgeHelperFixer(post, pattern, action); + } + + return pre + matcher.replaceAll("drools." + action + "(" + obj + "Handle, " + obj + ")") + post; + } + return raw; + } + + + /** Expand out the knowledge helper stuff */ + public String expand(String pattern, + Parser context) { + + return this.knowledgeHelperFixer(pattern); + + } + +} Property changes on: trunk/labs/jbossrules/drools-core/src/main/java/org/drools/lang/ConsequenceExpander.java ___________________________________________________________________ Name: svn:eol-style + native Modified: trunk/labs/jbossrules/drools-core/src/main/java/org/drools/lang/Parser.java =================================================================== --- trunk/labs/jbossrules/drools-core/src/main/java/org/drools/lang/Parser.java 2006-01-31 00:06:25 UTC (rev 2228) +++ trunk/labs/jbossrules/drools-core/src/main/java/org/drools/lang/Parser.java 2006-01-31 07:22:09 UTC (rev 2229) @@ -19,41 +19,63 @@ /** * The one, the only DRL parser. + * Full of regex goodness. If you are not totally comfortable with regex, + * then please either look elsewhere, or put on your safety pants. * * @master Bob McWirther * @apprentice Michael Neale */ public class Parser { - private static Pattern PACKAGE_DECL = Pattern.compile( "\\s*package\\s*([^;]+);?\\s*" ); - private static Pattern IMPORT_STATEMENT = Pattern.compile( "\\s*import\\s*([^;]+);?\\s*" ); - private static Pattern APP_DATA_STATEMENT = Pattern.compile( "\\s*application-data\\s*([^;]+)\\s([^;]+);?\\s*" ); - private static Pattern RULE_DECL = Pattern.compile( "\\s*rule\\s*(.*[^\\s]+)\\s*" ); - private static Pattern FUNCTION_DECL = Pattern.compile("\\s*functions?\\s*"); - private static Pattern EXPANDER_STATEMENT = Pattern.compile("\\s*use\\s*expander\\s([^;]+);?\\s*"); - private static Pattern FACT_BINDING = Pattern.compile( "\\s*(\\w+)\\s*=>\\s*(.*)" ); - private static Pattern FIELD_BINDING = Pattern.compile( "\\s*(\\w+):(\\w+)\\s*" ); + + //---------------------------------------- + // General parser recogniser patterns + //---------------------------------------- + static Pattern PACKAGE_DECL = Pattern.compile( "\\s*package\\s*([^;]+);?\\s*" ); + static Pattern IMPORT_STATEMENT = Pattern.compile( "\\s*import\\s*([^;]+);?\\s*" ); + static Pattern APP_DATA_STATEMENT = Pattern.compile( "\\s*application-data\\s*([^;]+)\\s([^;]+);?\\s*" ); + static Pattern RULE_DECL = Pattern.compile( "\\s*rule\\s*(.*[^\\s]+)\\s*" ); + static Pattern FUNCTION_DECL = Pattern.compile("\\s*functions?\\s*"); + static Pattern EXPANDER_STATEMENT = Pattern.compile("\\s*use\\s*expander\\s([^;]+);?\\s*"); + static Pattern FACT_BINDING = Pattern.compile( "\\s*(\\w+)\\s*=>\\s*(.*)" ); + static Pattern FIELD_BINDING = Pattern.compile( "\\s*(\\w+):(\\w+)\\s*" ); - private static String COMMENT_1 = "#"; - private static String COMMENT_2 = "//"; + //---------------------------------------- + // Consequence handling patterns + //---------------------------------------- + static String KNOWLEDGE_HELPER_PFX = ""; //could also be: "drools\\." for "classic" mode. + static Pattern MODIFY = Pattern.compile("(.*)\\b" + KNOWLEDGE_HELPER_PFX + "modify\\s*\\(([^\\)]+)\\)(.*)"); + static Pattern ASSERT = Pattern.compile("(.*)\\b" + KNOWLEDGE_HELPER_PFX + "assert\\s*\\(([^\\)]+)\\)(.*)"); + static Pattern RETRACT = Pattern.compile("(.*)\\b" + KNOWLEDGE_HELPER_PFX + "retract\\s*\\(([^\\)]+)\\)(.*)"); + + //--------------------------------------- + // Constants + //--------------------------------------- + static String COMMENT_1 = "#"; + static String COMMENT_2 = "//"; + private BufferedReader reader; - private String packageDeclaration; private List imports; private Expander expander; + private Expander consequenceExpander; private List rules; private Map applicationData; private String functions; - private int lineNumber; - public Parser(Reader reader) { + + /** + * @param reader A reader to UTF-8 encoded (preferably) DRL source. + */ + public Parser(Reader reader) { this.reader = new BufferedReader( reader ); this.imports = new ArrayList(); this.rules = new ArrayList(); this.expander = null; this.applicationData = new HashMap(); + this.consequenceExpander = new ConsequenceExpander(); this.lineNumber = 0; } @@ -378,7 +400,11 @@ break; } consumeDiscard(); - line = maybeExpand( trimLine ); + + //we expand with special consequence expander first (for knowledge helper). + line = maybeExpand( + consequenceExpander.expand(trimLine, this) + ); consequence.append( line + "\n" ); } System.err.println( "begin consequence"); Added: trunk/labs/jbossrules/drools-core/src/test/java/org/drools/lang/ConsequenceExpanderTest.java =================================================================== --- trunk/labs/jbossrules/drools-core/src/test/java/org/drools/lang/ConsequenceExpanderTest.java 2006-01-31 00:06:25 UTC (rev 2228) +++ trunk/labs/jbossrules/drools-core/src/test/java/org/drools/lang/ConsequenceExpanderTest.java 2006-01-31 07:22:09 UTC (rev 2229) @@ -0,0 +1,54 @@ +package org.drools.lang; + +import junit.framework.TestCase; + +public class ConsequenceExpanderTest extends TestCase { + + public static ConsequenceExpander helper = new ConsequenceExpander(); + + public void testAddHandlerSimple() { + String result = helper.knowledgeHelperFixer("modify(myObject )"); + assertEquals("drools.modify(myObjectHandle, myObject)", result); + + result = helper.knowledgeHelperFixer("modify ( myObject )"); + assertEquals("drools.modify(myObjectHandle, myObject)", result); + } + + public void testAddHandlerComplex() { + String result = helper.knowledgeHelperFixer("something modify(myObject ); other"); + assertEquals("something drools.modify(myObjectHandle, myObject); other", result); + + result = helper.knowledgeHelperFixer("something modify (myObject )"); + assertEquals("something drools.modify(myObjectHandle, myObject)", result); + + result = helper.knowledgeHelperFixer(" modify(myObject ) x"); + assertEquals(" drools.modify(myObjectHandle, myObject) x", result); + + //should not touch, as it is not a stand alone word + result = helper.knowledgeHelperFixer("xxmodify(myObject ) x"); + assertEquals("xxmodify(myObject ) x", result); + + + } + + public void testMultipleMatches() { + String result = helper.knowledgeHelperFixer("modify(myObject) modify(myObject )"); + assertEquals("drools.modify(myObjectHandle, myObject) drools.modify(myObjectHandle, myObject)", result); + + result = helper.knowledgeHelperFixer("xxx modify(myObject ) modify(myObject ) modify(yourObject ) yyy"); + assertEquals("xxx drools.modify(myObjectHandle, myObject) drools.modify(myObjectHandle, myObject) drools.modify(yourObjectHandle, yourObject) yyy", result); + } + + public void testAllActions() { + String result = helper.knowledgeHelperFixer("assert(myObject ) modify(ourObject);\t retract(herObject)"); + assertEquals("drools.assert(myObjectHandle, myObject) drools.modify(ourObjectHandle, ourObject);\t drools.retract(herObjectHandle, herObject)", result); + } + + public void testLeaveLargeAlone() { + String original = "yeah yeah yeah this is a long() thing Person (name=='drools') modify a thing"; + String result = helper.knowledgeHelperFixer(original); + assertEquals(original, result); + } + + +} Property changes on: trunk/labs/jbossrules/drools-core/src/test/java/org/drools/lang/ConsequenceExpanderTest.java ___________________________________________________________________ Name: svn:eol-style + native Modified: trunk/labs/jbossrules/drools-core/src/test/java/org/drools/lang/one-rule.drl =================================================================== --- trunk/labs/jbossrules/drools-core/src/test/java/org/drools/lang/one-rule.drl 2006-01-31 00:06:25 UTC (rev 2228) +++ trunk/labs/jbossrules/drools-core/src/test/java/org/drools/lang/one-rule.drl 2006-01-31 07:22:09 UTC (rev 2229) @@ -27,6 +27,8 @@ then make a ruckus, damnit Really, you should + #following should be expanded using the consequence expander... + modify ( anObject ); end |
From: <jbo...@li...> - 2006-01-31 00:06:31
|
Author: mic...@jb... Date: 2006-01-30 19:06:25 -0500 (Mon, 30 Jan 2006) New Revision: 2228 Modified: trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/security/RepositorySecurityManager.java Log: doco improve Modified: trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/security/RepositorySecurityManager.java =================================================================== --- trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/security/RepositorySecurityManager.java 2006-01-30 08:15:07 UTC (rev 2227) +++ trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/security/RepositorySecurityManager.java 2006-01-31 00:06:25 UTC (rev 2228) @@ -94,6 +94,8 @@ * * If the user belongs to a group with the name "admin" then they * automatically get full rights. + * + * NOTE: THIS WILL BE ACCESSED BY THE NON ADMIN API. MUST BE ALLOWED TO BE ACCESSED AS SUCH. */ public ACLEnforcer getEnforcerForUser(String userId) { |
From: <jbo...@li...> - 2006-01-30 08:15:23
|
Author: mic...@jb... Date: 2006-01-30 03:15:07 -0500 (Mon, 30 Jan 2006) New Revision: 2227 Added: trunk/labs/jbossrules/drools-core/src/main/java/org/drools/lang/DefaultGrammar_en.properties trunk/labs/jbossrules/drools-core/src/test/java/org/drools/lang/application-data.drl trunk/labs/jbossrules/drools-core/src/test/java/org/drools/lang/functions.drl Modified: trunk/labs/jbossrules/drools-core/src/main/java/org/drools/lang/Parser.java trunk/labs/jbossrules/drools-core/src/test/java/org/drools/lang/ParserTest.java Log: functions and application data added Added: trunk/labs/jbossrules/drools-core/src/main/java/org/drools/lang/DefaultGrammar_en.properties =================================================================== --- trunk/labs/jbossrules/drools-core/src/main/java/org/drools/lang/DefaultGrammar_en.properties 2006-01-30 05:23:05 UTC (rev 2226) +++ trunk/labs/jbossrules/drools-core/src/main/java/org/drools/lang/DefaultGrammar_en.properties 2006-01-30 08:15:07 UTC (rev 2227) @@ -0,0 +1,45 @@ +###################################################### +# # +# This is the basic English grammar resourcebundle # +# which uses If/then sentences to describe rules. # +# The file contains configurables such as noun, and # +# verb mapping. It also contains rule to natural # +# language grammar mapping. # +# # +###################################################### +if=If +then=Then +set=Set +set.verb=to +set.adverb= +object.has=has +object.equal=is +object.not.has=doesn\'t have +object.not.equal=is not equal +object.adj= +possessive=\'s +conjunction=and +conjunction.separator=, + + +###################################################### +# # +# Grammar mapping properties. These mappings allow # +# the RuleML parser to translate Rule grammar to # +# natural language. We do this by providing a # +# simple map which tests the Rule grammar. Each # +# type of sentence should map to one type of RuleML # +# grammar. The mappings can not be ambiguous and # +# must have a one to one relationship. # +# # +###################################################### +# the types of grammar mappings +grammar.types=constant,bind.var,bind.shadow + +# start the grammar mapping +constant.rule= +constant.nl= +bind.var.rule= +bind.var.nl= +bind.shadow.rule= +bind.shadow.nl= Property changes on: trunk/labs/jbossrules/drools-core/src/main/java/org/drools/lang/DefaultGrammar_en.properties ___________________________________________________________________ Name: svn:eol-style + native Modified: trunk/labs/jbossrules/drools-core/src/main/java/org/drools/lang/Parser.java =================================================================== --- trunk/labs/jbossrules/drools-core/src/main/java/org/drools/lang/Parser.java 2006-01-30 05:23:05 UTC (rev 2226) +++ trunk/labs/jbossrules/drools-core/src/main/java/org/drools/lang/Parser.java 2006-01-30 08:15:07 UTC (rev 2227) @@ -4,12 +4,15 @@ import java.io.IOException; import java.io.Reader; import java.util.ArrayList; +import java.util.HashMap; import java.util.Iterator; import java.util.List; +import java.util.Map; import java.util.StringTokenizer; import java.util.regex.Matcher; import java.util.regex.Pattern; +import org.drools.rule.ApplicationData; import org.drools.rule.DuplicateRuleNameException; import org.drools.rule.Rule; import org.drools.rule.RuleConstructionException; @@ -24,26 +27,25 @@ private static Pattern PACKAGE_DECL = Pattern.compile( "\\s*package\\s*([^;]+);?\\s*" ); private static Pattern IMPORT_STATEMENT = Pattern.compile( "\\s*import\\s*([^;]+);?\\s*" ); + private static Pattern APP_DATA_STATEMENT = Pattern.compile( "\\s*application-data\\s*([^;]+)\\s([^;]+);?\\s*" ); private static Pattern RULE_DECL = Pattern.compile( "\\s*rule\\s*(.*[^\\s]+)\\s*" ); - + private static Pattern FUNCTION_DECL = Pattern.compile("\\s*functions?\\s*"); private static Pattern EXPANDER_STATEMENT = Pattern.compile("\\s*use\\s*expander\\s([^;]+);?\\s*"); - private static Pattern FACT_BINDING = Pattern.compile( "\\s*(\\w+)\\s*=>\\s*(.*)" ); private static Pattern FIELD_BINDING = Pattern.compile( "\\s*(\\w+):(\\w+)\\s*" ); + private static String COMMENT_1 = "#"; private static String COMMENT_2 = "//"; - private static String COMMENT_1 = "#"; - private BufferedReader reader; private String packageDeclaration; private List imports; private Expander expander; private List rules; - + private Map applicationData; + private String functions; - private int lineNumber; public Parser(Reader reader) { @@ -51,6 +53,7 @@ this.imports = new ArrayList(); this.rules = new ArrayList(); this.expander = null; + this.applicationData = new HashMap(); this.lineNumber = 0; } @@ -66,6 +69,10 @@ return rules; } + public String getFunctions() { + return functions; + } + Expander getExpander() { return expander; } @@ -73,13 +80,17 @@ public void parse() throws IOException, RuleConstructionException { prolog(); rules(); + } protected void prolog() throws IOException { packageDeclaration(); importStatements(); + applicationDataStatements(); expanderStatement(); - functions(); + functions(); + //BOB: do we want to allow flexible ordering of functions, etc? + //I think they should be at the end actually... } protected void packageDeclaration() throws IOException { @@ -101,6 +112,29 @@ } } + protected void applicationDataStatements() throws IOException { + while ( applicationDataStatement() ) { + //nike + } + } + + protected boolean applicationDataStatement() throws IOException { + String line = laDiscard(); + + if ( line == null ) { return false; } + + Matcher matcher = APP_DATA_STATEMENT.matcher( line ); + + if ( matcher.matches() ) { + consumeDiscard(); + + applicationData.put( matcher.group( 2 ).trim(), matcher.group( 1 ).trim() ); + return true; + } + + return false; + } + protected boolean importStatement() throws IOException { String line = laDiscard(); @@ -134,9 +168,45 @@ return false; } - protected void functions() { - - } + protected void functions() throws IOException { + String line = laDiscard(); + + if ( line == null ) { return; } + + Matcher matcher = FUNCTION_DECL.matcher( line ); + + if ( matcher.matches() ) { + consumeDiscard(); + //here we could put the semantic type declaration + } else { + return; //no functions, chopper... here, theres no functions. + } + + StringBuffer buffer = new StringBuffer(); + + while ( true ) { + line = laDiscard(); + if ( line == null ) { + throw new ParseException( "end of functions expected", lineNumber ); + } + String trimLine = line.trim(); + if ( trimLine.equals( "end" ) ) { + break; + } + consumeDiscard(); + line = maybeExpand( trimLine ); + buffer.append( line + "\n" ); + } + + if ( ! line.trim().equals( "end" ) ) { + throw new ParseException( "[end] of functions expected. But instead got: [" + line.trim() + "]", lineNumber); + } + + this.functions = buffer.toString(); + + consumeDiscard(); + } + protected void rules() throws IOException, RuleConstructionException { while ( rule() ) { @@ -170,7 +240,7 @@ line = laDiscard(); if ( ! line.trim().equals( "end" ) ) { - throw new ParseException( "[end] expected. But instead got: [" + line.trim() + "]", lineNumber); + throw new ParseException( "end of rule expected. But instead got: [" + line.trim() + "]", lineNumber); } consumeDiscard(); @@ -374,4 +444,11 @@ return line; } + /** + * @return A Map<<String>identifier, <String>Class> view of the app data + */ + public Map getApplicationData() { + return this.applicationData; + } + } Modified: trunk/labs/jbossrules/drools-core/src/test/java/org/drools/lang/ParserTest.java =================================================================== --- trunk/labs/jbossrules/drools-core/src/test/java/org/drools/lang/ParserTest.java 2006-01-30 05:23:05 UTC (rev 2226) +++ trunk/labs/jbossrules/drools-core/src/test/java/org/drools/lang/ParserTest.java 2006-01-30 08:15:07 UTC (rev 2227) @@ -2,6 +2,8 @@ import java.io.InputStream; import java.io.InputStreamReader; +import java.util.List; +import java.util.Map; import junit.framework.TestCase; @@ -58,6 +60,23 @@ assertEquals("cheese_rules", ((Rule)parser.getRules().get(0)).getName() ); } + + public void test_with_appdata() throws Exception { + Parser parser = parser ( "application-data.drl" ); + parser.parse(); + Map appData = parser.getApplicationData(); + assertEquals(2, appData.size()); + assertEquals("MyObject", appData.get("me")); + assertEquals("YourObject", appData.get("you")); + } + + public void test_with_functions() throws Exception { + Parser parser = parser ( "functions.drl" ); + parser.parse(); + assertNotNull(parser.getFunctions()); + assertTrue(parser.getFunctions().indexOf("System.out.println(string);") > -1); + + } protected Parser parser(String name) { InputStream in = getClass().getResourceAsStream( name ); Added: trunk/labs/jbossrules/drools-core/src/test/java/org/drools/lang/application-data.drl =================================================================== --- trunk/labs/jbossrules/drools-core/src/test/java/org/drools/lang/application-data.drl 2006-01-30 05:23:05 UTC (rev 2226) +++ trunk/labs/jbossrules/drools-core/src/test/java/org/drools/lang/application-data.drl 2006-01-30 08:15:07 UTC (rev 2227) @@ -0,0 +1,16 @@ +# showing application data + +import java.lang.String +import java.util.Random + +#setup application data here (optional semi colons, as always). +application-data MyObject me; +application-data YourObject you + +#app data should come after imports, before functions + + + + + + Property changes on: trunk/labs/jbossrules/drools-core/src/test/java/org/drools/lang/application-data.drl ___________________________________________________________________ Name: svn:eol-style + native Added: trunk/labs/jbossrules/drools-core/src/test/java/org/drools/lang/functions.drl =================================================================== --- trunk/labs/jbossrules/drools-core/src/test/java/org/drools/lang/functions.drl 2006-01-30 05:23:05 UTC (rev 2226) +++ trunk/labs/jbossrules/drools-core/src/test/java/org/drools/lang/functions.drl 2006-01-30 08:15:07 UTC (rev 2227) @@ -0,0 +1,29 @@ +# shows functions + +import java.lang.String + +functions + + public static void log(String string) { + System.out.println(string); + } + +end + + +rule something + when + #nothing + then + #nothing +end + +rule one more thing + when + #nothing + then + #nothing +end + + + Property changes on: trunk/labs/jbossrules/drools-core/src/test/java/org/drools/lang/functions.drl ___________________________________________________________________ Name: svn:eol-style + native |
From: <jbo...@li...> - 2006-01-30 05:23:12
|
Author: mic...@jb... Date: 2006-01-30 00:23:05 -0500 (Mon, 30 Jan 2006) New Revision: 2226 Modified: trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/RuleSetDef.java Log: doco change only Modified: trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/RuleSetDef.java =================================================================== --- trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/RuleSetDef.java 2006-01-30 05:09:02 UTC (rev 2225) +++ trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/RuleSetDef.java 2006-01-30 05:23:05 UTC (rev 2226) @@ -319,6 +319,8 @@ * * IMPORTANT: once a new version is created, the RuleSet should be saved and * then loaded fresh, which will hide the non working versions of the rules. + * + * TODO: refactor this to only be called from the manager, and also for it to copy old permissions. */ public void createNewVersion(String comment) { |
From: <jbo...@li...> - 2006-01-30 05:09:10
|
Author: mic...@jb... Date: 2006-01-30 00:09:02 -0500 (Mon, 30 Jan 2006) New Revision: 2225 Modified: trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/security/ACLResource.java trunk/labs/jbossrules/drools-repository/src/main/resources/org/drools/repository/RuleDef.hbm.xml Log: added index Modified: trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/security/ACLResource.java =================================================================== --- trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/security/ACLResource.java 2006-01-30 04:10:00 UTC (rev 2224) +++ trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/security/ACLResource.java 2006-01-30 05:09:02 UTC (rev 2225) @@ -7,4 +7,6 @@ */ public interface ACLResource { + //This may be modified to allow surrogate IDs for permissioning purposes. + } Modified: trunk/labs/jbossrules/drools-repository/src/main/resources/org/drools/repository/RuleDef.hbm.xml =================================================================== --- trunk/labs/jbossrules/drools-repository/src/main/resources/org/drools/repository/RuleDef.hbm.xml 2006-01-30 04:10:00 UTC (rev 2224) +++ trunk/labs/jbossrules/drools-repository/src/main/resources/org/drools/repository/RuleDef.hbm.xml 2006-01-30 05:09:02 UTC (rev 2225) @@ -14,8 +14,11 @@ </id> <version name="lockingVersion" column="LOCKING_VERSION" /> - <property name="name" column="RULE_NAME" length="64" /> - <property name="versionNumber" column="VERSION_NUMBER" /> + + <property name="name" column="RULE_NAME" length="64" index="true" /> + <property name="versionNumber" column="VERSION_NUMBER" /> + <property name="historicalId" column="HISTORICAL_ID"/> + <property name="content" type="text" column="RULE_CONTENT" /> <property name="status" column="STATUS" length="32" /> <property name="checkedOut" column="CHECKED_OUT" /> @@ -24,7 +27,6 @@ <property name="documentation" column="DOCUMENTATION" type="text"/> <property name="effectiveDate" column="EFFECTIVE_DATE" /> <property name="expiryDate" column="EXPIRY_DATE"/> - <property name="historicalId" column="HISTORICAL_ID"/> <property name="historicalRecord" column="HISTORICAL_RECORD_FLAG"/> <property name="owningRuleSetName" column="OWNING_RULESET_NAME" /> <property name="lastSavedByUser" column="LAST_SAVED_USER" /> |
Author: mic...@jb... Date: 2006-01-29 23:10:00 -0500 (Sun, 29 Jan 2006) New Revision: 2224 Added: trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/db/RepositoryConfig.java trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/security/ trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/security/ACLEnforcer.java trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/security/ACLResource.java trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/security/AssetPermission.java trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/security/PermissionGroup.java trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/security/RepositorySecurityException.java trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/security/RepositorySecurityManager.java trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/security/RepositoryUser.java trunk/labs/jbossrules/drools-repository/src/main/resources/org/drools/repository/db/ trunk/labs/jbossrules/drools-repository/src/main/resources/org/drools/repository/db/RepositoryConfig.hbm.xml trunk/labs/jbossrules/drools-repository/src/main/resources/org/drools/repository/security/ trunk/labs/jbossrules/drools-repository/src/main/resources/org/drools/repository/security/AssetPermission.hbm.xml trunk/labs/jbossrules/drools-repository/src/main/resources/org/drools/repository/security/PermissionGroup.hbm.xml trunk/labs/jbossrules/drools-repository/src/main/resources/org/drools/repository/security/RepositoryUser.hbm.xml trunk/labs/jbossrules/drools-repository/src/test/java/org/drools/repository/security/ trunk/labs/jbossrules/drools-repository/src/test/java/org/drools/repository/security/ACLEnforcerTest.java trunk/labs/jbossrules/drools-repository/src/test/java/org/drools/repository/security/AssetPermissionTest.java trunk/labs/jbossrules/drools-repository/src/test/java/org/drools/repository/security/RepositorySecurityManagerTest.java Modified: trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/FunctionDef.java trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/RepositoryManagerImpl.java trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/RuleDef.java trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/RuleSetAttachment.java trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/RuleSetDef.java trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/db/HibernateUtil.java trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/db/RepoProxyHandler.java trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/db/StoreInterceptor.java trunk/labs/jbossrules/drools-repository/src/test/java/org/drools/repository/IntegrationTest.java trunk/labs/jbossrules/drools-repository/src/test/java/org/drools/repository/RulePersistenceTest.java trunk/labs/jbossrules/drools-repository/src/test/java/org/drools/repository/db/PersistentCase.java Log: added fine grained ACL (including instance basedsecurity) Modified: trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/FunctionDef.java =================================================================== --- trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/FunctionDef.java 2006-01-29 19:56:59 UTC (rev 2223) +++ trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/FunctionDef.java 2006-01-30 04:10:00 UTC (rev 2224) @@ -1,6 +1,7 @@ package org.drools.repository; import org.drools.repository.db.IVersionable; +import org.drools.repository.security.ACLResource; /** * A FunctionDef contains the definition of a function that is used in one or more rules. @@ -10,7 +11,7 @@ */ public class FunctionDef extends Asset implements - IVersionable { + IVersionable, ACLResource { private static final long serialVersionUID = -7585928690157539970L; Modified: trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/RepositoryManagerImpl.java =================================================================== --- trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/RepositoryManagerImpl.java 2006-01-29 19:56:59 UTC (rev 2223) +++ trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/RepositoryManagerImpl.java 2006-01-30 04:10:00 UTC (rev 2224) @@ -268,7 +268,7 @@ session.disableFilter( "workingVersionFilter" ); } - /** Sets the current user principal for auditing, and access control purposes */ + /** Sets the current user principal for checkin/out purposes. */ public void setCurrentUser(Principal user) { this.currentUser = user; } Modified: trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/RuleDef.java =================================================================== --- trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/RuleDef.java 2006-01-29 19:56:59 UTC (rev 2223) +++ trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/RuleDef.java 2006-01-30 04:10:00 UTC (rev 2224) @@ -7,10 +7,11 @@ import org.drools.repository.db.ISaveHistory; import org.drools.repository.db.IVersionable; +import org.drools.repository.security.ACLResource; public class RuleDef extends Asset implements - ISaveHistory { + ISaveHistory, ACLResource { private static final long serialVersionUID = -677781085801764266L; Modified: trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/RuleSetAttachment.java =================================================================== --- trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/RuleSetAttachment.java 2006-01-29 19:56:59 UTC (rev 2223) +++ trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/RuleSetAttachment.java 2006-01-30 04:10:00 UTC (rev 2224) @@ -5,6 +5,7 @@ import org.drools.repository.db.ISaveHistory; import org.drools.repository.db.IVersionable; +import org.drools.repository.security.ACLResource; /** @@ -20,7 +21,7 @@ * @author <a href="mailto:mic...@gm..."> Michael Neale</a> * */ -public class RuleSetAttachment extends Asset implements ISaveHistory { +public class RuleSetAttachment extends Asset implements ISaveHistory, ACLResource { private static final long serialVersionUID = 7474038734785975202L; Modified: trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/RuleSetDef.java =================================================================== --- trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/RuleSetDef.java 2006-01-29 19:56:59 UTC (rev 2223) +++ trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/RuleSetDef.java 2006-01-30 04:10:00 UTC (rev 2224) @@ -5,6 +5,7 @@ import java.util.Set; import org.drools.repository.db.IVersionable; +import org.drools.repository.security.ACLResource; /** * The ruleset definition contains a grouping of rules for editing/release. The @@ -29,7 +30,7 @@ */ public class RuleSetDef extends Asset implements - Comparable { + Comparable, ACLResource { private static final long serialVersionUID = 608068118653708104L; private String name; Modified: trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/db/HibernateUtil.java =================================================================== --- trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/db/HibernateUtil.java 2006-01-29 19:56:59 UTC (rev 2223) +++ trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/db/HibernateUtil.java 2006-01-30 04:10:00 UTC (rev 2224) @@ -10,6 +10,9 @@ import org.drools.repository.RuleSetDef; import org.drools.repository.RuleSetVersionInfo; import org.drools.repository.Tag; +import org.drools.repository.security.AssetPermission; +import org.drools.repository.security.RepositoryUser; +import org.drools.repository.security.PermissionGroup; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; @@ -52,9 +55,8 @@ public static Configuration getConfiguration() { Configuration cfg = new Configuration(); cfg.setInterceptor( new StoreInterceptor() ); + registerPersistentClasses( cfg ); -// cfg.setProperty("connection.username", "sa"); -// cfg.setProperty("connection.password", ""); cfg.configure(DROOLS_REPOSITORY_CONFIG); return cfg; } @@ -71,7 +73,11 @@ .addClass(RuleSetDef.class) .addClass(RuleSetAttachment.class) .addClass(RuleSetVersionInfo.class) - .addClass(ImportDef.class); + .addClass(ImportDef.class) + .addClass(AssetPermission.class) + .addClass(PermissionGroup.class) + .addClass(RepositoryUser.class) + .addClass(RepositoryConfig.class); } public static SessionFactory getSessionFactory() { Modified: trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/db/RepoProxyHandler.java =================================================================== --- trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/db/RepoProxyHandler.java 2006-01-29 19:56:59 UTC (rev 2223) +++ trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/db/RepoProxyHandler.java 2006-01-30 04:10:00 UTC (rev 2224) @@ -10,6 +10,8 @@ import org.drools.repository.RepositoryException; import org.drools.repository.RepositoryManagerImpl; +import org.drools.repository.security.ACLEnforcer; +import org.drools.repository.security.RepositorySecurityManager; import org.hibernate.Session; import org.hibernate.Transaction; @@ -40,6 +42,7 @@ private Session session = null; //for stateful sessions private boolean stateful = false; private Principal currentUser; //the user context, for auditing (optional) + private ACLEnforcer aclEnforcer; //the users ACL rights, if applicable. /** * This is essentially for stateless repository access. @@ -120,9 +123,11 @@ private void cleanup() { + this.repoImpl.injectSession(null); StoreInterceptor.setCurrentConnection(null); StoreInterceptor.setCurrentUser(null); + StoreInterceptor.setCurrentACLEnforcer(null); } /** @@ -164,6 +169,8 @@ private void configure(Session session, Principal user) { StoreInterceptor.setCurrentConnection( session.connection() ); StoreInterceptor.setCurrentUser( user ); + StoreInterceptor.setCurrentACLEnforcer( aclEnforcer ); + repoImpl.enableHistoryFilter( session ); repoImpl.injectSession( session ); this.repoImpl.setCurrentUser(currentUser); @@ -181,9 +188,18 @@ } } - /** The current user for auditing and control purposes. */ + /** + * The current user for auditing and control purposes. + * Also loads the ACL if applicable. */ public void setCurrentUser(Principal user) { this.currentUser = user; + if (user != null) { + RepositorySecurityManager mgr = new RepositorySecurityManager(); + if (mgr.isSecurityEnabled()) { + + aclEnforcer = mgr.getEnforcerForUser(user.getName()); + } + } } Added: trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/db/RepositoryConfig.java =================================================================== --- trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/db/RepositoryConfig.java 2006-01-29 19:56:59 UTC (rev 2223) +++ trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/db/RepositoryConfig.java 2006-01-30 04:10:00 UTC (rev 2224) @@ -0,0 +1,28 @@ +package org.drools.repository.db; + +/** + * Just an entity for misc repo config items. + * @author <a href="mailto:mic...@gm..."> Michael Neale</a> + * + */ +public class RepositoryConfig { + + private String key; + private String value; + + public String getKey() { + return key; + } + public void setKey(String key) { + this.key = key; + } + public String getValue() { + return value; + } + public void setValue(String value) { + this.value = value; + } + + + +} Property changes on: trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/db/RepositoryConfig.java ___________________________________________________________________ Name: svn:eol-style + native Modified: trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/db/StoreInterceptor.java =================================================================== --- trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/db/StoreInterceptor.java 2006-01-29 19:56:59 UTC (rev 2223) +++ trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/db/StoreInterceptor.java 2006-01-30 04:10:00 UTC (rev 2224) @@ -6,6 +6,9 @@ import java.util.Date; import org.drools.repository.Asset; +import org.drools.repository.security.ACLEnforcer; +import org.drools.repository.security.ACLResource; +import org.drools.repository.security.AssetPermission; import org.hibernate.EmptyInterceptor; import org.hibernate.LockMode; import org.hibernate.Session; @@ -21,8 +24,7 @@ * * Note that it will also save audit information about whom saved the data. * - * This can be extended in future to provide additional audit trail information, or instance based security - * (to enforce ACLs on save etc). + * ACLs are also enforced here. * * @author <a href="mailto:mic...@gm..."> Michael Neale</a> */ @@ -37,6 +39,9 @@ //we also need the current user if it has been set. private static ThreadLocal currentUser = new ThreadLocal(); + //for enforcing ACLs + private static ThreadLocal currentACLEnforcer = new ThreadLocal(); + /** * Create historical records, and log events. */ @@ -46,27 +51,86 @@ Object[] previousState, String[] propertyNames, Type[] types) { + + checkACLAllowed( entity, id, "You are not authorized to save this asset.", + AssetPermission.WRITE ); + checkACLDenied( entity, id, "You have been denied authority to save this asset.", + AssetPermission.DENY_WRITE); + if ( entity instanceof ISaveHistory ) { handleSaveHistory( entity ); } - return handleUserSaveInfo( entity, currentState, propertyNames ); } + + public boolean onLoad(Object entity, + Serializable id, + Object[] state, + String[] propertyNames, + Type[] types) + { + checkACLAllowed(entity, id, "You are not authorized to load this asset.", + AssetPermission.READ); + checkACLDenied(entity, id, "You have been blocked from loading this asset.", + AssetPermission.DENY_READ); + return false; + } + /** record who and when */ public boolean onSave(Object entity, Serializable id, Object[] currentState, String[] propertyNames, Type[] types) { - + return handleUserSaveInfo( entity, currentState, propertyNames ); } + + public void onDelete(Object entity, + Serializable id, + Object[] arg2, + String[] arg3, + Type[] arg4) { + checkACLAllowed(entity, id, "You are not authorized to delete this asset.", + AssetPermission.DELETE); + checkACLDenied(entity, id, "You have been disallowed from deleting this asset.", + AssetPermission.DENY_DELETE); + } + + + + /** + * Check that the ACL allows the user the appropriate permission. + */ + private void checkACLAllowed(Object entity, + Serializable assetId, String failMessage, int permission) { + if (! (entity instanceof ACLResource)) return; + ACLEnforcer enforcer = (ACLEnforcer) currentACLEnforcer.get(); + if (enforcer != null) { + //TODO: make it more flexible in what the "ID" is - may be rulename for instance?? + enforcer.checkAllowed(entity, assetId, permission, failMessage); + } + } + + /** + * Check for explicitly denied ACL entries. + */ + private void checkACLDenied(Object entity, + Serializable assetId, String failMessage, int permission) { + if (! (entity instanceof ACLResource)) return; + ACLEnforcer enforcer = (ACLEnforcer) currentACLEnforcer.get(); + if (enforcer != null) { + enforcer.checkDenied(entity, assetId, permission, failMessage); + } + } + + /** * This will load up the old copy, and save it as a history record @@ -83,9 +147,9 @@ ISaveHistory copy = (ISaveHistory) prev.copy(); copy.setHistoricalId( versionable.getId() ); copy.setHistoricalRecord( true ); - //session.beginTransaction(); + session.save( copy ); - //session.getTransaction().commit(); + session.flush(); session.close(); } @@ -107,6 +171,11 @@ currentUser.set(user); } + /** Set the ACL enforcer to enforce access rules for the current user */ + public static void setCurrentACLEnforcer(ACLEnforcer enforcer) { + currentACLEnforcer.set(enforcer); + } + private SessionFactory getSessionFactory() { return HibernateUtil.getSessionFactory(); } @@ -137,4 +206,7 @@ } + + + } Added: trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/security/ACLEnforcer.java =================================================================== --- trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/security/ACLEnforcer.java 2006-01-29 19:56:59 UTC (rev 2223) +++ trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/security/ACLEnforcer.java 2006-01-30 04:10:00 UTC (rev 2224) @@ -0,0 +1,99 @@ +package org.drools.repository.security; + +import java.io.Serializable; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; + +/** + * This class enforcers ACL rights on an asset, for an individual user + * who is interacting with the repository. + * + * @author <a href="mailto:mic...@gm..."> Michael Neale</a> + */ +public class ACLEnforcer { + + //this is basically a map of AssetTypes. Each AssetType has a map, keyed on assetId. Each item in this + //inner map is an AssetPermission object. + public Map permissionMap; + + public ACLEnforcer() { + permissionMap = new HashMap(); + } + + /** + * Config it up from a set of AssetPermissions. + * + * @param permissions + */ + public void setPermissions(Set permissions) { + for ( Iterator iter = permissions.iterator(); iter.hasNext(); ) { + AssetPermission perm = (AssetPermission) iter.next(); + Object existingPermMap = permissionMap.get(perm.getAssetType()); + if (existingPermMap != null) { + Map existing = (Map) existingPermMap; + if (existing.containsKey(perm.getAssetId())) { //add to existing permission + AssetPermission current = (AssetPermission) existing.get(perm.getAssetId()); + current.setPermission(current.getPermission() | perm.getPermission()); + } else { + existing.put(perm.getAssetId(), perm); + } + } else { + Map existing = new HashMap(); + existing.put(perm.getAssetId(), perm); + permissionMap.put(perm.getAssetType(), existing); + } + } + } + + /** + * This will check for the positive permission for the given asset. + */ + public boolean isAllowed(String assetType, Serializable assetId, int permission) { + Map perms = (Map) permissionMap.get(assetType); + if (perms == null) return false; + + AssetPermission perm = (AssetPermission) perms.get(assetId); + if (perm == null) return false; + return perm.hasPermission(permission); + } + + /** + * Checks for a particular DENY* permission has been set. (Negative permission). + */ + public boolean isDenied(String assetType, Serializable assetId, int permission) { + return isAllowed(assetType, assetId, permission); + } + + /** + * This will throw an exception if it is not permitted. + * It will also check for "global" permissiong (ALL_INSTANCES). + * @param entity The entity being checked, only used to get class name. + */ + public void checkAllowed(Object entity, Serializable assetId, int permission, String failMessage) { + String assetType = entity.getClass().getName(); + + boolean allowed = this.isAllowed(assetType, AssetPermission.ALL_INSTANCES, permission) + || this.isAllowed(assetType, assetId, permission); + if (!allowed) { + throw new RepositorySecurityException(failMessage); + } + + } + + /** + * This will throw an exception if it has been explicitly denied. + * Obviously only applies to negative "DENY_*" permissions. + * @param entity The entity being checked, only used to get class name. + */ + public void checkDenied(Object entity, Serializable assetId, int permission, String failMessage) { + String assetType = entity.getClass().getName(); + boolean denied = this.isDenied(assetType, assetId, permission) || + this.isDenied(assetType, AssetPermission.ALL_INSTANCES, permission); + if (denied) { + throw new RepositorySecurityException(failMessage); + } + } + +} Property changes on: trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/security/ACLEnforcer.java ___________________________________________________________________ Name: svn:eol-style + native Added: trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/security/ACLResource.java =================================================================== --- trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/security/ACLResource.java 2006-01-29 19:56:59 UTC (rev 2223) +++ trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/security/ACLResource.java 2006-01-30 04:10:00 UTC (rev 2224) @@ -0,0 +1,10 @@ +package org.drools.repository.security; + +/** + * A simple marker interface to indicate that an asset is ACL controlled. + * @author <a href="mailto:mic...@gm..."> Michael Neale</a> + * + */ +public interface ACLResource { + +} Property changes on: trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/security/ACLResource.java ___________________________________________________________________ Name: svn:eol-style + native Added: trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/security/AssetPermission.java =================================================================== --- trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/security/AssetPermission.java 2006-01-29 19:56:59 UTC (rev 2223) +++ trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/security/AssetPermission.java 2006-01-30 04:10:00 UTC (rev 2224) @@ -0,0 +1,110 @@ +package org.drools.repository.security; + +import java.io.Serializable; +import java.security.acl.Permission; + +import org.drools.repository.Asset; + + +/** + * This represents permissions on an asset. + * This is like an ACL Entry. + * The user group maps this to a named group of users. + * + * Permissions may be on instances, or globally, or to a whole class of assets. + * + * @author <a href="mailto:mic...@gm..."> Michael Neale</a> + * TODO: make this work with "partial" rules for matching IDs. ie can be more then just ID. + * May mean that ACLResource needs to have a method for getting the ID for security purposes. + */ +public class AssetPermission implements Permission { + + private Long id; + + public static final int READ = 1; + public static final int WRITE = 2; + public static final int DELETE = 4; + + public static final int DENY_READ = 8; + public static final int DENY_WRITE = 16; + public static final int DENY_DELETE = 32; + + /** + * Use this when you want it to apply to ALL instances. + */ + public static final Serializable ALL_INSTANCES = new Long(-1); + + private String assetType; + private Serializable assetId; + private int permission = READ; + + /** + * + * @param assetType A string representing the full classname of the asset to be secured. + * @param assetId The id of the asset. Can be ALL_INSTANCES to apply to whole class. + * @param permission The permission (can be allow or deny, as appropriate). + */ + public AssetPermission(String assetType, + Serializable assetId, + int permission) { + + this.assetType = assetType; + this.assetId = assetId; + this.permission = permission; + } + + /** + * Convenience constructor - reads in the id and class name from the object. + */ + public AssetPermission(Asset asset, int permission) { + if (!(asset instanceof ACLResource)) { + throw new IllegalArgumentException("Asset is not an ACL type resource."); + } + this.assetId = asset.getId(); + this.assetType = asset.getClass().getName(); + this.permission = permission; + } + + AssetPermission() {} + + public Serializable getAssetId() { + return assetId; + } + public void setAssetId(Serializable assetId) { + this.assetId = assetId; + } + public String getAssetType() { + return assetType; + } + public void setAssetType(String assetType) { + this.assetType = assetType; + } + + public int getPermission() { + return permission; + } + public void setPermission(int permission) { + this.permission = permission; + } + + public Long getId() { + return id; + } + private void setId(Long id) { + this.id = id; + } + + /** Do bitwise comparison to check permission */ + public boolean hasPermission(int permission) { + return permission == (this.permission & permission); + } + + + public String toString() { + return "AssetPermission [" + assetType + "," + assetId + "," + permission + "]"; + } + + + + +} Property changes on: trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/security/AssetPermission.java ___________________________________________________________________ Name: svn:eol-style + native Added: trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/security/PermissionGroup.java =================================================================== --- trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/security/PermissionGroup.java 2006-01-29 19:56:59 UTC (rev 2223) +++ trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/security/PermissionGroup.java 2006-01-30 04:10:00 UTC (rev 2224) @@ -0,0 +1,111 @@ +package org.drools.repository.security; + +import java.util.HashSet; +import java.util.Set; + +/** + * A user collection is a loose grouping of users for the purposes of access control lists on + * resources (ie rules, functions etc). + * Permissions are assigned to user groups (not to users directly). + * + * User groups have users assigned. + * (note: in future, user group membership may be provided externally). + * The group membership may be determined externally to the repo, which means the + * repo will need to be passed a context of what groups the current user + * is a member of for the purposes of permissions (as they are all loaded up into + * the ACLEnforcer object which is used by the interceptor). + * + * These groupings will most likely not correspond to LDAP style groups however. These + * groups exist for the purpose of setting roles in the repository. + * + * These provide collections of granted permissions, and a set of users for whom these permissions apply. + * A user may belong to many of these groups, their permissions are the sum of them. + * + * PermissionGroups are not nested, they are simple structures. + * @author <a href="mailto:mic...@gm..."> Michael Neale</a> + */ +public class PermissionGroup { + + private Long id; + + private Set userIdentities = new HashSet(); + private Set assetPermissions = new HashSet(); + + private String name; + private String description; + + public PermissionGroup() { + + } + + public String getDescription() { + return description; + } + + public void setDescription(String description) { + this.description = description; + } + + public PermissionGroup(String name) { + this.name = name; + } + + public Set getUserIdentities() { + return userIdentities; + } + + void setUserIdentities(Set userIdentities) { + this.userIdentities = userIdentities; + } + + /** + * Add a users identity to this group. + * Note that if groups are managed externally, then this will not need to be used. + * All that is needed is to know what names groups a user belongs to, + * and all the relevant permissions can be loaded. + */ + public void addUserIdentity(String userId) { + this.userIdentities.add( new RepositoryUser(userId) ); + } + + public void addPermission(AssetPermission permission) { + this.assetPermissions.add(permission); + } + + public Set getAssetPermissions() { + return assetPermissions; + } + + + + void setAssetPermissions(Set assetPermissions) { + this.assetPermissions = assetPermissions; + } + + + + public Long getId() { + return id; + } + + + + void setId(Long id) { + this.id = id; + } + + + + public String getName() { + return name; + } + + + + void setName(String name) { + this.name = name; + } + + + +} Property changes on: trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/security/PermissionGroup.java ___________________________________________________________________ Name: svn:eol-style + native Added: trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/security/RepositorySecurityException.java =================================================================== --- trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/security/RepositorySecurityException.java 2006-01-29 19:56:59 UTC (rev 2223) +++ trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/security/RepositorySecurityException.java 2006-01-30 04:10:00 UTC (rev 2224) @@ -0,0 +1,14 @@ +package org.drools.repository.security; + +import org.drools.repository.RepositoryException; + +public class RepositorySecurityException extends RepositoryException { + + private static final long serialVersionUID = -6726082443948637629L; + + public RepositorySecurityException(String message) { + super( message ); + + } + +} Property changes on: trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/security/RepositorySecurityException.java ___________________________________________________________________ Name: svn:eol-style + native Added: trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/security/RepositorySecurityManager.java =================================================================== --- trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/security/RepositorySecurityManager.java 2006-01-29 19:56:59 UTC (rev 2223) +++ trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/security/RepositorySecurityManager.java 2006-01-30 04:10:00 UTC (rev 2224) @@ -0,0 +1,201 @@ +package org.drools.repository.security; + +import java.io.Serializable; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Set; + +import org.drools.repository.db.HibernateUtil; +import org.drools.repository.db.RepositoryConfig; +import org.hibernate.Session; + +/** + * Provides an administrative interface for setting security parameters. + * Services in this interface should only be made available to trusted + * personnel. + * + * @author <a href="mailto:mic...@gm..."> Michael Neale</a> + * + */ +public class RepositorySecurityManager { + + + + private static final String SECURITY_ENABLED = "security.enabled"; + //sessions for the manager are stateful + private Session session; + + /** + * Creates a new instance with a new session. + * Once a unit of work has completed, commit() the changes. + */ + public RepositorySecurityManager() { + session = HibernateUtil.getSessionFactory().getCurrentSession(); + session.beginTransaction(); + } + + public void saveGroup(PermissionGroup group) { + session.merge(group); + } + + public PermissionGroup loadGroup(String groupName) { + //Note, group membership maybe determined outside the repo. + //in which case, this method should not be used to determine what groups a user + //belongs to. + Object result = session.createQuery("from PermissionGroup where name = :name") + .setString("name", groupName).uniqueResult(); + + return (PermissionGroup) result; + } + + /** List groups by userId */ + public List listGroups(String userId) { + List result = session.createQuery( + "select ug from PermissionGroup as ug join ug.userIdentities as users " + + "where users.userId = :userId") + .setString("userId", userId).list(); + + return result; + } + + /** List all groups */ + public List listGroups() { + List result = session.createQuery("from PermissionGroup").list(); + return result; + } + + + /** Load a super set of all users permissions, based on their group membership */ + public Set loadPermissionsForUser(String userId) { + Set permissions = new HashSet(); + List groups = listGroups(userId); + for ( Iterator iter = groups.iterator(); iter.hasNext(); ) { + PermissionGroup group = (PermissionGroup) iter.next(); + permissions.addAll(group.getAssetPermissions()); + } + return permissions; + } + + + /** + * Load the permission set for a group. This may be useful if the group + * and user relationship is outside the repository database. + */ + public Set loadPermissionsForGroup(String groupName) { + PermissionGroup group = loadGroup(groupName); + return group.getAssetPermissions(); + } + + + /** + * Loads up the enforcer for the specified user based on the repo database + * knowledge of what groups they belong to. + * + * If the user belongs to a group with the name "admin" then they + * automatically get full rights. + */ + public ACLEnforcer getEnforcerForUser(String userId) { + + List groups = listGroups(userId); + Set permissions = new HashSet(); + for ( Iterator iter = groups.iterator(); iter.hasNext(); ) { + PermissionGroup group = (PermissionGroup) iter.next(); + if (group.getName().equalsIgnoreCase("admin")) { + return new SuACLEnforcer(); + } + permissions.addAll(group.getAssetPermissions()); + } + + ACLEnforcer enforcer = new ACLEnforcer(); + enforcer.setPermissions(permissions); + return enforcer; + } + + + public void enableSecurity(boolean on) { + RepositoryConfig config = new RepositoryConfig(); + config.setKey(SECURITY_ENABLED); + config.setValue(Boolean.toString(on)); + + session.merge(config); + } + + public boolean isSecurityEnabled() { + + RepositoryConfig config = (RepositoryConfig) session.get(RepositoryConfig.class, SECURITY_ENABLED); + if (config == null) return false; + return (Boolean.parseBoolean(config.getValue())); + } + + public void commitAndClose() { + session.getTransaction().commit(); + } + + /** + * This will add a permission to the named group. + * If the group doesn't exist, it will create it. + * + * This can be used in tandem with loadPermissionForGroup + * to determine permissions when group membership is maintained outside + * of the repository database (such as in LDAP). + * + */ + public void addPermissionToGroup(String groupName, AssetPermission permission) { + PermissionGroup group = this.loadGroup(groupName); + if (group == null) { + group = new PermissionGroup(groupName); + } + group.addPermission(permission); + this.saveGroup(group); + } + + public void addUserToGroup(String userName, String groupName) { + PermissionGroup group = this.loadGroup(groupName); + if (group == null) { + group = new PermissionGroup(groupName); + } + group.addUserIdentity(userName); + session.merge(group); + } + + /** + * This is for super users. Lets them get away with anything. + * + * @author <a href="mailto:mic...@gm..."> Michael Neale</a> + */ + static class SuACLEnforcer extends ACLEnforcer { + + public void checkAllowed(Object entity, + Serializable id, + int permission, + String failMessage) { + + } + + public void checkDenied(Object entity, + Serializable id, + int permission, + String failMessage) { + } + + public boolean isAllowed(String assetType, + Serializable id, + int permission) { + return true; + } + + public boolean isDenied(String assetType, + Serializable id, + int permission) { + return false; + + } + + + + + + } + +} Property changes on: trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/security/RepositorySecurityManager.java ___________________________________________________________________ Name: svn:eol-style + native Added: trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/security/RepositoryUser.java =================================================================== --- trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/security/RepositoryUser.java 2006-01-29 19:56:59 UTC (rev 2223) +++ trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/security/RepositoryUser.java 2006-01-30 04:10:00 UTC (rev 2224) @@ -0,0 +1,30 @@ +package org.drools.repository.security; + +import java.security.Principal; + +/** Simple wrapper for user identity for the repository to enforce ACLs */ +public class RepositoryUser + implements + Principal { + + private String userId; + + public RepositoryUser(String userId) { + this.userId = userId; + } + + RepositoryUser() {} + + public String getName() { + return userId; + } + + public String getUserId() { + return this.userId; + } + + void setUserId(String id) { + this.userId = id; + } + +} Property changes on: trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/security/RepositoryUser.java ___________________________________________________________________ Name: svn:eol-style + native Added: trunk/labs/jbossrules/drools-repository/src/main/resources/org/drools/repository/db/RepositoryConfig.hbm.xml =================================================================== --- trunk/labs/jbossrules/drools-repository/src/main/resources/org/drools/repository/db/RepositoryConfig.hbm.xml 2006-01-29 19:56:59 UTC (rev 2223) +++ trunk/labs/jbossrules/drools-repository/src/main/resources/org/drools/repository/db/RepositoryConfig.hbm.xml 2006-01-30 04:10:00 UTC (rev 2224) @@ -0,0 +1,11 @@ +<?xml version="1.0"?> +<!DOCTYPE hibernate-mapping PUBLIC + "-//Hibernate/Hibernate Mapping DTD 3.0//EN" + "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> + +<hibernate-mapping> + <class name="org.drools.repository.db.RepositoryConfig" table="DROOLS_CONFIG"> + <id name="key" column="PROPERTY_KEY" /> + <property name="value" column="PROPERTY_VALUE" length="512" /> + </class> +</hibernate-mapping> \ No newline at end of file Property changes on: trunk/labs/jbossrules/drools-repository/src/main/resources/org/drools/repository/db/RepositoryConfig.hbm.xml ___________________________________________________________________ Name: svn:eol-style + native Added: trunk/labs/jbossrules/drools-repository/src/main/resources/org/drools/repository/security/AssetPermission.hbm.xml =================================================================== --- trunk/labs/jbossrules/drools-repository/src/main/resources/org/drools/repository/security/AssetPermission.hbm.xml 2006-01-29 19:56:59 UTC (rev 2223) +++ trunk/labs/jbossrules/drools-repository/src/main/resources/org/drools/repository/security/AssetPermission.hbm.xml 2006-01-30 04:10:00 UTC (rev 2224) @@ -0,0 +1,20 @@ +<?xml version="1.0"?> +<!DOCTYPE hibernate-mapping PUBLIC + "-//Hibernate/Hibernate Mapping DTD 3.0//EN" + "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> + + +<hibernate-mapping> + + <class name="org.drools.repository.security.AssetPermission" table="DROOLS_PERMISSIONS"> + <id name="id" column="PERMISSION_ID"> + <generator class="native" /> + </id> + + <property name="assetType" type="string" /> + <property name="assetId" type="serializable" index="true"/> + <property name="permission" /> + + </class> + +</hibernate-mapping> \ No newline at end of file Property changes on: trunk/labs/jbossrules/drools-repository/src/main/resources/org/drools/repository/security/AssetPermission.hbm.xml ___________________________________________________________________ Name: svn:eol-style + native Added: trunk/labs/jbossrules/drools-repository/src/main/resources/org/drools/repository/security/PermissionGroup.hbm.xml =================================================================== --- trunk/labs/jbossrules/drools-repository/src/main/resources/org/drools/repository/security/PermissionGroup.hbm.xml 2006-01-29 19:56:59 UTC (rev 2223) +++ trunk/labs/jbossrules/drools-repository/src/main/resources/org/drools/repository/security/PermissionGroup.hbm.xml 2006-01-30 04:10:00 UTC (rev 2224) @@ -0,0 +1,29 @@ +<?xml version="1.0"?> +<!DOCTYPE hibernate-mapping PUBLIC + "-//Hibernate/Hibernate Mapping DTD 3.0//EN" + "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> + + +<hibernate-mapping> + + <class name="org.drools.repository.security.PermissionGroup" table="DROOLS_ACL_GROUPS"> + <id name="id" column="GROUP_ID"> + <generator class="native" /> + </id> + + <property name="name" unique="true"/> + <property name="description" /> + + <set name="userIdentities" cascade="all"> + <key column="GROUP_ID"/> + <many-to-many class="org.drools.repository.security.RepositoryUser" /> + </set> + + <set name="assetPermissions" cascade="all"> + <key column="GROUP_ID" /> + <one-to-many class="org.drools.repository.security.AssetPermission"/> + </set> + + </class> + +</hibernate-mapping> \ No newline at end of file Property changes on: trunk/labs/jbossrules/drools-repository/src/main/resources/org/drools/repository/security/PermissionGroup.hbm.xml ___________________________________________________________________ Name: svn:eol-style + native Added: trunk/labs/jbossrules/drools-repository/src/main/resources/org/drools/repository/security/RepositoryUser.hbm.xml =================================================================== --- trunk/labs/jbossrules/drools-repository/src/main/resources/org/drools/repository/security/RepositoryUser.hbm.xml 2006-01-29 19:56:59 UTC (rev 2223) +++ trunk/labs/jbossrules/drools-repository/src/main/resources/org/drools/repository/security/RepositoryUser.hbm.xml 2006-01-30 04:10:00 UTC (rev 2224) @@ -0,0 +1,13 @@ +<?xml version="1.0"?> +<!DOCTYPE hibernate-mapping PUBLIC + "-//Hibernate/Hibernate Mapping DTD 3.0//EN" + "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> + + +<hibernate-mapping> + + <class name="org.drools.repository.security.RepositoryUser" table="DROOLS_ACL_USERS"> + <id name="userId" column="USER_ID"/> + </class> + +</hibernate-mapping> \ No newline at end of file Property changes on: trunk/labs/jbossrules/drools-repository/src/main/resources/org/drools/repository/security/RepositoryUser.hbm.xml ___________________________________________________________________ Name: svn:eol-style + native Modified: trunk/labs/jbossrules/drools-repository/src/test/java/org/drools/repository/IntegrationTest.java =================================================================== --- trunk/labs/jbossrules/drools-repository/src/test/java/org/drools/repository/IntegrationTest.java 2006-01-29 19:56:59 UTC (rev 2223) +++ trunk/labs/jbossrules/drools-repository/src/test/java/org/drools/repository/IntegrationTest.java 2006-01-30 04:10:00 UTC (rev 2224) @@ -9,6 +9,9 @@ import java.util.Map; import java.util.Random; +import org.drools.repository.security.AssetPermission; +import org.drools.repository.security.RepositorySecurityException; +import org.drools.repository.security.RepositorySecurityManager; import org.hibernate.StaleObjectStateException; import junit.framework.TestCase; @@ -20,415 +23,565 @@ * * Including concurrent editing of rules, simulating multiple rules in parallel. * - * Note that I am using stateful repository instances as it makes it easier to test. - * I can control when the session is closed etc in a single threaded test run. + * Note that I am using stateful repository instances as it makes it easier to + * test. I can control when the session is closed etc in a single threaded test + * run. * * * @author <a href="mailto:mic...@gm..."> Michael Neale</a> */ public class IntegrationTest extends TestCase { - - + /** - * This will all execute as one JUnit test. - * Any failure will cause the test to stop, but this is not a unit test, - * so that is acceptable. + * This will all execute as one JUnit test. Any failure will cause the test + * to stop, but this is not a unit test, so that is acceptable. */ public void testBootstrap() throws Exception { runVersioningTests(); runAttachmentTests(); runLocalOfflineTests(); runConcurrentTests(); + runACLTests(); + + } + + private void runACLTests() { + RuleSetDef setA = new RuleSetDef( "aclSet", + null ); + setA.addRule( new RuleDef( "offline1", + "blah" ) ); + setA.addRule( new RuleDef( "offline2", + "blah" ) ); + + RepositoryManager repo = RepositoryFactory.getStatefulRepository(); + repo.save( setA ); + repo.close(); + + //we enable security + RepositorySecurityManager mgr = new RepositorySecurityManager(); + mgr.enableSecurity( true ); + + + repo = RepositoryFactory.getRepository( getAclTestUser(), + true ); + + // should fail, as we don't have ruleset permission + try { + setA = repo.loadRuleSet( "aclSet", + 1 ); + fail( "Should not be allowed to load" ); + } + catch ( RepositorySecurityException e ) { + + } + + mgr.addUserToGroup( "aclTester", + "aclTesters" ); + mgr.addPermissionToGroup( "aclTesters", + new AssetPermission( setA, + AssetPermission.READ ) ); + //we have to close the connection, and open another one to get new ACL + repo.close(); + repo = RepositoryFactory.getRepository( getAclTestUser(), + true ); + // still should not be allowed, as we don't have rule permissions ! + try { + setA = repo.loadRuleSet( "aclSet", + 1 ); + fail( "Should not be allowed to load" ); + } + catch ( RepositorySecurityException e ) { + + } + + repo.close(); + + //add permissions to read all ruledefs + mgr.addPermissionToGroup( "aclTesters", + new AssetPermission( RuleDef.class.getName(), + AssetPermission.ALL_INSTANCES, + AssetPermission.READ ) ); + + //and load it up fresh + repo = RepositoryFactory.getRepository( getAclTestUser(), + true ); + //should be ok now + setA = repo.loadRuleSet( "aclSet", + 1 ); + assertNotNull(setA); + + repo.close(); + mgr.enableSecurity( false ); + mgr.commitAndClose(); + } + private Principal getAclTestUser() { + return new Principal() { + public String getName() { + return "aclTester"; + } + }; + } /** * Test local store features, simulating 2 users running offline. */ private void runLocalOfflineTests() throws Exception { - - RuleSetDef setA = new RuleSetDef("offline1", null); - setA.addRule(new RuleDef("offline1", "blah")); - setA.addRule(new RuleDef("offline2", "blah")); - + + RuleSetDef setA = new RuleSetDef( "offline1", + null ); + setA.addRule( new RuleDef( "offline1", + "blah" ) ); + setA.addRule( new RuleDef( "offline2", + "blah" ) ); + RepositoryManager repo = RepositoryFactory.getStatefulRepository(); - repo.save(setA); + repo.save( setA ); repo.close(); - + repo = RepositoryFactory.getStatefulRepository(); - //load up copy A - setA = repo.loadRuleSet("offline1", 1); + // load up copy A + setA = repo.loadRuleSet( "offline1", + 1 ); repo.close(); - - //now load up copy B + + // now load up copy B repo = RepositoryFactory.getStatefulRepository(); - RuleSetDef setB = repo.loadRuleSet("offline1", 1); + RuleSetDef setB = repo.loadRuleSet( "offline1", + 1 ); repo.close(); - //now store them locally + // now store them locally LocalStore store = new LocalStore(); ByteArrayOutputStream outA = new ByteArrayOutputStream(); ByteArrayOutputStream outB = new ByteArrayOutputStream(); - store.save(setA, outA); - store.save(setB, outB); - - - setA = (RuleSetDef) store.load(new ByteArrayInputStream(outA.toByteArray())); - setB = (RuleSetDef) store.load(new ByteArrayInputStream(outB.toByteArray())); - //setA.addRule(new RuleDef("yeah", "boo")); - //setB.addRule(new RuleDef("goo", "ya")); - RuleDef rule1 = setA.findRuleByName("offline1"); - RuleDef rule2 = setB.findRuleByName("offline2"); - rule1.setContent("something"); - //setA.addApplicationData(new ApplicationDataDef("dsadsa", "dfsads")); - //setB.setMetaData(new MetaData()); - - //no problems expected, as they were editing different rules + store.save( setA, + outA ); + store.save( setB, + outB ); + + setA = (RuleSetDef) store.load( new ByteArrayInputStream( outA.toByteArray() ) ); + setB = (RuleSetDef) store.load( new ByteArrayInputStream( outB.toByteArray() ) ); + // setA.addRule(new RuleDef("yeah", "boo")); + // setB.addRule(new RuleDef("goo", "ya")); + RuleDef rule1 = setA.findRuleByName( "offline1" ); + RuleDef rule2 = setB.findRuleByName( "offline2" ); + rule1.setContent( "something" ); + setA.addApplicationData(new ApplicationDataDef("dsadsa", "dfsads")); + setB.setMetaData(new MetaData()); + + // no problems expected, as they were editing different rules repo = RepositoryFactory.getStatefulRepository(); - repo.save(setA); + repo.save( setA ); repo.close(); - + repo = RepositoryFactory.getStatefulRepository(); - repo.save(setB); + repo.save( setB ); repo.close(); - + } - /** * The purpose of this test is to simulate 2 different users editing rules * in different session. Detached and all. */ private void runConcurrentTests() { - //2 repos, representing different users. + // 2 repos, representing different users. RepositoryManager repoA = RepositoryFactory.getStatefulRepository(); RepositoryManager repoB = RepositoryFactory.getStatefulRepository(); - - - //Lets try a simple rule, which will stay stand alone - RuleDef ruleA = new RuleDef("Concurrent 1", "content1"); - repoA.save(ruleA); + + // Lets try a simple rule, which will stay stand alone + RuleDef ruleA = new RuleDef( "Concurrent 1", + "content1" ); + repoA.save( ruleA ); repoA.close(); repoA = RepositoryFactory.getStatefulRepository(); - - //Bob loads it up, decides he wants to edit it. - RuleDef ruleB = repoB.loadRule("Concurrent 1", 1); - assertEquals("content1", ruleB.getContent()); - ruleB.setContent("bobs version"); - - //Michael also is editing his version. - ruleA.setContent("michaels version"); - - //oh dear, we can't both be write can we? - //but Bob is just a bit quicker ... - repoB.save(ruleB); + + // Bob loads it up, decides he wants to edit it. + RuleDef ruleB = repoB.loadRule( "Concurrent 1", + 1 ); + assertEquals( "content1", + ruleB.getContent() ); + ruleB.setContent( "bobs version" ); + + // Michael also is editing his version. + ruleA.setContent( "michaels version" ); + + // oh dear, we can't both be write can we? + // but Bob is just a bit quicker ... + repoB.save( ruleB ); try { - repoA.save(ruleA); + repoA.save( ruleA ); fail(); - } catch (StaleObjectStateException e) { - assertNotNull(e.getMessage()); } - + catch ( StaleObjectStateException e ) { + assertNotNull( e.getMessage() ); + } + repoA = RepositoryFactory.getStatefulRepository(); - - - //now try some rulesets. - RuleSetDef ruleSet = new RuleSetDef("Integration concurrent 1", null); - ruleSet.addRule(new RuleDef("Concurrent 2", "abc").addTag("yeah")); - repoA.save(ruleSet); + + // now try some rulesets. + RuleSetDef ruleSet = new RuleSetDef( "Integration concurrent 1", + null ); + ruleSet.addRule( new RuleDef( "Concurrent 2", + "abc" ).addTag( "yeah" ) ); + repoA.save( ruleSet ); repoA.close(); - - //we will add a rule to each one, concurrently + + // we will add a rule to each one, concurrently repoA = RepositoryFactory.getStatefulRepository(); repoB = RepositoryFactory.getStatefulRepository(); - - RuleSetDef ruleSetA = repoA.loadRuleSet("Integration concurrent 1", 1); - RuleSetDef ruleSetB = repoB.loadRuleSet("Integration concurrent 1", 1); - ruleA = new RuleDef("Concurrent 3", "content"); - ruleSetA.addRule(ruleA); - ruleSetB.addRule(new RuleDef("Concurrent 4", "content")); - - //should have no problems, as we are not touching the same rules. - repoA.save(ruleSetA); - repoB.save(ruleSetB); - - ruleSetA.addFunction(new FunctionDef("abc", "yeah")); - repoA.save(ruleSetA); - - ruleA.setContent("new content"); - repoA.save(ruleSetA); - + RuleSetDef ruleSetA = repoA.loadRuleSet( "Integration concurrent 1", + 1 ); + RuleSetDef ruleSetB = repoB.loadRuleSet( "Integration concurrent 1", + 1 ); + + ruleA = new RuleDef( "Concurrent 3", + "content" ); + ruleSetA.addRule( ruleA ); + ruleSetB.addRule( new RuleDef( "Concurrent 4", + "content" ) ); + + // should have no problems, as we are not touching the same rules. + repoA.save( ruleSetA ); + repoB.save( ruleSetB ); + + ruleSetA.addFunction( new FunctionDef( "abc", + "yeah" ) ); + repoA.save( ruleSetA ); + + ruleA.setContent( "new content" ); + repoA.save( ruleSetA ); + repoA.close(); repoB.close(); - + repoA = RepositoryFactory.getStatefulRepository(); - ruleSetA = repoA.loadRuleSet("Integration concurrent 1", 1); - assertEquals(3, ruleSetA.getRules().size()); - ruleA = ruleSetA.findRuleByName("Concurrent 3"); - assertEquals("new content", ruleA.getContent()); - + ruleSetA = repoA.loadRuleSet... [truncated message content] |
From: <jbo...@li...> - 2006-01-29 19:57:28
|
Author: mnasato Date: 2006-01-29 14:56:59 -0500 (Sun, 29 Jan 2006) New Revision: 2223 Modified: trunk/labs/davcache/src/net/sf/davcache/TreeCacheStore.java Log: remove properties from treeCache in deleteFile() Modified: trunk/labs/davcache/src/net/sf/davcache/TreeCacheStore.java =================================================================== --- trunk/labs/davcache/src/net/sf/davcache/TreeCacheStore.java 2006-01-29 13:21:00 UTC (rev 2222) +++ trunk/labs/davcache/src/net/sf/davcache/TreeCacheStore.java 2006-01-29 19:56:59 UTC (rev 2223) @@ -144,6 +144,7 @@ { FqnAndKey pair = splitFqnAndKey(path); treeCache.remove(pair.getFqn(), pair.getKey()); + treeCache.remove(getPropsPath(path)); } public void moveFile(String path, String destinationPath) throws CacheException |
From: <jbo...@li...> - 2006-01-29 13:21:26
|
Author: mnasato Date: 2006-01-29 08:21:00 -0500 (Sun, 29 Jan 2006) New Revision: 2222 Modified: trunk/labs/davcache/src/net/sf/davcache/WebdavServlet.java Log: fix space chars decoding in MOVE destination (DAVCACHE-1) Modified: trunk/labs/davcache/src/net/sf/davcache/WebdavServlet.java =================================================================== --- trunk/labs/davcache/src/net/sf/davcache/WebdavServlet.java 2006-01-27 21:59:55 UTC (rev 2221) +++ trunk/labs/davcache/src/net/sf/davcache/WebdavServlet.java 2006-01-29 13:21:00 UTC (rev 2222) @@ -9,8 +9,6 @@ import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; -import java.net.URI; -import java.net.URISyntaxException; import java.util.Iterator; import java.util.Set; @@ -100,10 +98,9 @@ { // TODO check Overwrite header first String path = getRelativePath(request); - String destinationHeader = request.getHeader("Destination"); + String absoluteDestinationPath = request.getHeader("Destination"); try { - String absoluteDestinationPath = new URI(destinationHeader).getPath(); String destinationPath = relativizePath(request, absoluteDestinationPath); if (store.isFile(path)) { @@ -118,10 +115,6 @@ response.setStatus(HttpServletResponse.SC_CREATED); } } - catch (URISyntaxException e) - { - throw new ServletException(e); - } catch (CacheException e) { throw new ServletException(e); @@ -332,12 +325,18 @@ */ private String getRelativePath(HttpServletRequest request) { - // TODO this works only when servlet-mapping is "/*" return relativizePath(request, getAbsolutePath(request)); } private String relativizePath(HttpServletRequest request, String path) { + // TODO this works only when servlet-mapping is "/*" + int schema = path.indexOf("://"); + if (schema != -1) + { + // strip http://www.host.com/ + path = path.substring(path.indexOf("/", schema + 3)); + } String contextPath = request.getContextPath(); return path.substring(contextPath.length()); } |
From: <jbo...@li...> - 2006-01-27 22:00:13
|
Author: szimano Date: 2006-01-27 16:59:55 -0500 (Fri, 27 Jan 2006) New Revision: 2221 Added: trunk/forge/portal-extensions/shotoku/shotoku-files/src/java/org/jboss/shotoku/files/FileContentManager.java Removed: trunk/forge/portal-extensions/shotoku/shotoku-files/src/java/org/jboss/shotoku/files/FilesContentManager.java Modified: trunk/forge/portal-extensions/shotoku/maven.xml trunk/forge/portal-extensions/shotoku/project.properties trunk/forge/portal-extensions/shotoku/shotoku-files/maven.xml trunk/forge/portal-extensions/shotoku/shotoku-files/project.properties trunk/forge/portal-extensions/shotoku/shotoku-files/project.xml trunk/forge/portal-extensions/shotoku/shotoku-files/src/java/org/jboss/shotoku/files/FileDirectory.java trunk/forge/portal-extensions/shotoku/shotoku-files/src/java/org/jboss/shotoku/files/FileHistory.java trunk/forge/portal-extensions/shotoku/shotoku-files/src/java/org/jboss/shotoku/files/FileNode.java trunk/forge/portal-extensions/shotoku/shotoku-files/src/java/org/jboss/shotoku/files/FileTools.java trunk/forge/portal-extensions/shotoku/shotoku-svn/maven.xml trunk/forge/portal-extensions/shotoku/shotoku-svn/project.properties trunk/forge/portal-extensions/shotoku/shotoku-svn/project.xml Log: further implementation http://jira.jboss.com/jira/browse/JBSHOTOKU-53 Modified: trunk/forge/portal-extensions/shotoku/maven.xml =================================================================== --- trunk/forge/portal-extensions/shotoku/maven.xml 2006-01-27 20:49:45 UTC (rev 2220) +++ trunk/forge/portal-extensions/shotoku/maven.xml 2006-01-27 21:59:55 UTC (rev 2221) @@ -11,11 +11,13 @@ <goal name="all"> <attainGoal name="clean" /> - <j:set var="prefix" value="" /> + <attainGoal name="shotoku:build" /> + <attainGoal name="shotoku:deploy" /> + <!--<j:set var="prefix" value="" /> <j:set var="goal" value="build" /> <attainGoal name="shotoku-all-projects" /> <j:set var="goal" value="deploy" /> - <attainGoal name="shotoku-all-projects" /> + <attainGoal name="shotoku-all-projects" />--> </goal> <goal name="shotoku-all-projects"> @@ -25,6 +27,9 @@ <maven:reactor includes="${prefix}shotoku-aop/project.xml" excludes="" basedir="." banner="Shotoku base aop" goals="${goal}" ignoreFailures="false" /> + <maven:reactor includes="${prefix}shotoku-files/project.xml" excludes="" basedir="." + banner="Shotoku files content-manager" + goals="${goal}" ignoreFailures="false" /> <maven:reactor includes="${prefix}shotoku-svn/project.xml" excludes="" basedir="." banner="Shotoku svn service" goals="${goal}" ignoreFailures="false" /> @@ -47,6 +52,13 @@ <j:set var="prefix" value="shotoku/" /> <j:set var="goal" value="deploy" /> <attainGoal name="shotoku-all-projects" /> + + <!-- Copying the ear to the deploy directory. --> + <ant:copy todir="${local.deploy.dir}"> + <ant:fileset dir="shotoku-svn/target" flatten="true" overwrite="true"> + <ant:filename name="${shotoku.ear.dir}/**" /> + </ant:fileset> + </ant:copy> </goal> <goal name="shotoku:build"> @@ -63,6 +75,13 @@ <j:set var="prefix" value="" /> <j:set var="goal" value="deploy" /> <attainGoal name="shotoku-all-projects" /> + + <!-- Copying the ear to the deploy directory. --> + <ant:copy todir="${local.deploy.dir}"> + <ant:fileset dir="shotoku-svn/target" flatten="true" overwrite="true"> + <ant:filename name="${shotoku.ear.dir}/**" /> + </ant:fileset> + </ant:copy> </goal> <goal name="clean"> @@ -72,7 +91,8 @@ <ant:delete dir="shotoku-aop/target" /> <ant:delete dir="shotoku-svn/target" /> <ant:delete dir="shotoku-test/target" /> - <ant:delete dir="${local.deploy.dir}/00shotoku.ear" /> + <ant:delete dir="shotoku-files/target" /> + <ant:delete dir="${local.deploy.dir}/${shotoku.ear.dir}" /> </goal> <goal name="jar-to-dir"> @@ -86,14 +106,14 @@ <goal name="dist"> <attainGoal name="all" /> <ant:mkdir dir="target" /> - <ant:copy todir="target/binary/00shotoku.ear" overwrite="true"> - <ant:fileset dir="shotoku-svn/target/00shotoku.ear" /> + <ant:copy todir="target/binary/${shotoku.ear.dir}" overwrite="true"> + <ant:fileset dir="shotoku-svn/target/${shotoku.ear.dir}" /> </ant:copy> <ant:copy todir="target/binary" file="shotoku-aop/target/shotoku-aop.aop" /> - <j:set var="jar.to.dir" value="target/binary/00shotoku.ear/shotoku-base.jar" /> + <j:set var="jar.to.dir" value="target/binary/${shotoku.ear.dir}/shotoku-base.jar" /> <attainGoal name="jar-to-dir" /> - <j:set var="jar.to.dir" value="target/binary/00shotoku.ear/shotoku-svn.ejb3" /> + <j:set var="jar.to.dir" value="target/binary/${shotoku.ear.dir}/shotoku-svn.ejb3" /> <attainGoal name="jar-to-dir" /> <ant:tar destfile="target/shotoku-${version}-binary.tar.gz" Modified: trunk/forge/portal-extensions/shotoku/project.properties =================================================================== --- trunk/forge/portal-extensions/shotoku/project.properties 2006-01-27 20:49:45 UTC (rev 2220) +++ trunk/forge/portal-extensions/shotoku/project.properties 2006-01-27 21:59:55 UTC (rev 2221) @@ -1,4 +1,6 @@ maven.repo.remote=http://repository.atlassian.com,http://www.ibiblio.org/maven,http://dist.codehaus.org/ maven.junit.fork=yes maven.war.src=${basedir}/src/web -version=1.0-alpha2 \ No newline at end of file +version=1.0-alpha2 + +shotoku.ear.dir=00shotoku.ear \ No newline at end of file Modified: trunk/forge/portal-extensions/shotoku/shotoku-files/maven.xml =================================================================== --- trunk/forge/portal-extensions/shotoku/shotoku-files/maven.xml 2006-01-27 20:49:45 UTC (rev 2220) +++ trunk/forge/portal-extensions/shotoku/shotoku-files/maven.xml 2006-01-27 21:59:55 UTC (rev 2221) @@ -9,46 +9,20 @@ </goal> <goal name="build"> - <attainGoal name="ejb" /> + <attainGoal name="jar" /> + + <ant:copy overwrtie="true" + tofile="${maven.repo.local}/shotoku/jars/shotoku-files.jar" + file="target/shotoku-files-1.0.jar" /> </goal> - <goal name="deploy"> + <goal name="deploy"> <!-- Constructing the ear. --> - <ant:copy overwrite="true" - tofile="target/${shotoku.ear.dir}/shotoku-svn.ejb3" - file="target/shotoku-svn-1.0.jar" /> - <ant:copy - todir="target/${shotoku.ear.dir}" overwrite="true" - file="${maven.repo.local}/shotoku/jars/shotoku-base.jar" /> - <ant:copy - todir="target/${shotoku.ear.dir}" overwrite="true" - file="${maven.repo.local}/commons-configuration/jars/commons-configuration-1.1.jar" /> - <ant:copy - todir="target/${shotoku.ear.dir}" overwrite="true" - file="${maven.repo.local}/commons-lang/jars/commons-lang-2.1.jar" /> - <ant:copy - todir="target/${shotoku.ear.dir}" overwrite="true" - file="${maven.repo.local}/commons-collections/jars/commons-collections-3.1.jar" /> - <ant:copy - todir="target/${shotoku.ear.dir}" overwrite="true" - file="${maven.repo.local}/tmate/jars/javasvn.jar" /> - <ant:copy - todir="target/${shotoku.ear.dir}" overwrite="true"> - <ant:fileset dir="${maven.repo.local}/velocity/jars"> - <ant:filename name="velocity*-1.4.jar" /> - </ant:fileset> - </ant:copy> - <ant:copy todir="target/${shotoku.ear.dir}"> - <ant:fileset dir="src/app" flatten="true" overwrite="true"> - <ant:filename name="**" /> - </ant:fileset> - </ant:copy> - - <!-- Copying the ear to the deploy directory. --> - <ant:copy todir="${local.deploy.dir}"> - <ant:fileset dir="target" flatten="true" overwrite="true"> - <ant:filename name="${shotoku.ear.dir}/**" /> - </ant:fileset> - </ant:copy> + + <!-- <ant:copy overwrtie="true" + tofile="../shotoku-svn/target/${shotoku.ear.dir}/shotoku-files.jar" + file="target/shotoku-files-1.0.jar" /> --> + </goal> + </project> Modified: trunk/forge/portal-extensions/shotoku/shotoku-files/project.properties =================================================================== --- trunk/forge/portal-extensions/shotoku/shotoku-files/project.properties 2006-01-27 20:49:45 UTC (rev 2220) +++ trunk/forge/portal-extensions/shotoku/shotoku-files/project.properties 2006-01-27 21:59:55 UTC (rev 2221) @@ -3,5 +3,3 @@ maven.war.src=${basedir}/src/web maven.ejb.excludes=**/*Listener*,**/listener maven.war.classes.excludes=**/*Bean* - -shotoku.ear.dir=00shotoku.ear \ No newline at end of file Modified: trunk/forge/portal-extensions/shotoku/shotoku-files/project.xml =================================================================== --- trunk/forge/portal-extensions/shotoku/shotoku-files/project.xml 2006-01-27 20:49:45 UTC (rev 2220) +++ trunk/forge/portal-extensions/shotoku/shotoku-files/project.xml 2006-01-27 21:59:55 UTC (rev 2221) @@ -7,11 +7,11 @@ <project> <pomVersion>3</pomVersion> <extend>../project.xml</extend> - <id>shotoku-svn</id> - <name>Shotoku svn</name> + <id>shotoku-files</id> + <name>Shotoku Files</name> <currentVersion>1.0</currentVersion> <organization> - <name>Adam Warski</name> + <name>Tomasz Szymanski</name> <url>http://mamut.net.pl</url> </organization> <description></description> Added: trunk/forge/portal-extensions/shotoku/shotoku-files/src/java/org/jboss/shotoku/files/FileContentManager.java =================================================================== --- trunk/forge/portal-extensions/shotoku/shotoku-files/src/java/org/jboss/shotoku/files/FileContentManager.java 2006-01-27 20:49:45 UTC (rev 2220) +++ trunk/forge/portal-extensions/shotoku/shotoku-files/src/java/org/jboss/shotoku/files/FileContentManager.java 2006-01-27 21:59:55 UTC (rev 2221) @@ -0,0 +1,144 @@ +/* + * JBoss, Home of Professional Open Source + * Copyright 2005, JBoss Inc., and individual contributors as indicated + * by the @authors tag. See the copyright.txt in the distribution for a + * full listing of individual contributors. + * + * This is free software; you can redistribute it and/or modify it + * under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation; either version 2.1 of + * the License, or (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this software; if not, write to the Free + * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA + * 02110-1301 USA, or see the FSF site: http://www.fsf.org. + */ +package org.jboss.shotoku.files; + +import java.io.File; +import java.util.Collection; + +import org.apache.commons.configuration.Configuration; +import org.jboss.logging.Logger; +import org.jboss.shotoku.ContentManager; +import org.jboss.shotoku.Directory; +import org.jboss.shotoku.Node; +import org.jboss.shotoku.Resource; +import org.jboss.shotoku.exceptions.DeleteException; +import org.jboss.shotoku.exceptions.RepositoryException; +import org.jboss.shotoku.exceptions.ResourceDoesNotExist; +import org.jboss.shotoku.exceptions.SaveException; + +public class FileContentManager extends ContentManager { + + private String pathToRepo; + + private String pathToRepoCurrent; + + private String pathToRepoHistory; + + private final static String CURRENT = "CURRENT"; + + private final static String HISTORY = "HISTORY"; + + private Logger log = Logger.getLogger(FileContentManager.class); + + public FileContentManager(String id, String prefix, Configuration conf) throws RepositoryException { + super(id, prefix); + + // add separator at the end and at the begginig + if (!prefix.startsWith("/")) { + prefix = "/" + prefix; + } + + if (!prefix.endsWith("/")) { + prefix += "/"; + } + + pathToRepo = getProperty("shotoku.default.localpath"); + + if (pathToRepo == null) { + throw new RepositoryException("shotoku.default.localpath is not set in properties"); + } + else if (!(new File(pathToRepo)).exists() || !(new File(pathToRepo)).isDirectory()){ + throw new RepositoryException(pathToRepo+" doesn't exist or isn't a directory"); + } + + // create paths + + pathToRepoCurrent = pathToRepo + File.pathSeparator + CURRENT; + pathToRepoHistory = pathToRepo + File.pathSeparator + HISTORY; + + // check for current and history existance + File fileCur = new File(pathToRepoCurrent); + File fileHis = new File(pathToRepoHistory); + + // create CURRENT folder if it doesn't exist + if (!fileCur.exists()) { + fileCur.mkdirs(); + log.info("Added CURRENT folder"); + } + + // create HISTORY folder if it doesn't exist + if (!fileHis.exists()) { + fileHis.mkdirs(); + log.info("Added HISTORY folder"); + } + } + + @Override + public Directory getRootDirectory() throws RepositoryException { + return new FileDirectory(getPathToRepoCurrent(), this); + } + + @Override + public Node getNode(String nodeName) throws ResourceDoesNotExist, + RepositoryException { + return getRootDirectory().getNode(nodeName); + } + + @Override + public Directory getDirectory(String dirName) throws ResourceDoesNotExist, + RepositoryException { + return getRootDirectory().getDirectory(dirName); + } + + @Override + public void save(Collection<Resource> resources, String message) + throws SaveException, RepositoryException { + for (Resource resource : resources) { + resource.save(message); + } + } + + @Override + public void delete(Collection<Resource> resources) throws DeleteException, + RepositoryException { + for (Resource resource : resources) { + resource.delete(); + } + } + + public String getPathToRepo() { + return pathToRepo; + } + + public String getPathToRepoCurrent() { + return pathToRepoCurrent + prefix; + } + + public String getPathToRepoHistory() { + return pathToRepoHistory + prefix; + } + + public String getPrefix() { + return prefix; + } + +} Modified: trunk/forge/portal-extensions/shotoku/shotoku-files/src/java/org/jboss/shotoku/files/FileDirectory.java =================================================================== --- trunk/forge/portal-extensions/shotoku/shotoku-files/src/java/org/jboss/shotoku/files/FileDirectory.java 2006-01-27 20:49:45 UTC (rev 2220) +++ trunk/forge/portal-extensions/shotoku/shotoku-files/src/java/org/jboss/shotoku/files/FileDirectory.java 2006-01-27 21:59:55 UTC (rev 2221) @@ -22,10 +22,14 @@ package org.jboss.shotoku.files; import java.io.File; +import java.io.FileOutputStream; import java.io.IOException; +import java.io.OutputStream; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Properties; import org.jboss.shotoku.ContentManager; import org.jboss.shotoku.Directory; @@ -43,34 +47,48 @@ private File directory; - private FilesContentManager manager; + private FileContentManager manager; + private String dirFullPath; + + private String dirPath; + + private Properties props; + + private boolean dirChanged = false; + /** * */ private static final long serialVersionUID = 1L; - public FileDirectory(String directory, FilesContentManager manager) throws RepositoryException { - File dir = new File(directory); + public FileDirectory(String directory, FileContentManager manager) throws RepositoryException { + while (directory.startsWith("/")) { + directory = directory.substring(1); + } + while(directory.endsWith("/")) { + directory = directory.substring(0, directory.length()-2); + } + + dirFullPath = manager.getPathToRepoCurrent()+File.pathSeparator+directory; + + dirPath = directory; + + File dir = new File(dirFullPath); + this.manager = manager; - if (!dir.isDirectory()) { + if (!dir.exists()) + dirChanged = true; + + if (dir.exists() && !dir.isDirectory()) { throw new RepositoryException(directory + " is not a directory"); } this.directory = dir; } - public FileDirectory(File directory) throws RepositoryException { - if (directory.isDirectory()) { - this.directory = directory; - } else { - throw new RepositoryException(directory.getAbsolutePath() - + " is not a directory."); - } - } - public NodeList getNodes() throws RepositoryException { List<Node> list = new ArrayList<Node>(); @@ -102,7 +120,7 @@ // get all children for (File directory : children) { if (directory.isDirectory()) { - list.add(new FileDirectory(directory)); + list.add(new FileDirectory(dirFullPath + File.pathSeparator + directory.getName(), manager)); } } @@ -134,12 +152,12 @@ + " doesn't exists"); } - return new FileDirectory(dir); + return new FileDirectory(dirFullPath + File.pathSeparator + name, manager); } public Node newNode(String name) throws ResourceAlreadyExists, RepositoryException { - File file = new File(this.directory.getAbsolutePath() + name); + File file = new File(this.directory.getAbsolutePath() + File.pathSeparator + name); if (file.exists()) { throw new ResourceAlreadyExists("File " + file.getAbsolutePath() @@ -177,77 +195,182 @@ } } - return new FileDirectory(dir); + return new FileDirectory(dirFullPath + File.pathSeparator + name, manager); } public boolean hasIndex(String arg0) throws RepositoryException { - // TODO Auto-generated method stub + // this feature is still not implemented in Shotoku return false; } public void setIndex(String arg0, boolean arg1) throws RepositoryException { - // TODO Auto-generated method stub + // this feature is still not implemented in Shotoku } - public void copyTo(Directory arg0, String arg1, String arg2) + public void copyTo(Directory dir, String newName, String logMessage) throws CopyException { - // TODO Auto-generated method stub + try { + // create new directory + Directory newDir = dir.newDirectory(newName); + List<Directory> dirs = getDirectories(); + + // copy all subdirectories + for (Directory subDir : dirs) { + subDir.copyTo(newDir, subDir.getName(), logMessage); + } + + NodeList nodes = getNodes(); + + //copy all nodes inside directory + for (Node node : nodes.toList()) { + node.copyTo(newDir, node.getName(), logMessage); + } + + } catch (RepositoryException e) { + throw new CopyException(e); + } catch (ResourceAlreadyExists e) { + throw new CopyException(e); + } } - public void moveTo(Directory arg0, String arg1) throws MoveException { - // TODO Auto-generated method stub - + public void moveTo(Directory dir, String logMessage) throws MoveException { + try { + // create new directory + Directory newDir = dir.newDirectory(getName()); + + // set it's properties + refreshProps(); + + for (Object key : props.keySet()) { + newDir.setProperty((String)key, props.getProperty((String)key)); + } + + // save dir with props + newDir.save(logMessage); + + List<Directory> dirs = getDirectories(); + + // move all subdirectories + for (Directory subDir : dirs) { + subDir.moveTo(newDir, logMessage); + } + + NodeList nodes = getNodes(); + + // move all nodes inside directory + for (Node node : nodes.toList()) { + node.moveTo(newDir, logMessage); + } + + // delete this dir history + File hisDir = FileTools.getHistoryDir(this, manager); + hisDir.delete(); + + } catch (Exception e) { + throw new MoveException(e); + } } public Map<String, String> getProperties() throws RepositoryException { - // TODO Auto-generated method stub - return null; + try { + refreshProps(); + } catch (IOException e) { + throw new RepositoryException(e); + } + + Map<String, String> map = new HashMap<String,String>(); + + for (Object key : props.keySet()) { + map.put((String)key, props.getProperty((String)key)); + } + + return map; } - public String getProperty(String arg0) throws RepositoryException { - // TODO Auto-generated method stub - return null; + private void refreshProps() throws IOException { + if (!dirChanged) { + props = FileTools.getPropertiesForDirectory(this, manager); + } } - public void deleteProperty(String arg0) throws RepositoryException { - // TODO Auto-generated method stub + public String getProperty(String name) throws RepositoryException { + try { + refreshProps(); + } catch (IOException e) { + throw new RepositoryException(e); + } + + return props.getProperty(name); + } + public void deleteProperty(String name) throws RepositoryException { + try { + refreshProps(); + } catch (IOException e) { + throw new RepositoryException(e); + } + + dirChanged = true; + + props.remove(name); } - public void setProperty(String arg0, String arg1) { - // TODO Auto-generated method stub - + public void setProperty(String name, String value) { + try { + refreshProps(); + } catch (IOException e) { + throw new RepositoryException(e); + } + + dirChanged = true; + + props.setProperty(name, value); } - public void save(String arg0) throws SaveException, RepositoryException { - // TODO Auto-generated method stub - + public void save(String logMessage) throws SaveException, RepositoryException { + if (!directory.exists()) + if (!directory.mkdirs()) { + throw new SaveException("Couldn't create directory: "+getFullName()); + } + + if (dirChanged) { + try { + File propFile = FileTools.getPropertiesFileForDirectory(this, manager); + + OutputStream os = new FileOutputStream(propFile); + + props.store(os, FileTools.STORE_TEXT); + + os.close(); + } catch (IOException e) { + throw new SaveException(e); + } + } + } public String getLogMessage() throws RepositoryException { - // TODO Auto-generated method stub - return null; + return ""; } public String getFullName() { - // TODO Auto-generated method stub - return null; + return dirPath; } public Directory getParent() throws RepositoryException { - return new FileDirectory(directory.getParentFile()); + return new FileDirectory(directory.getParent(), manager); } public void delete() throws DeleteException, RepositoryException { - // TODO Auto-generated method stub - + if (!directory.delete()) { + throw new DeleteException("Couldn't delete directory: "+dirFullPath); + } } public String getName() { - // TODO Auto-generated method stub - return null; + return directory.getName(); } public String toString() { Modified: trunk/forge/portal-extensions/shotoku/shotoku-files/src/java/org/jboss/shotoku/files/FileHistory.java =================================================================== --- trunk/forge/portal-extensions/shotoku/shotoku-files/src/java/org/jboss/shotoku/files/FileHistory.java 2006-01-27 20:49:45 UTC (rev 2220) +++ trunk/forge/portal-extensions/shotoku/shotoku-files/src/java/org/jboss/shotoku/files/FileHistory.java 2006-01-27 21:59:55 UTC (rev 2221) @@ -40,9 +40,9 @@ private FileNode node; - private FilesContentManager manager; + private FileContentManager manager; - public FileHistory(FileNode node, FilesContentManager manager) { + public FileHistory(FileNode node, FileContentManager manager) { this.node = node; this.manager = manager; } @@ -67,6 +67,15 @@ File revFile = FileTools.getFileAtRevision(node, revision, manager); + try { + // get properties for version + Properties props = FileTools.getPropertiesAtRevision(node, manager, revision); + + node.setProperties(props); + } catch (IOException e1) { + throw new RepositoryException(e1); + } + if (!revFile.exists()) { throw new ResourceDoesNotExist("There is no revision " + revision + " of node " + node.getFullName()); Modified: trunk/forge/portal-extensions/shotoku/shotoku-files/src/java/org/jboss/shotoku/files/FileNode.java =================================================================== --- trunk/forge/portal-extensions/shotoku/shotoku-files/src/java/org/jboss/shotoku/files/FileNode.java 2006-01-27 20:49:45 UTC (rev 2220) +++ trunk/forge/portal-extensions/shotoku/shotoku-files/src/java/org/jboss/shotoku/files/FileNode.java 2006-01-27 21:59:55 UTC (rev 2221) @@ -44,13 +44,15 @@ import org.jboss.shotoku.exceptions.ResourceDoesNotExist; import org.jboss.shotoku.exceptions.SaveException; +import sun.misc.Perf.GetPerfAction; + public class FileNode implements Node { private File file; private File tmpFile; - private FilesContentManager manager; + private FileContentManager manager; private Directory directory; @@ -70,7 +72,7 @@ private static final long serialVersionUID = 1L; public FileNode(Directory directory, String node, boolean newFile, - FilesContentManager manager) throws RepositoryException, + FileContentManager manager) throws RepositoryException, ResourceAlreadyExists, ResourceDoesNotExist { File fil = new File(directory + File.pathSeparator + node); @@ -425,7 +427,7 @@ * directory is already the root directory. */ public Directory getParent() throws RepositoryException { - return new FileDirectory(file.getParentFile()); + return new FileDirectory(file.getParent(), manager); } /** @@ -451,6 +453,7 @@ // get next history file File nextVersion = FileTools.getNextHistoryFile(this, manager, i); + File nextPropFile = FileTools.getNextHistoryPropFile(this, manager, i); if (nextVersion.exists()) { throw new SaveException("Conflict in saving: history file exists"); @@ -462,6 +465,18 @@ throw new RepositoryException(e); } + // save props version + try { + OutputStream hisProps = new FileOutputStream(nextPropFile); + + // get current props + FileTools.getPropertiesForNode(this, manager).store(hisProps, FileTools.STORE_TEXT); + + hisProps.close(); + } catch (IOException e) { + throw new RepositoryException(e); + } + // save prevoius version copyToFile(file.getAbsolutePath()); @@ -519,7 +534,7 @@ } throw new RepositoryException(e); } - + // set bools to false lastVersion = contentChanged = propsChanged = false; } @@ -594,4 +609,8 @@ public String getNodeName() { return file.getName(); } + + public void setProperties(Properties props) { + this.props = props; + } } Modified: trunk/forge/portal-extensions/shotoku/shotoku-files/src/java/org/jboss/shotoku/files/FileTools.java =================================================================== --- trunk/forge/portal-extensions/shotoku/shotoku-files/src/java/org/jboss/shotoku/files/FileTools.java 2006-01-27 20:49:45 UTC (rev 2220) +++ trunk/forge/portal-extensions/shotoku/shotoku-files/src/java/org/jboss/shotoku/files/FileTools.java 2006-01-27 21:59:55 UTC (rev 2221) @@ -25,6 +25,7 @@ import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; +import java.io.InputStream; import java.util.Properties; import javax.activation.MimetypesFileTypeMap; @@ -34,26 +35,28 @@ public class FileTools { private static MimetypesFileTypeMap mimeTypes; - + private final static String HIST_PROPS = "history.properties"; private final static String PROPS = "properties.properties"; public static final String STORE_TEXT = "Properties saved by Shotoku file-based"; - + public static final String REVISION_SUFFIX = ".version"; + public static final String PROPERTIES_SUFFIX = ".properties"; + static { mimeTypes = new MimetypesFileTypeMap(FileTools.class .getResourceAsStream("/mime.types.txt")); } - + public static String getMimeType(File file) { return mimeTypes.getContentType(file); } - + public static File getFileAtRevision(FileNode node, int revison, - FilesContentManager manager) { + FileContentManager manager) { // delete beggining part of path to get only dir inside repo String directory = node.getDirectory().toString().replace( manager.getPathToRepoCurrent(), ""); @@ -68,7 +71,7 @@ return hisFile; } - public static File getHistoryDir(FileNode node, FilesContentManager manager) { + public static File getHistoryDir(FileNode node, FileContentManager manager) { // delete beggining part of path to get only dir inside repo String directory = node.getDirectory().toString().replace( manager.getPathToRepoCurrent(), ""); @@ -82,7 +85,7 @@ return hisFile; } - public static File getHistoryFile(FileNode node, FilesContentManager manager) { + public static File getHistoryFile(FileNode node, FileContentManager manager) { // delete beggining part of path to get only dir inside repo String directory = node.getDirectory().toString().replace( manager.getPathToRepoCurrent(), ""); @@ -98,7 +101,7 @@ return hisFile; } - public static File getPropsFile(FileNode node, FilesContentManager manager) { + public static File getPropsFile(FileNode node, FileContentManager manager) { // delete beggining part of path to get only dir inside repo String directory = node.getDirectory().toString().replace( manager.getPathToRepoCurrent(), ""); @@ -115,7 +118,7 @@ } public static Properties getHistoryForNode(FileNode node, - FilesContentManager manager) throws RepositoryException { + FileContentManager manager) throws RepositoryException { File hisFile = getHistoryFile(node, manager); @@ -133,7 +136,7 @@ } public static Properties getPropertiesForNode(FileNode node, - FilesContentManager manager) throws RepositoryException { + FileContentManager manager) throws RepositoryException { File propsFile = getPropsFile(node, manager); @@ -168,7 +171,7 @@ } public static File getNextHistoryFile(FileNode node, - FilesContentManager manager, int version) { + FileContentManager manager, int version) { // delete beggining part of path to get only dir inside repo String directory = node.getDirectory().toString().replace( manager.getPathToRepoCurrent(), ""); @@ -184,4 +187,90 @@ return hisFile; } + + public static File getNextHistoryPropFile(FileNode node, + FileContentManager manager, int version) { + // delete beggining part of path to get only dir inside repo + String directory = node.getDirectory().toString().replace( + manager.getPathToRepoCurrent(), ""); + + String pathToHistory = manager.getPathToRepoHistory() + + File.pathSeparator + directory + File.pathSeparator + + node.getNodeName() + "-his"; + + createHistoryStructure(pathToHistory); + + File hisFile = new File(pathToHistory + File.pathSeparator + version + + PROPERTIES_SUFFIX); + + return hisFile; + } + + public static Properties getPropertiesAtRevision(FileNode node, + FileContentManager manager, int version) throws IOException { + // delete beggining part of path to get only dir inside repo + String directory = node.getDirectory().toString().replace( + manager.getPathToRepoCurrent(), ""); + + String pathToHistory = manager.getPathToRepoHistory() + + File.pathSeparator + directory + File.pathSeparator + + node.getNodeName() + "-his"; + + File hisFile = new File(pathToHistory + File.pathSeparator + version + + PROPERTIES_SUFFIX); + + Properties props = new Properties(); + + if (hisFile.exists()) { + InputStream is = new FileInputStream(hisFile); + + props.load(is); + + is.close(); + + return props; + } + + throw new IOException("Couldn't find history props"); + } + + public static File getHistoryDir(FileDirectory directory, + FileContentManager manager) { + File historyDir = new File(manager.getPathToRepoHistory() + + File.pathSeparator + directory.getFullName() + "-his"); + + if (!historyDir.exists()) { + historyDir.mkdirs(); + } + + return historyDir; + } + + public static File getPropertiesFileForDirectory(FileDirectory directory, + FileContentManager manager) throws IOException { + File propsFile = new File(manager.getPathToRepoHistory() + + File.pathSeparator + directory.getFullName() + "-his" + File.pathSeparator + PROPS); + + if (!propsFile.exists()) { + getHistoryDir(directory, manager); + propsFile.createNewFile(); + } + + return propsFile; + } + + public static Properties getPropertiesForDirectory(FileDirectory directory, + FileContentManager manager) throws IOException { + File propsFile = getPropertiesFileForDirectory(directory, manager); + + Properties props = new Properties(); + + InputStream is = new FileInputStream(propsFile); + + props.load(is); + + is.close(); + + return props; + } } Deleted: trunk/forge/portal-extensions/shotoku/shotoku-files/src/java/org/jboss/shotoku/files/FilesContentManager.java =================================================================== --- trunk/forge/portal-extensions/shotoku/shotoku-files/src/java/org/jboss/shotoku/files/FilesContentManager.java 2006-01-27 20:49:45 UTC (rev 2220) +++ trunk/forge/portal-extensions/shotoku/shotoku-files/src/java/org/jboss/shotoku/files/FilesContentManager.java 2006-01-27 21:59:55 UTC (rev 2221) @@ -1,143 +0,0 @@ -/* - * JBoss, Home of Professional Open Source - * Copyright 2005, JBoss Inc., and individual contributors as indicated - * by the @authors tag. See the copyright.txt in the distribution for a - * full listing of individual contributors. - * - * This is free software; you can redistribute it and/or modify it - * under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation; either version 2.1 of - * the License, or (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this software; if not, write to the Free - * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA - * 02110-1301 USA, or see the FSF site: http://www.fsf.org. - */ -package org.jboss.shotoku.files; - -import java.io.File; -import java.util.Collection; - -import org.jboss.logging.Logger; -import org.jboss.shotoku.ContentManager; -import org.jboss.shotoku.Directory; -import org.jboss.shotoku.Node; -import org.jboss.shotoku.Resource; -import org.jboss.shotoku.exceptions.DeleteException; -import org.jboss.shotoku.exceptions.RepositoryException; -import org.jboss.shotoku.exceptions.ResourceDoesNotExist; -import org.jboss.shotoku.exceptions.SaveException; - -public class FilesContentManager extends ContentManager { - - private String pathToRepo; - - private String pathToRepoCurrent; - - private String pathToRepoHistory; - - private final static String CURRENT = "CURRENT"; - - private final static String HISTORY = "HISTORY"; - - private Logger log = Logger.getLogger(FilesContentManager.class); - - public FilesContentManager(String id, String prefix) throws RepositoryException { - super(id, prefix); - - // add separator at the end and at the begginig - if (!prefix.startsWith("/")) { - prefix = "/" + prefix; - } - - if (!prefix.endsWith("/")) { - prefix += "/"; - } - - pathToRepo = getProperty("shotoku.default.localpath"); - - if (pathToRepo == null) { - throw new RepositoryException("shotoku.default.localpath is not set in properties"); - } - else if (!(new File(pathToRepo)).exists() || !(new File(pathToRepo)).isDirectory()){ - throw new RepositoryException(pathToRepo+" doesn't exist or isn't a directory"); - } - - // create paths - - pathToRepoCurrent = pathToRepo + File.pathSeparator + CURRENT; - pathToRepoHistory = pathToRepo + File.pathSeparator + HISTORY; - - // check for current and history existance - File fileCur = new File(pathToRepoCurrent); - File fileHis = new File(pathToRepoHistory); - - // create CURRENT folder if it doesn't exist - if (!fileCur.exists()) { - fileCur.mkdirs(); - log.info("Added CURRENT folder"); - } - - // create HISTORY folder if it doesn't exist - if (!fileHis.exists()) { - fileHis.mkdirs(); - log.info("Added HISTORY folder"); - } - } - - @Override - public Directory getRootDirectory() throws RepositoryException { - return new FileDirectory(getPathToRepoCurrent(), this); - } - - @Override - public Node getNode(String nodeName) throws ResourceDoesNotExist, - RepositoryException { - return getRootDirectory().getNode(nodeName); - } - - @Override - public Directory getDirectory(String dirName) throws ResourceDoesNotExist, - RepositoryException { - return getRootDirectory().getDirectory(dirName); - } - - @Override - public void save(Collection<Resource> resources, String message) - throws SaveException, RepositoryException { - for (Resource resource : resources) { - resource.save(message); - } - } - - @Override - public void delete(Collection<Resource> resources) throws DeleteException, - RepositoryException { - for (Resource resource : resources) { - resource.delete(); - } - } - - public String getPathToRepo() { - return pathToRepo; - } - - public String getPathToRepoCurrent() { - return pathToRepoCurrent + prefix; - } - - public String getPathToRepoHistory() { - return pathToRepoHistory + prefix; - } - - public String getPrefix() { - return prefix; - } - -} Modified: trunk/forge/portal-extensions/shotoku/shotoku-svn/maven.xml =================================================================== --- trunk/forge/portal-extensions/shotoku/shotoku-svn/maven.xml 2006-01-27 20:49:45 UTC (rev 2220) +++ trunk/forge/portal-extensions/shotoku/shotoku-svn/maven.xml 2006-01-27 21:59:55 UTC (rev 2221) @@ -21,6 +21,9 @@ todir="target/${shotoku.ear.dir}" overwrite="true" file="${maven.repo.local}/shotoku/jars/shotoku-base.jar" /> <ant:copy + todir="target/${shotoku.ear.dir}" overwrite="true" + file="${maven.repo.local}/shotoku/jars/shotoku-files.jar" /> + <ant:copy todir="target/${shotoku.ear.dir}" overwrite="true" file="${maven.repo.local}/commons-configuration/jars/commons-configuration-1.1.jar" /> <ant:copy @@ -38,17 +41,12 @@ <ant:filename name="velocity*-1.4.jar" /> </ant:fileset> </ant:copy> + <ant:copy todir="target/${shotoku.ear.dir}"> <ant:fileset dir="src/app" flatten="true" overwrite="true"> <ant:filename name="**" /> </ant:fileset> </ant:copy> - - <!-- Copying the ear to the deploy directory. --> - <ant:copy todir="${local.deploy.dir}"> - <ant:fileset dir="target" flatten="true" overwrite="true"> - <ant:filename name="${shotoku.ear.dir}/**" /> - </ant:fileset> - </ant:copy> + </goal> </project> Modified: trunk/forge/portal-extensions/shotoku/shotoku-svn/project.properties =================================================================== --- trunk/forge/portal-extensions/shotoku/shotoku-svn/project.properties 2006-01-27 20:49:45 UTC (rev 2220) +++ trunk/forge/portal-extensions/shotoku/shotoku-svn/project.properties 2006-01-27 21:59:55 UTC (rev 2221) @@ -3,5 +3,3 @@ maven.war.src=${basedir}/src/web maven.ejb.excludes=**/*Listener*,**/listener maven.war.classes.excludes=**/*Bean* - -shotoku.ear.dir=00shotoku.ear \ No newline at end of file Modified: trunk/forge/portal-extensions/shotoku/shotoku-svn/project.xml =================================================================== --- trunk/forge/portal-extensions/shotoku/shotoku-svn/project.xml 2006-01-27 20:49:45 UTC (rev 2220) +++ trunk/forge/portal-extensions/shotoku/shotoku-svn/project.xml 2006-01-27 21:59:55 UTC (rev 2221) @@ -35,6 +35,15 @@ <ejb.manifest.classpath>true</ejb.manifest.classpath> </properties> </dependency> + + <dependency> + <groupId>shotoku</groupId> + <artifactId>shotoku-files</artifactId> + <jar>shotoku-files.jar</jar> + <properties> + <ejb.manifest.classpath>true</ejb.manifest.classpath> + </properties> + </dependency> <dependency> <groupId>velocity</groupId> |
From: <jbo...@li...> - 2006-01-27 20:49:55
|
Author: aron.gombas Date: 2006-01-27 15:49:45 -0500 (Fri, 27 Jan 2006) New Revision: 2220 Modified: trunk/labs/kosmos/web-portlet/pages/svn_monitoring.jsp trunk/labs/kosmos/web-portlet/pages/svn_monitoring_activity_details.jsp trunk/labs/kosmos/web-portlet/pages/svn_monitoring_repository_details.jsp Log: Cosmetic changes Modified: trunk/labs/kosmos/web-portlet/pages/svn_monitoring.jsp =================================================================== --- trunk/labs/kosmos/web-portlet/pages/svn_monitoring.jsp 2006-01-27 19:39:24 UTC (rev 2219) +++ trunk/labs/kosmos/web-portlet/pages/svn_monitoring.jsp 2006-01-27 20:49:45 UTC (rev 2220) @@ -4,15 +4,15 @@ <fmt:setBundle basename="hu.midori.kosmos.portlet.svn.svn_monitoring" scope="application"/> <display:table name="${repositories}" id="repositoriesIt" requestURI="<%=renderResponse.createRenderURL().toString() %>" requestURIcontext="false"> - <c:set var="id" scope="page" value="${repositoriesIt.id}"/> + <c:set var="id" scope="page" value="${repositoriesIt.id}"/> <display:column style="width:20px"> <c:choose> - <c:when test="${(repositoriesIt.latestTouchAgeInDays > 7) || (repositoriesIt.activity < 0.2)}"> + <c:when test="${(repositoriesIt.latestTouchAgeInDays > 31) || (repositoriesIt.activity < 0.05)}"> <img src="<%= renderRequest.getContextPath() %>/pages/images/old.gif" title="<fmt:message key="legend.old"/>"/> </c:when> <c:otherwise> - </c:otherwise> + </c:otherwise> </c:choose> </display:column> <display:column titleKey="svnrepository.location" style="white-space:nowrap" sortProperty="location" sortable="true"> @@ -21,34 +21,34 @@ <a href="<portlet:renderURL><portlet:param name="action" value="viewRepositoryDetails"/><portlet:param name="id" value="<%= pageContext.getAttribute("id").toString() %>"/></portlet:renderURL>"> <img src="<%= renderRequest.getContextPath() %>/pages/images/info.gif" title="<fmt:message key="svnrepository.repositoryDetails"/>" border="0"/> </a> - </display:column> + </display:column> <display:column titleKey="svnrepository.revision" style="white-space:nowrap" sortProperty="revision" sortable="true"> <c:out value="${repositoriesIt.revision}"/> <a href="<portlet:renderURL><portlet:param name="action" value="viewRevisionDetails"/><portlet:param name="id" value="<%= pageContext.getAttribute("id").toString() %>"/></portlet:renderURL>"> - <img src="<%= renderRequest.getContextPath() %>/pages/images/info.gif" title="<fmt:message key="svnrepository.revisionDetails"/>" border="0"/> + <img src="<%= renderRequest.getContextPath() %>/pages/images/info.gif" title="<fmt:message key="svnrepository.revisionDetails"/>" border="0"/> </a> </display:column> <display:column titleKey="svnrepository.committersTotal" style="white-space:nowrap" sortProperty="committersTotal" sortable="true"> <fmt:formatNumber value="${repositoriesIt.committersTotal}"/> <a href="<portlet:renderURL><portlet:param name="action" value="viewCommitterDetails"/><portlet:param name="id" value="<%= pageContext.getAttribute("id").toString() %>"/></portlet:renderURL>"> - <img src="<%= renderRequest.getContextPath() %>/pages/images/info.gif" title="<fmt:message key="svnrepository.committerDetails"/>" border="0"/> + <img src="<%= renderRequest.getContextPath() %>/pages/images/info.gif" title="<fmt:message key="svnrepository.committerDetails"/>" border="0"/> </a> - </display:column> + </display:column> <display:column titleKey="svnrepository.activityLast7Days" style="white-space:nowrap" sortProperty="activity" sortable="true"> - <c:if test="${repositoriesIt.activity < 0.5}"><span class="portlet-msg-error"></c:if> + <c:if test="${repositoriesIt.activity < 0.05}"><span class="portlet-msg-error"></c:if> <fmt:formatNumber value="${repositoriesIt.activity}" type="percent" minFractionDigits="1" maxFractionDigits="1"/> - <c:if test="${repositoriesIt.activity < 0.5}"></span></c:if> + <c:if test="${repositoriesIt.activity < 0.05}"></span></c:if> - <a href="<portlet:renderURL><portlet:param name="action" value="viewActivityDetails"/><portlet:param name="id" value="<%= pageContext.getAttribute("id").toString() %>"/></portlet:renderURL>"> - <img src="<%= renderRequest.getContextPath() %>/pages/images/info.gif" title="<fmt:message key="svnrepository.activityDetails"/>" border="0"/> + <a href="<portlet:renderURL><portlet:param name="action" value="viewActivityDetails"/><portlet:param name="id" value="<%= pageContext.getAttribute("id").toString() %>"/></portlet:renderURL>"> + <img src="<%= renderRequest.getContextPath() %>/pages/images/info.gif" title="<fmt:message key="svnrepository.activityDetails"/>" border="0"/> </a> </display:column> <display:column titleKey="svnrepository.latestTouchAge" style="white-space:nowrap" sortProperty="latestTouchAge" sortable="true"> - <c:if test="${repositoriesIt.latestTouchAgeInDays > 7}"><span class="portlet-msg-error"></c:if> + <c:if test="${repositoriesIt.latestTouchAgeInDays > 31}"><span class="portlet-msg-error"></c:if> <kosmos:age time="${repositoriesIt.latestTouchAge}"/> - <c:if test="${repositoriesIt.latestTouchAgeInDays > 7}"></span></c:if> - </display:column> + <c:if test="${repositoriesIt.latestTouchAgeInDays > 31}"></span></c:if> + </display:column> <display:footer> <%@include file="includes/table_footer.jsp"%> </display:footer> Modified: trunk/labs/kosmos/web-portlet/pages/svn_monitoring_activity_details.jsp =================================================================== --- trunk/labs/kosmos/web-portlet/pages/svn_monitoring_activity_details.jsp 2006-01-27 19:39:24 UTC (rev 2219) +++ trunk/labs/kosmos/web-portlet/pages/svn_monitoring_activity_details.jsp 2006-01-27 20:49:45 UTC (rev 2220) @@ -4,7 +4,7 @@ <fmt:setBundle basename="hu.midori.kosmos.portlet.svn.svn_monitoring" scope="application"/> <table> - <tr class="portlet-section-body"> + <tr class="portlet-section-body"> <td><fmt:message key="svnrepository.commitsToday"/>:</td> <td><fmt:formatNumber value="${repository.commitsToday}"/></td> <td><fmt:message key="svnrepository.committersToday"/>:</td> @@ -16,7 +16,7 @@ <td><fmt:message key="svnrepository.committersLast7Days"/>:</td> <td><fmt:formatNumber value="${repository.committersLast7Days}"/></td> </tr> - <tr class="portlet-section-body"> + <tr class="portlet-section-body"> <td><fmt:message key="svnrepository.commitsLast31Days"/>:</td> <td><fmt:formatNumber value="${repository.commitsLast31Days}"/></td> <td><fmt:message key="svnrepository.committersLast31Days"/>:</td> @@ -31,12 +31,12 @@ <tr class="portlet-section-body"> <td valign="top"><fmt:message key="svnrepository.commitHistory"/>:</td> <td valign="top"><img src="<c:out value="${repository.commitsPerWeekChartUrl}"/>" title="<fmt:message key="svnrepository.commitHistory"/>"/></td> - <td colspan="2" valign="top"> - + <td valign="top" colspan="2"> + <c:set var="listSize" value="${fn:length(repository.commits)}"/> <c:set var="listIndex" value="0"/> <%@include file="includes/table_expander.jsp" %> - + <table> <c:forEach var="commit" items="${repository.commits}" varStatus="status"> <c:choose> @@ -49,7 +49,7 @@ </c:choose> <td><c:out value="${commit.message}"/><br/>(A<c:out value="${commit.addedFiles}"/> D<c:out value="${commit.deletedFiles}"/> U<c:out value="${commit.modifiedFiles}"/> R<c:out value="${commit.replacedFiles}"/>)</td> <td><c:out value="${commit.author}"/></td> - <td> + <td> <c:if test="${commit.ageInDays == 0}"><span class="portlet-msg-alert"></c:if> <kosmos:age time="${commit.age}"/> <c:if test="${commit.ageInDays == 0}"></span></c:if> @@ -59,10 +59,9 @@ </table> </td> </tr> - <%@include file="includes/table_footer.jsp"%> + <%@include file="includes/table_footer.jsp"%> </table> - + <form action="<portlet:renderURL/>" method="post"> <input type="submit" class="portlet-form-button" name="submit" value="<fmt:message key="action.back"/>"/> </form> - \ No newline at end of file Modified: trunk/labs/kosmos/web-portlet/pages/svn_monitoring_repository_details.jsp =================================================================== --- trunk/labs/kosmos/web-portlet/pages/svn_monitoring_repository_details.jsp 2006-01-27 19:39:24 UTC (rev 2219) +++ trunk/labs/kosmos/web-portlet/pages/svn_monitoring_repository_details.jsp 2006-01-27 20:49:45 UTC (rev 2220) @@ -4,7 +4,7 @@ <fmt:setBundle basename="hu.midori.kosmos.portlet.svn.svn_monitoring" scope="application"/> <table> - <tr class="portlet-section-body"> + <tr class="portlet-section-body"> <td><fmt:message key="svnrepository.dirs"/>:</td> <td><fmt:formatNumber value="${repository.dirs}"/></td> <td/> @@ -19,24 +19,25 @@ <td><fmt:formatNumber value="${repository.dirs + repository.files}"/></td> <td/> </tr> - <tr class="portlet-section-alternate"> + <tr class="portlet-section-alternate"> <td><fmt:message key="svnrepository.totalFileSize"/>:</td> <td><fmt:formatNumber value="${repository.totalFileSize}"/> B</td> <td/> </tr> - <tr class="portlet-section-body"> + <tr class="portlet-section-body"> <td><fmt:message key="svnrepository.repositoryEntryHistory"/>:</td> - <td><img src="<c:out value="${repository.repoEntriesPerWeekChartUrl}"/>" title="<fmt:message key="svnrepository.repositoryEntryHistory"/>"/></td> + <td valign="top"><img src="<c:out value="${repository.repoEntriesPerWeekChartUrl}"/>" title="<fmt:message key="svnrepository.repositoryEntryHistory"/>"/></td> <td/> </tr> - <tr class="portlet-section-alternate"> - <td><fmt:message key="svnrepository.filesByFileType"/>:</td> - <td><img src="<c:out value="${repository.filesPerFileTypeChartUrl}"/>" title="<fmt:message key="svnrepository.filesPerFileType"/>"/></td> - <td> + <tr class="portlet-section-alternate"> + <td valign="top"><fmt:message key="svnrepository.filesByFileType"/>:</td> + <td valign="top"><img src="<c:out value="${repository.filesPerFileTypeChartUrl}"/>" title="<fmt:message key="svnrepository.filesPerFileType"/>"/></td> + <td valign="top"> + <c:set var="listSize" value="${fn:length(repository.filesPerFileType)}"/> <c:set var="listIndex" value="0"/> <%@include file="includes/table_expander.jsp" %> - + <table> <c:forEach var="item" items="${repository.filesPerFileType}" varStatus="status"> <c:choose> @@ -53,12 +54,11 @@ </tr> </c:forEach> </table> - </td> + </td> </tr> - <%@include file="includes/table_footer.jsp"%> + <%@include file="includes/table_footer.jsp"%> </table> <form action="<portlet:renderURL/>" method="post"> <input type="submit" class="portlet-form-button" name="submit" value="<fmt:message key="action.back"/>"/> </form> - \ No newline at end of file |
From: <jbo...@li...> - 2006-01-27 19:39:30
|
Author: rl...@jb... Date: 2006-01-27 14:39:24 -0500 (Fri, 27 Jan 2006) New Revision: 2219 Modified: trunk/labs/jbossbuild/projects/maven-plugins/javacc-maven-plugin/pom.xml Log: updated version number used to be distinct Modified: trunk/labs/jbossbuild/projects/maven-plugins/javacc-maven-plugin/pom.xml =================================================================== --- trunk/labs/jbossbuild/projects/maven-plugins/javacc-maven-plugin/pom.xml 2006-01-27 13:44:30 UTC (rev 2218) +++ trunk/labs/jbossbuild/projects/maven-plugins/javacc-maven-plugin/pom.xml 2006-01-27 19:39:24 UTC (rev 2219) @@ -7,7 +7,7 @@ </parent> <artifactId>javacc-maven-plugin</artifactId> <packaging>maven-plugin</packaging> - <version>0.6.1-SNAPSHOT</version> + <version>0.6.1.1</version> <name>Maven Javacc Plugin</name> <dependencies> <dependency> |
From: <jbo...@li...> - 2006-01-27 13:44:36
|
Author: wrzep Date: 2006-01-27 08:44:30 -0500 (Fri, 27 Jan 2006) New Revision: 2218 Modified: trunk/forge/portal-extensions/forge-status/src/java/org/jboss/forge/status/Column.java Log: http://jira.jboss.com/jira/browse/JBLAB-595 Pawel Modified: trunk/forge/portal-extensions/forge-status/src/java/org/jboss/forge/status/Column.java =================================================================== --- trunk/forge/portal-extensions/forge-status/src/java/org/jboss/forge/status/Column.java 2006-01-27 13:21:42 UTC (rev 2217) +++ trunk/forge/portal-extensions/forge-status/src/java/org/jboss/forge/status/Column.java 2006-01-27 13:44:30 UTC (rev 2218) @@ -98,9 +98,14 @@ if (plugin.getLinkName() != null) { entryContext.next("hasLink"); entryContext.put("special-link", plugin.getLink(projectId)); + + if (plugin.getLink(projectId) != null) { + entryContext.next("project-hasLink"); + } } else { entryContext.next("hasNotLink"); } + } } catch (Exception e) { log.error("Could not get value for plugin: " + plugin.getId(), e); |
From: <jbo...@li...> - 2006-01-27 13:21:51
|
Author: wrzep Date: 2006-01-27 08:21:42 -0500 (Fri, 27 Jan 2006) New Revision: 2217 Modified: trunk/forge/portal-extensions/forge-status/src/java/org/jboss/forge/status/Column.java trunk/forge/portal-extensions/forge-status/src/java/org/jboss/forge/status/plugins/Plugin.java trunk/forge/portal-extensions/forge-status/src/java/org/jboss/forge/status/plugins/cc/CcStatusPlugin.java trunk/forge/portal-extensions/forge-status/src/java/org/jboss/forge/status/plugins/jira/JiraStatusPlugin.java trunk/forge/portal-extensions/forge-status/src/java/org/jboss/forge/status/plugins/svn/SvnStatusPlugin.java Log: Displaying additional link (eg. JIRA location) only when plugin supports it. http://jira.jboss.com/jira/browse/JBLAB-595 Pawel Modified: trunk/forge/portal-extensions/forge-status/src/java/org/jboss/forge/status/Column.java =================================================================== --- trunk/forge/portal-extensions/forge-status/src/java/org/jboss/forge/status/Column.java 2006-01-26 21:57:20 UTC (rev 2216) +++ trunk/forge/portal-extensions/forge-status/src/java/org/jboss/forge/status/Column.java 2006-01-27 13:21:42 UTC (rev 2217) @@ -76,6 +76,13 @@ public void fillHeaderInfo(DelegateContext columnContext) { columnContext.put("name", getName()); columnContext.put("id", getId()); + + if (plugin.getLinkName() != null) { + columnContext.next("hasLink"); + columnContext.put("special-link-name", plugin.getLinkName()); + } else { + columnContext.next("hasNotLink"); + } } public void fillValue(DelegateContext entryContext, String projectId) { @@ -87,7 +94,13 @@ if (value != null) { entryContext.put("value", Long.toString(value)); entryContext.put("rate", Integer.toString(rate)); - entryContext.put("special-link", plugin.getLink(projectId)); + + if (plugin.getLinkName() != null) { + entryContext.next("hasLink"); + entryContext.put("special-link", plugin.getLink(projectId)); + } else { + entryContext.next("hasNotLink"); + } } } catch (Exception e) { log.error("Could not get value for plugin: " + plugin.getId(), e); Modified: trunk/forge/portal-extensions/forge-status/src/java/org/jboss/forge/status/plugins/Plugin.java =================================================================== --- trunk/forge/portal-extensions/forge-status/src/java/org/jboss/forge/status/plugins/Plugin.java 2006-01-26 21:57:20 UTC (rev 2216) +++ trunk/forge/portal-extensions/forge-status/src/java/org/jboss/forge/status/plugins/Plugin.java 2006-01-27 13:21:42 UTC (rev 2217) @@ -76,6 +76,14 @@ return null; } + /** For the given project returns name of link associated with this plugin + * or null if projects have not any link associated with this plugin. + * This method should be overrided inside plugins that have some links associated with projects. + */ + public String getLinkName() { + return null; + } + /** * For the given project returns it's rate. * Rate is computed as project's score share in the higest score. Modified: trunk/forge/portal-extensions/forge-status/src/java/org/jboss/forge/status/plugins/cc/CcStatusPlugin.java =================================================================== --- trunk/forge/portal-extensions/forge-status/src/java/org/jboss/forge/status/plugins/cc/CcStatusPlugin.java 2006-01-26 21:57:20 UTC (rev 2216) +++ trunk/forge/portal-extensions/forge-status/src/java/org/jboss/forge/status/plugins/cc/CcStatusPlugin.java 2006-01-27 13:21:42 UTC (rev 2217) @@ -43,6 +43,8 @@ private static final String CC_SERVICE_PROPERTY = "cc-service"; private static final String CC_ADRESS_TAG = "cc-adress"; + + private static final String CC_LINK_NAME = "CruiseControl location"; @Override protected String getKosmosServiceTag() { return CC_SERVICE_PROPERTY;}; @@ -104,5 +106,9 @@ public String getLink(String projectId) { return getCcURL(projectId); } - + + @Override + public String getLinkName() { + return CC_LINK_NAME; + } } Modified: trunk/forge/portal-extensions/forge-status/src/java/org/jboss/forge/status/plugins/jira/JiraStatusPlugin.java =================================================================== --- trunk/forge/portal-extensions/forge-status/src/java/org/jboss/forge/status/plugins/jira/JiraStatusPlugin.java 2006-01-26 21:57:20 UTC (rev 2216) +++ trunk/forge/portal-extensions/forge-status/src/java/org/jboss/forge/status/plugins/jira/JiraStatusPlugin.java 2006-01-27 13:21:42 UTC (rev 2217) @@ -43,6 +43,8 @@ private static final String JIRA_SERVICE_PROPERTY = "jira-service"; private static final String JIRA_ADRESS_TAG = "jira-adress"; + + private static final String JIRA_LINK_NAME = "JIRA location"; protected String getKosmosServiceTag() { return JIRA_SERVICE_PROPERTY;}; @@ -102,4 +104,9 @@ public String getLink(String projectId) { return getJiraURL(projectId); } + + @Override + public String getLinkName() { + return JIRA_LINK_NAME; + } } Modified: trunk/forge/portal-extensions/forge-status/src/java/org/jboss/forge/status/plugins/svn/SvnStatusPlugin.java =================================================================== --- trunk/forge/portal-extensions/forge-status/src/java/org/jboss/forge/status/plugins/svn/SvnStatusPlugin.java 2006-01-26 21:57:20 UTC (rev 2216) +++ trunk/forge/portal-extensions/forge-status/src/java/org/jboss/forge/status/plugins/svn/SvnStatusPlugin.java 2006-01-27 13:21:42 UTC (rev 2217) @@ -43,6 +43,8 @@ private static final String SVN_SERVICE_PROPERTY = "svn-service"; private static final String SVN_REPO_ADRESS_TAG = "svn-repo"; + + private static final String SVN_LINK_NAME = "Svn repository location"; protected String getKosmosServiceTag() { return SVN_SERVICE_PROPERTY;}; @@ -103,4 +105,9 @@ return getRepoURL(projectId); } + @Override + public String getLinkName() { + return SVN_LINK_NAME; + } + } |
Author: rl...@jb... Date: 2006-01-26 16:57:20 -0500 (Thu, 26 Jan 2006) New Revision: 2216 Added: trunk/labs/jbossbuild/projects/maven-plugins/maven-jboss-compiler-plugin/ trunk/labs/jbossbuild/projects/maven-plugins/maven-jboss-compiler-plugin/.classpath trunk/labs/jbossbuild/projects/maven-plugins/maven-jboss-compiler-plugin/.project trunk/labs/jbossbuild/projects/maven-plugins/maven-jboss-compiler-plugin/.wtpmodules trunk/labs/jbossbuild/projects/maven-plugins/maven-jboss-compiler-plugin/pom.xml trunk/labs/jbossbuild/projects/maven-plugins/maven-jboss-compiler-plugin/src/ trunk/labs/jbossbuild/projects/maven-plugins/maven-jboss-compiler-plugin/src/main/ trunk/labs/jbossbuild/projects/maven-plugins/maven-jboss-compiler-plugin/src/main/java/ trunk/labs/jbossbuild/projects/maven-plugins/maven-jboss-compiler-plugin/src/main/java/org/ trunk/labs/jbossbuild/projects/maven-plugins/maven-jboss-compiler-plugin/src/main/java/org/apache/ trunk/labs/jbossbuild/projects/maven-plugins/maven-jboss-compiler-plugin/src/main/java/org/apache/maven/ trunk/labs/jbossbuild/projects/maven-plugins/maven-jboss-compiler-plugin/src/main/java/org/apache/maven/plugin/ trunk/labs/jbossbuild/projects/maven-plugins/maven-jboss-compiler-plugin/src/main/java/org/apache/maven/plugin/AbstractCompilerMojo.java trunk/labs/jbossbuild/projects/maven-plugins/maven-jboss-compiler-plugin/src/main/java/org/apache/maven/plugin/CompilationFailureException.java trunk/labs/jbossbuild/projects/maven-plugins/maven-jboss-compiler-plugin/src/main/java/org/apache/maven/plugin/CompilerMojo.java trunk/labs/jbossbuild/projects/maven-plugins/maven-jboss-compiler-plugin/src/main/java/org/apache/maven/plugin/TestCompilerMojo.java trunk/labs/jbossbuild/projects/maven-plugins/maven-jboss-compiler-plugin/src/site/ trunk/labs/jbossbuild/projects/maven-plugins/maven-jboss-compiler-plugin/src/site/apt/ trunk/labs/jbossbuild/projects/maven-plugins/maven-jboss-compiler-plugin/src/site/apt/howto.apt trunk/labs/jbossbuild/projects/maven-plugins/maven-jboss-compiler-plugin/src/site/apt/introduction.apt trunk/labs/jbossbuild/projects/maven-plugins/maven-jboss-compiler-plugin/src/site/site.xml Log: initial entry of alternate compiler plugin Added: trunk/labs/jbossbuild/projects/maven-plugins/maven-jboss-compiler-plugin/.classpath =================================================================== --- trunk/labs/jbossbuild/projects/maven-plugins/maven-jboss-compiler-plugin/.classpath 2006-01-26 20:48:47 UTC (rev 2215) +++ trunk/labs/jbossbuild/projects/maven-plugins/maven-jboss-compiler-plugin/.classpath 2006-01-26 21:57:20 UTC (rev 2216) @@ -0,0 +1,14 @@ +<classpath> + <classpathentry kind="src" path="src/main/java"/> + <classpathentry kind="output" path="target/classes"/> + <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/> + <classpathentry kind="var" path="M2_REPO/org/codehaus/plexus/plexus-utils/1.0.4/plexus-utils-1.0.4.jar"/> + <classpathentry kind="var" path="M2_REPO/junit/junit/3.8.1/junit-3.8.1.jar"/> + <classpathentry kind="var" path="M2_REPO/org/codehaus/plexus/plexus-compiler-javac/1.6-SNAPSHOT/plexus-compiler-javac-1.6-SNAPSHOT.jar"/> + <classpathentry kind="var" path="M2_REPO/org/codehaus/plexus/plexus-container-default/1.0-alpha-8/plexus-container-default-1.0-alpha-8.jar"/> + <classpathentry kind="var" path="M2_REPO/classworlds/classworlds/1.1-alpha-2/classworlds-1.1-alpha-2.jar"/> + <classpathentry kind="var" path="M2_REPO/org/apache/maven/maven-artifact/2.0/maven-artifact-2.0.jar"/> + <classpathentry kind="var" path="M2_REPO/org/apache/maven/maven-plugin-api/2.0/maven-plugin-api-2.0.jar"/> + <classpathentry kind="var" path="M2_REPO/org/codehaus/plexus/plexus-compiler-manager/1.6-SNAPSHOT/plexus-compiler-manager-1.6-SNAPSHOT.jar"/> + <classpathentry kind="var" path="M2_REPO/org/codehaus/plexus/plexus-compiler-api/1.6-SNAPSHOT/plexus-compiler-api-1.6-SNAPSHOT.jar"/> +</classpath> \ No newline at end of file Added: trunk/labs/jbossbuild/projects/maven-plugins/maven-jboss-compiler-plugin/.project =================================================================== --- trunk/labs/jbossbuild/projects/maven-plugins/maven-jboss-compiler-plugin/.project 2006-01-26 20:48:47 UTC (rev 2215) +++ trunk/labs/jbossbuild/projects/maven-plugins/maven-jboss-compiler-plugin/.project 2006-01-26 21:57:20 UTC (rev 2216) @@ -0,0 +1,28 @@ +<projectDescription> + <name>maven-jboss-compiler-plugin</name> + <comment>Maven plugin parent</comment> + <projects/> + <buildSpec> + <buildCommand> + <name>org.eclipse.jdt.core.javabuilder</name> + <arguments/> + </buildCommand> + <buildCommand> + <name>org.eclipse.wst.common.modulecore.ComponentStructuralBuilder</name> + <arguments/> + </buildCommand> + <buildCommand> + <name>org.eclipse.wst.validation.validationbuilder</name> + <arguments/> + </buildCommand> + <buildCommand> + <name>org.eclipse.wst.common.modulecore.ComponentStructuralBuilderDependencyResolver</name> + <arguments/> + </buildCommand> + </buildSpec> + <natures> + <nature>org.eclipse.jdt.core.javanature</nature> + <nature>org.eclipse.jem.workbench.JavaEMFNature</nature> + <nature>org.eclipse.wst.common.modulecore.ModuleCoreNature</nature> + </natures> +</projectDescription> \ No newline at end of file Added: trunk/labs/jbossbuild/projects/maven-plugins/maven-jboss-compiler-plugin/.wtpmodules =================================================================== --- trunk/labs/jbossbuild/projects/maven-plugins/maven-jboss-compiler-plugin/.wtpmodules 2006-01-26 20:48:47 UTC (rev 2215) +++ trunk/labs/jbossbuild/projects/maven-plugins/maven-jboss-compiler-plugin/.wtpmodules 2006-01-26 21:57:20 UTC (rev 2216) @@ -0,0 +1,8 @@ +<project-modules id="moduleCoreId"> + <wb-module deploy-name="maven-jboss-compiler-plugin"> + <module-type module-type-id="jst.utility"> + <property name="java-output-path" value="/target/classes"/> + </module-type> + <wb-resource deploy-path="/" source-path="src/main/java"/> + </wb-module> +</project-modules> \ No newline at end of file Added: trunk/labs/jbossbuild/projects/maven-plugins/maven-jboss-compiler-plugin/pom.xml =================================================================== --- trunk/labs/jbossbuild/projects/maven-plugins/maven-jboss-compiler-plugin/pom.xml 2006-01-26 20:48:47 UTC (rev 2215) +++ trunk/labs/jbossbuild/projects/maven-plugins/maven-jboss-compiler-plugin/pom.xml 2006-01-26 21:57:20 UTC (rev 2216) @@ -0,0 +1,41 @@ +<project> + <parent> + <artifactId>maven-plugin-parent</artifactId> + <groupId>org.apache.maven.plugins</groupId> + <version>2.0</version> + </parent> + <modelVersion>4.0.0</modelVersion> + <artifactId>maven-jboss-compiler-plugin</artifactId> + <packaging>maven-plugin</packaging> + <name>Maven Compiler Plugin</name> + <version>2.0.1-SNAPSHOT</version> + <inceptionYear>2001</inceptionYear> + <dependencies> + <dependency> + <groupId>org.codehaus.plexus</groupId> + <artifactId>plexus-utils</artifactId> + <version>1.0.4</version> + </dependency> + <dependency> + <groupId>org.codehaus.plexus</groupId> + <artifactId>plexus-compiler-api</artifactId> + <version>1.6-SNAPSHOT</version> + </dependency> + <dependency> + <groupId>org.codehaus.plexus</groupId> + <artifactId>plexus-compiler-manager</artifactId> + <version>1.6-SNAPSHOT</version> + </dependency> + <dependency> + <groupId>org.codehaus.plexus</groupId> + <artifactId>plexus-compiler-javac</artifactId> + <version>1.6-SNAPSHOT</version> + <scope>runtime</scope> + </dependency> + <dependency> + <groupId>org.apache.maven</groupId> + <artifactId>maven-artifact</artifactId> + <version>2.0</version> + </dependency> + </dependencies> +</project> Added: trunk/labs/jbossbuild/projects/maven-plugins/maven-jboss-compiler-plugin/src/main/java/org/apache/maven/plugin/AbstractCompilerMojo.java =================================================================== --- trunk/labs/jbossbuild/projects/maven-plugins/maven-jboss-compiler-plugin/src/main/java/org/apache/maven/plugin/AbstractCompilerMojo.java 2006-01-26 20:48:47 UTC (rev 2215) +++ trunk/labs/jbossbuild/projects/maven-plugins/maven-jboss-compiler-plugin/src/main/java/org/apache/maven/plugin/AbstractCompilerMojo.java 2006-01-26 21:57:20 UTC (rev 2216) @@ -0,0 +1,621 @@ +package org.apache.maven.plugin; + +/* + * Copyright 2001-2005 The Apache Software Foundation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.File; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.codehaus.plexus.compiler.Compiler; +import org.codehaus.plexus.compiler.CompilerConfiguration; +import org.codehaus.plexus.compiler.CompilerError; +import org.codehaus.plexus.compiler.CompilerException; +import org.codehaus.plexus.compiler.CompilerOutputStyle; +import org.codehaus.plexus.compiler.manager.CompilerManager; +import org.codehaus.plexus.compiler.manager.NoSuchCompilerException; +import org.codehaus.plexus.compiler.util.scan.InclusionScanException; +import org.codehaus.plexus.compiler.util.scan.SourceInclusionScanner; +import org.codehaus.plexus.compiler.util.scan.mapping.SingleTargetSourceMapping; +import org.codehaus.plexus.compiler.util.scan.mapping.SourceMapping; +import org.codehaus.plexus.compiler.util.scan.mapping.SuffixMapping; +import org.codehaus.plexus.util.StringUtils; + +/** + * TODO: At least one step could be optimized, currently the plugin will do two + * scans of all the source code if the compiler has to have the entire set of + * sources. This is currently the case for at least the C# compiler and most + * likely all the other .NET compilers too. + * + * @author others + * @author <a href="mailto:tr...@in...">Trygve Laugstøl</a> + * @version $Id: StaleSourceScannerTest.java 2393 2005-08-08 22:32:59Z kenney $ + */ +public abstract class AbstractCompilerMojo + extends AbstractMojo +{ + // ---------------------------------------------------------------------- + // Configurables + // ---------------------------------------------------------------------- + + /** + * Whether to include debugging information in the compiled class files. + * The default value is true. + * + * @parameter expression="${maven.compiler.debug}" default-value="true" + */ + private boolean debug; + + /** + * Whether to output messages about what the compiler is doing + * + * @parameter default-value="false" + */ + private boolean verbose; + + /** + * Output source locations where deprecated APIs are used + * + * @parameter + */ + private boolean showDeprecation; + + /** + * Optimize compiled code using the compiler's optimization methods + * + * @parameter default-value="false" + */ + private boolean optimize; + + /** + * Output warnings + * + * @parameter + */ + private boolean showWarnings; + + /** + * The -source argument for the Java compiler + * + * @parameter + */ + private String source; + + /** + * The -target argument for the Java compiler + * + * @parameter + */ + private String target; + + /** + * The -encoding argument for the Java compiler + * + * @parameter + */ + private String encoding; + + /** + * The granularity in milliseconds of the last modification + * date for testing whether a source needs recompilation + * + * @parameter expression="${lastModGranularityMs}" default-value="0" + */ + private int staleMillis; + + /** + * The compiler id of the compiler to use. + * + * @parameter default-value="javac" + */ + private String compilerId; + + /** + * Version of the compiler to use, ex. "1.3", "1.5" + * + * @parameter + */ + private String compilerVersion; + + /** + * Runs the compiler in a separate process. + * <p/> + * If not set the compiler will default to a executable. + * + * @parameter default-value="false" + */ + private boolean fork; + + /** + * Initial size, in megabytes, of the memory allocation pool, ex. "64", "64m". + * + * @parameter + */ + private String meminitial; + + /** + * maximum size, in megabytes, of the memory allocation pool, ex. "128", "128m". + * + * @parameter + */ + private String maxmem; + + /** + * The executable of the compiler to use. + * + * @parameter + */ + private String executable; + + /** + * Arguments to be passed to the compiler if fork is set to true. + * <p/> + * This is because the list of valid arguments passed to a Java compiler + * varies based on the compiler version. + * + * @parameter + */ + private Map compilerArguments; + + /** + * Used to control the name of the output file when compiling a set of + * sources to a single file. + * + * @parameter expression="${project.build.finalName}" + */ + private String outputFileName; + + /** + * Custom compiliation classpath locations to pass to the compiler. These + * classpaths will be placed at the beginning of the classpath list + * + * @parameter expression="${customClasspathLocations}" + */ + private ArrayList customClasspathLocations; + + + // ---------------------------------------------------------------------- + // Read-only parameters + // ---------------------------------------------------------------------- + + /** + * The directory to run the compiler from if fork is true. + * + * @parameter expression="${basedir}" + * @required + * @readonly + */ + private File basedir; + + /** + * The target directory of the compiler if fork is true. + * + * @parameter expression="${project.build.directory}" + * @required + * @readonly + */ + private File buildDirectory; + + /** + * Plexus compiler manager. + * + * @component + */ + private CompilerManager compilerManager; + + protected abstract SourceInclusionScanner getSourceInclusionScanner( int staleMillis ); + + protected abstract SourceInclusionScanner getSourceInclusionScanner( String inputFileEnding ); + + protected abstract List getClasspathElements(); + + protected abstract List getCompileSourceRoots(); + + protected abstract File getOutputDirectory(); + + public void execute() + throws MojoExecutionException, CompilationFailureException + { + // ---------------------------------------------------------------------- + // Look up the compiler. This is done before other code than can + // cause the mojo to return before the lookup is done possibly resulting + // in misconfigured POMs still building. + // ---------------------------------------------------------------------- + + Compiler compiler; + + getLog().debug( "Using compiler '" + compilerId + "'." ); + + try + { + compiler = compilerManager.getCompiler( compilerId ); + } + catch ( NoSuchCompilerException e ) + { + throw new MojoExecutionException( "No such compiler '" + e.getCompilerId() + "'." ); + } + + // ---------------------------------------------------------------------- + // + // ---------------------------------------------------------------------- + + List compileSourceRoots = removeEmptyCompileSourceRoots( getCompileSourceRoots() ); + + if ( compileSourceRoots.isEmpty() ) + { + getLog().info( "No sources to compile" ); + + return; + } + + ArrayList completeClasspath=new ArrayList(); + + //setup the classpath using a combination of project classpath and user defined classpath + if ( getCustomClasspathLocations() != null ) + completeClasspath.addAll(getCustomClasspathLocations()); + + completeClasspath.addAll(getClasspathElements()); + + if ( getLog().isDebugEnabled() ) + { + getLog().debug( "Source directories: " + compileSourceRoots.toString().replace( ',', '\n' ) ); + getLog().debug( "Classpath: " + completeClasspath.toString().replace( ',', '\n' ) ); + getLog().debug( "Output directory: " + getOutputDirectory() ); + } + + // ---------------------------------------------------------------------- + // Create the compiler configuration + // ---------------------------------------------------------------------- + + CompilerConfiguration compilerConfiguration = new CompilerConfiguration(); + + compilerConfiguration.setOutputLocation( getOutputDirectory().getAbsolutePath() ); + + compilerConfiguration.setClasspathEntries( completeClasspath ); + + compilerConfiguration.setSourceLocations( compileSourceRoots ); + + compilerConfiguration.setOptimize( optimize ); + + compilerConfiguration.setDebug( debug ); + + compilerConfiguration.setVerbose( verbose ); + + compilerConfiguration.setShowWarnings( showWarnings ); + + compilerConfiguration.setShowDeprecation( showDeprecation ); + + compilerConfiguration.setSourceVersion( source ); + + compilerConfiguration.setTargetVersion( target ); + + compilerConfiguration.setSourceEncoding( encoding ); + + if ( compilerArguments != null ) + { + LinkedHashMap cplrArgsCopy = new LinkedHashMap(); + for ( Iterator i = compilerArguments.entrySet().iterator(); i.hasNext(); ) + { + Map.Entry me = (Map.Entry) i.next(); + String key = (String) me.getKey(); + if ( !key.startsWith( "-" )) + { + key = "-" + key; + } + cplrArgsCopy.put( key, me.getValue() ); + } + compilerConfiguration.setCustomCompilerArguments( cplrArgsCopy ); + } + + compilerConfiguration.setFork( fork ); + + if( fork ) + { + if ( !StringUtils.isEmpty( meminitial ) ) + { + String value = getMemoryValue( meminitial ); + + if ( value != null ) + { + compilerConfiguration.setMeminitial( value ); + } + else + { + getLog().info( "Invalid value for meminitial '" + meminitial + "'. Ignoring this option." ); + } + } + + if ( !StringUtils.isEmpty( maxmem ) ) + { + String value = getMemoryValue( maxmem ); + + if ( value != null ) + { + compilerConfiguration.setMaxmem( value ); + } + else + { + getLog().info( "Invalid value for maxmem '" + maxmem + "'. Ignoring this option." ); + } + } + } + + compilerConfiguration.setExecutable( executable ); + + compilerConfiguration.setWorkingDirectory( basedir ); + + compilerConfiguration.setCompilerVersion( compilerVersion ); + + compilerConfiguration.setBuildDirectory( buildDirectory ); + + compilerConfiguration.setOutputFileName( outputFileName ); + + // TODO: have an option to always compile (without need to clean) + Set staleSources; + + boolean canUpdateTarget; + + try + { + staleSources = + computeStaleSources( compilerConfiguration, compiler, getSourceInclusionScanner( staleMillis ) ); + + canUpdateTarget = compiler.canUpdateTarget( compilerConfiguration ); + + if ( compiler.getCompilerOutputStyle().equals( CompilerOutputStyle.ONE_OUTPUT_FILE_FOR_ALL_INPUT_FILES ) && + !canUpdateTarget ) + { + getLog().info( "RESCANNING!" ); + // TODO: This second scan for source files is sub-optimal + String inputFileEnding = compiler.getInputFileEnding( compilerConfiguration ); + + Set sources = computeStaleSources( compilerConfiguration, compiler, + getSourceInclusionScanner( inputFileEnding ) ); + + compilerConfiguration.setSourceFiles( sources ); + } + else + { + compilerConfiguration.setSourceFiles( staleSources ); + } + } + catch ( CompilerException e ) + { + throw new MojoExecutionException( "Error while computing stale sources.", e ); + } + + if ( staleSources.isEmpty() ) + { + getLog().info( "Nothing to compile - all classes are up to date" ); + + return; + } + + // ---------------------------------------------------------------------- + // Dump configuration + // ---------------------------------------------------------------------- + + if ( getLog().isDebugEnabled() ) + { + getLog().debug( "Classpath:" ); + + for ( Iterator it = completeClasspath.iterator(); it.hasNext(); ) + { + String s = (String) it.next(); + + getLog().debug( " " + s ); + } + + getLog().debug( "Source roots:" ); + + for ( Iterator it = getCompileSourceRoots().iterator(); it.hasNext(); ) + { + String root = (String) it.next(); + + getLog().debug( " " + root ); + } + + if ( fork ) + { + try + { + String[] cl = compiler.createCommandLine( compilerConfiguration ); + if ( cl != null && cl.length > 0 ) + { + StringBuffer sb = new StringBuffer(); + sb.append( cl[0] ); + for ( int i = 1; i < cl.length; i++ ) + { + sb.append( " " ); + sb.append( cl[i] ); + } + getLog().debug( "Command line options:" ); + getLog().debug( sb ); + } + } + catch ( CompilerException ce ) + { + getLog().debug( ce ); + } + } + } + + // ---------------------------------------------------------------------- + // Compile! + // ---------------------------------------------------------------------- + + List messages; + + try + { + messages = compiler.compile( compilerConfiguration ); + } + catch ( Exception e ) + { + // TODO: don't catch Exception + throw new MojoExecutionException( "Fatal error compiling", e ); + } + + boolean compilationError = false; + + for ( Iterator i = messages.iterator(); i.hasNext(); ) + { + CompilerError message = (CompilerError) i.next(); + + if ( message.isError() ) + { + compilationError = true; + } + } + + if ( compilationError ) + { + throw new CompilationFailureException( messages ); + } + else + { + for ( Iterator i = messages.iterator(); i.hasNext(); ) + { + CompilerError message = (CompilerError) i.next(); + + getLog().warn( message.toString() ); + } + } + } + + private String getMemoryValue( String setting ) + { + String value = null; + + // Allow '128' or '128m' + if ( isDigits( setting ) ) + { + value = setting + "m"; + } + else + { + if ( ( isDigits( setting.substring( 0, setting.length() - 1 ) ) ) && + ( setting.toLowerCase().endsWith( "m" ) ) ) + { + value = setting; + } + } + return value; + } + + private boolean isDigits( String string ) + { + for ( int i = 0; i < string.length(); i++ ) + { + if ( !Character.isDigit( string.charAt( i ) ) ) + { + return false; + } + } + return true; + } + + private Set computeStaleSources( CompilerConfiguration compilerConfiguration, Compiler compiler, + SourceInclusionScanner scanner ) + throws MojoExecutionException, CompilerException + { + CompilerOutputStyle outputStyle = compiler.getCompilerOutputStyle(); + + SourceMapping mapping; + + File outputDirectory; + + if ( outputStyle == CompilerOutputStyle.ONE_OUTPUT_FILE_PER_INPUT_FILE ) + { + mapping = new SuffixMapping( compiler.getInputFileEnding( compilerConfiguration ), compiler + .getOutputFileEnding( compilerConfiguration ) ); + + outputDirectory = getOutputDirectory(); + } + else if ( outputStyle == CompilerOutputStyle.ONE_OUTPUT_FILE_FOR_ALL_INPUT_FILES ) + { + mapping = new SingleTargetSourceMapping( compiler.getInputFileEnding( compilerConfiguration ), compiler + .getOutputFile( compilerConfiguration ) ); + + outputDirectory = buildDirectory; + } + else + { + throw new MojoExecutionException( "Unknown compiler output style: '" + outputStyle + "'." ); + } + + scanner.addSourceMapping( mapping ); + + Set staleSources = new HashSet(); + + for ( Iterator it = getCompileSourceRoots().iterator(); it.hasNext(); ) + { + String sourceRoot = (String) it.next(); + + File rootFile = new File( sourceRoot ); + + if ( !rootFile.isDirectory() ) + { + continue; + } + + try + { + staleSources.addAll( scanner.getIncludedSources( rootFile, outputDirectory ) ); + } + catch ( InclusionScanException e ) + { + throw new MojoExecutionException( + "Error scanning source root: \'" + sourceRoot + "\' " + "for stale files to recompile.", e ); + } + } + + return staleSources; + } + + /** + * @todo also in ant plugin. This should be resolved at some point so that it does not need to + * be calculated continuously - or should the plugins accept empty source roots as is? + */ + private static List removeEmptyCompileSourceRoots( List compileSourceRootsList ) + { + List newCompileSourceRootsList = new ArrayList(); + if ( compileSourceRootsList != null ) + { + // copy as I may be modifying it + for ( Iterator i = compileSourceRootsList.iterator(); i.hasNext(); ) + { + String srcDir = (String) i.next(); + if ( !newCompileSourceRootsList.contains( srcDir ) && new File( srcDir ).exists() ) + { + newCompileSourceRootsList.add( srcDir ); + } + } + } + return newCompileSourceRootsList; + } + /** + * @return Returns the customClasspathLocations. + */ + public ArrayList getCustomClasspathLocations() { + return customClasspathLocations; + } +} Added: trunk/labs/jbossbuild/projects/maven-plugins/maven-jboss-compiler-plugin/src/main/java/org/apache/maven/plugin/CompilationFailureException.java =================================================================== --- trunk/labs/jbossbuild/projects/maven-plugins/maven-jboss-compiler-plugin/src/main/java/org/apache/maven/plugin/CompilationFailureException.java 2006-01-26 20:48:47 UTC (rev 2215) +++ trunk/labs/jbossbuild/projects/maven-plugins/maven-jboss-compiler-plugin/src/main/java/org/apache/maven/plugin/CompilationFailureException.java 2006-01-26 21:57:20 UTC (rev 2216) @@ -0,0 +1,50 @@ +package org.apache.maven.plugin; + +/* + * Copyright 2001-2005 The Apache Software Foundation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.codehaus.plexus.compiler.CompilerError; + +import java.util.Iterator; +import java.util.List; + +/** + * @author <a href="mailto:ja...@ma...">Jason van Zyl</a> + * @version $Id: CompilationFailureException.java 314963 2005-10-12 16:58:03Z brett $ + */ +public class CompilationFailureException + extends MojoFailureException +{ + private static final String LS = System.getProperty( "line.separator" ); + + public CompilationFailureException( List messages ) + { + super( null, "Compilation failure", longMessage( messages ) ); + } + + public static String longMessage( List messages ) + { + StringBuffer sb = new StringBuffer(); + + for ( Iterator it = messages.iterator(); it.hasNext() ; ) + { + CompilerError compilerError = (CompilerError) it.next(); + + sb.append( compilerError ).append( LS ); + } + return sb.toString(); + } +} Added: trunk/labs/jbossbuild/projects/maven-plugins/maven-jboss-compiler-plugin/src/main/java/org/apache/maven/plugin/CompilerMojo.java =================================================================== --- trunk/labs/jbossbuild/projects/maven-plugins/maven-jboss-compiler-plugin/src/main/java/org/apache/maven/plugin/CompilerMojo.java 2006-01-26 20:48:47 UTC (rev 2215) +++ trunk/labs/jbossbuild/projects/maven-plugins/maven-jboss-compiler-plugin/src/main/java/org/apache/maven/plugin/CompilerMojo.java 2006-01-26 21:57:20 UTC (rev 2216) @@ -0,0 +1,157 @@ +package org.apache.maven.plugin; + +/* + * Copyright 2001-2005 The Apache Software Foundation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.io.File; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.apache.maven.artifact.Artifact; +import org.codehaus.plexus.compiler.util.scan.SimpleSourceInclusionScanner; +import org.codehaus.plexus.compiler.util.scan.SourceInclusionScanner; +import org.codehaus.plexus.compiler.util.scan.StaleSourceScanner; + +/** + * @author <a href="mailto:ja...@ma...">Jason van Zyl </a> + * @version $Id: CompilerMojo.java 314975 2005-10-12 17:30:39Z brett $ + * @goal compile + * @phase compile + * @requiresDependencyResolution compile + * @description Compiles application sources + */ +public class CompilerMojo + extends AbstractCompilerMojo +{ + /** + * The source directories containing the sources to be compiled. + * + * @parameter expression="${compileSourceRoots}" + * @required + * + */ + private ArrayList compileSourceRoots; + + /** + * Project classpath. + * + * @parameter expression="${project.compileClasspathElements}" + * @required + * @readonly + */ + private List classpathElements; + + /** + * The directory for compiled classes. + * + * @parameter expression="${outputDirectory}" + * @required + * + */ + private File outputDirectory; + + /** + * Project artifacts. + * + * @parameter expression="${project.artifact}" + * @required + * @readonly + * @todo this is an export variable, really + */ + private Artifact projectArtifact; + + /** + * A list of inclusion filters for the compiler. + * + * @parameter + */ + private Set includes = new HashSet(); + + /** + * A list of exclusion filters for the compiler. + * + * @parameter + */ + private Set excludes = new HashSet(); + + protected List getCompileSourceRoots() + { + return compileSourceRoots; + } + + protected List getClasspathElements() + { + return classpathElements; + } + + protected File getOutputDirectory() + { + return outputDirectory; + } + + public void execute() + throws MojoExecutionException, CompilationFailureException + { + super.execute(); + + projectArtifact.setFile( outputDirectory ); + } + + protected SourceInclusionScanner getSourceInclusionScanner( int staleMillis ) + { + SourceInclusionScanner scanner = null; + + if ( includes.isEmpty() && excludes.isEmpty() ) + { + scanner = new StaleSourceScanner( staleMillis ); + } + else + { + if ( includes.isEmpty() ) + { + includes.add( "**/*.java" ); + } + scanner = new StaleSourceScanner( staleMillis, includes, excludes ); + } + + return scanner; + } + + protected SourceInclusionScanner getSourceInclusionScanner( String inputFileEnding ) + { + SourceInclusionScanner scanner = null; + + if ( includes.isEmpty() && excludes.isEmpty() ) + { + includes = Collections.singleton( "**/*." + inputFileEnding ); + scanner = new SimpleSourceInclusionScanner( includes, Collections.EMPTY_SET ); + } + else + { + if ( includes.isEmpty() ) + { + includes.add( "**/*." + inputFileEnding ); + } + scanner = new SimpleSourceInclusionScanner( excludes, excludes ); + } + + return scanner; + } + +} \ No newline at end of file Added: trunk/labs/jbossbuild/projects/maven-plugins/maven-jboss-compiler-plugin/src/main/java/org/apache/maven/plugin/TestCompilerMojo.java =================================================================== --- trunk/labs/jbossbuild/projects/maven-plugins/maven-jboss-compiler-plugin/src/main/java/org/apache/maven/plugin/TestCompilerMojo.java 2006-01-26 20:48:47 UTC (rev 2215) +++ trunk/labs/jbossbuild/projects/maven-plugins/maven-jboss-compiler-plugin/src/main/java/org/apache/maven/plugin/TestCompilerMojo.java 2006-01-26 21:57:20 UTC (rev 2216) @@ -0,0 +1,158 @@ +package org.apache.maven.plugin; + +/* + * Copyright 2001-2005 The Apache Software Foundation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.codehaus.plexus.compiler.util.scan.SimpleSourceInclusionScanner; +import org.codehaus.plexus.compiler.util.scan.SourceInclusionScanner; +import org.codehaus.plexus.compiler.util.scan.StaleSourceScanner; + +import java.io.File; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +/** + * @author <a href="mailto:ja...@ma...">Jason van Zyl</a> + * @version $Id: TestCompilerMojo.java 344360 2005-11-15 12:54:44Z brett $ + * @goal testCompile + * @phase test-compile + * @description Compiles test sources + * @requiresDependencyResolution test + */ +public class TestCompilerMojo + extends AbstractCompilerMojo +{ + /** + * Set this to 'true' to bypass unit tests entirely. + * Its use is NOT RECOMMENDED, but quite convenient on occasion. + * + * @parameter expression="${maven.test.skip}" + */ + private boolean skip; + + /** + * The source directories containing the test-source to be compiled. + * + * @parameter expression="${project.testCompileSourceRoots}" + * @required + * @readonly + */ + private List compileSourceRoots; + + /** + * Project test classpath. + * + * @parameter expression="${project.testClasspathElements}" + * @required + * @readonly + */ + private List classpathElements; + + /** + * The directory where compiled test classes go. + * + * @parameter expression="${project.build.testOutputDirectory}" + * @required + * @readonly + */ + private File outputDirectory; + + /** + * A list of inclusion filters for the compiler. + * + * @parameter + */ + private Set testIncludes = new HashSet(); + + /** + * A list of exclusion filters for the compiler. + * + * @parameter + */ + private Set testExcludes = new HashSet(); + + public void execute() + throws MojoExecutionException, CompilationFailureException + { + if ( skip ) + { + getLog().info( "Not compiling test sources" ); + } + else + { + super.execute(); + } + } + + protected List getCompileSourceRoots() + { + return compileSourceRoots; + } + + protected List getClasspathElements() + { + return classpathElements; + } + + protected File getOutputDirectory() + { + return outputDirectory; + } + + protected SourceInclusionScanner getSourceInclusionScanner( int staleMillis ) + { + SourceInclusionScanner scanner = null; + + if ( testIncludes.isEmpty() && testExcludes.isEmpty() ) + { + scanner = new StaleSourceScanner( staleMillis ); + } + else + { + if ( testIncludes.isEmpty() ) + { + testIncludes.add( "**/*.java" ); + } + scanner = new StaleSourceScanner( staleMillis, testIncludes, testExcludes ); + } + + return scanner; + } + + protected SourceInclusionScanner getSourceInclusionScanner( String inputFileEnding ) + { + SourceInclusionScanner scanner = null; + + if ( testIncludes.isEmpty() && testExcludes.isEmpty() ) + { + testIncludes = Collections.singleton( "**/*." + inputFileEnding ); + scanner = new SimpleSourceInclusionScanner( testIncludes, Collections.EMPTY_SET ); + } + else + { + if ( testIncludes.isEmpty() ) + { + testIncludes.add( "**/*." + inputFileEnding ); + } + scanner = new SimpleSourceInclusionScanner( testIncludes, testExcludes ); + } + + return scanner; + } + +} Added: trunk/labs/jbossbuild/projects/maven-plugins/maven-jboss-compiler-plugin/src/site/apt/howto.apt =================================================================== --- trunk/labs/jbossbuild/projects/maven-plugins/maven-jboss-compiler-plugin/src/site/apt/howto.apt 2006-01-26 20:48:47 UTC (rev 2215) +++ trunk/labs/jbossbuild/projects/maven-plugins/maven-jboss-compiler-plugin/src/site/apt/howto.apt 2006-01-26 21:57:20 UTC (rev 2216) @@ -0,0 +1,42 @@ + ------ + Maven 2 Compiler Plugin + ------ + Johnny R. Ruiz III + <jr...@ex...> + ------ + September 19, 2005 + +How to Use + + These example shows how to set the -source and -target argument of the Java Compiler. + + It also shows how to exclude certain files on the items to be compiled. + +------------------- +<project> + ... + <build> + ... + <plugins> + <plugin> + <groupId>org.apache.maven.plugins</groupId> + <artifactId>maven-compiler-plugin</artifactId> + <configuration> + <source>1.5</source> + <target>1.5</target> + <excludes> + <exclude implementation="java.lang.String">**/*Point*.java</exclude> + </excludes> + </configuration> + </plugin> + </plugins> + ... + </build> + ... +</project> +------------------- + + There are other parameters that you can configure like fork, includes/include, debug, showWarnings etc. + + For full documentation, click {{{index.html}here}}. + Added: trunk/labs/jbossbuild/projects/maven-plugins/maven-jboss-compiler-plugin/src/site/apt/introduction.apt =================================================================== --- trunk/labs/jbossbuild/projects/maven-plugins/maven-jboss-compiler-plugin/src/site/apt/introduction.apt 2006-01-26 20:48:47 UTC (rev 2215) +++ trunk/labs/jbossbuild/projects/maven-plugins/maven-jboss-compiler-plugin/src/site/apt/introduction.apt 2006-01-26 21:57:20 UTC (rev 2216) @@ -0,0 +1,14 @@ + ------ + Maven 2 Compiler Plugin + ------ + Johnny R. Ruiz III + <jr...@ex...> + ------ + September 19, 2005 + +Introduction + + This plugin is the Maven2 version of Maven1's Java Plugin. + + This plugin provides the basic Javac facilities. + Added: trunk/labs/jbossbuild/projects/maven-plugins/maven-jboss-compiler-plugin/src/site/site.xml =================================================================== --- trunk/labs/jbossbuild/projects/maven-plugins/maven-jboss-compiler-plugin/src/site/site.xml 2006-01-26 20:48:47 UTC (rev 2215) +++ trunk/labs/jbossbuild/projects/maven-plugins/maven-jboss-compiler-plugin/src/site/site.xml 2006-01-26 21:57:20 UTC (rev 2216) @@ -0,0 +1,41 @@ +<?xml version="1.0" encoding="ISO-8859-1"?> + +<!-- +/* + * Copyright 2001-2005 The Apache Software Foundation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +--> + +<project name="Maven Compiler Plugin"> + <bannerLeft> + <name>Maven Compiler Plugin</name> + <src>http://maven.apache.org/images/apache-maven-project.png</src> + <href>http://maven.apache.org/</href> + </bannerLeft> + <bannerRight> + <src>http://maven.apache.org/images/maven-small.gif</src> + </bannerRight> + <body> + <links> + <item name="Maven 2" href="http://maven.apache.org/maven2/"/> + </links> + + <menu name="Overview"> + <item name="Introduction" href="introduction.html"/> + <item name="How to Use" href="howto.html"/> + </menu> + ${reports} + </body> +</project> |
From: <jbo...@li...> - 2006-01-26 20:46:11
|
Author: dam...@jb... Date: 2006-01-26 15:46:06 -0500 (Thu, 26 Jan 2006) New Revision: 2214 Added: trunk/labs/trailblazers/ Log: Added trailblazers. |
From: <jbo...@li...> - 2006-01-26 19:36:51
|
Author: wrzep Date: 2006-01-26 14:36:42 -0500 (Thu, 26 Jan 2006) New Revision: 2213 Modified: trunk/forge/portal-extensions/forge-theme/jbossForgeLayout.war/graphs.css Log: http://jira.jboss.com/jira/browse/JBLAB-595 Pawel Modified: trunk/forge/portal-extensions/forge-theme/jbossForgeLayout.war/graphs.css =================================================================== --- trunk/forge/portal-extensions/forge-theme/jbossForgeLayout.war/graphs.css 2006-01-26 19:24:31 UTC (rev 2212) +++ trunk/forge/portal-extensions/forge-theme/jbossForgeLayout.war/graphs.css 2006-01-26 19:36:42 UTC (rev 2213) @@ -45,13 +45,13 @@ width: 197px; height: 20px; margin: 0 0 15px; - background: url("/jbossForge/images/graphs/g_colorbar.jpg"); + background: url("/jbossForge/images/graphs/g_colorbar2.jpg"); } * html dd { float: none; } /* IE is dumb; Quick IE hack, apply favorite filter methods for wider browser compatibility */ dd div { position: relative; - background: url("/jbossForge/images/graphs/g_colorbar2.jpg"); + background: url("/jbossForge/images/graphs/g_colorbar.jpg"); height: 20px; width: 75%; text-align:right; |
From: <jbo...@li...> - 2006-01-26 19:24:44
|
Author: wrzep Date: 2006-01-26 14:24:31 -0500 (Thu, 26 Jan 2006) New Revision: 2212 Modified: trunk/forge/portal-extensions/forge-status/src/java/org/jboss/forge/status/StatusNodeWatcher.java trunk/forge/portal-extensions/forge-theme/jbossForgeLayout.war/images/graphs/g_colorbar.jpg trunk/forge/portal-extensions/forge-theme/jbossForgeLayout.war/images/graphs/g_colorbar2.jpg Log: Rotated graphs css bar images (green = 0%, red = 100%, was inversely) http://jira.jboss.com/jira/browse/JBLAB-595 Pawel Modified: trunk/forge/portal-extensions/forge-status/src/java/org/jboss/forge/status/StatusNodeWatcher.java =================================================================== --- trunk/forge/portal-extensions/forge-status/src/java/org/jboss/forge/status/StatusNodeWatcher.java 2006-01-26 18:37:43 UTC (rev 2211) +++ trunk/forge/portal-extensions/forge-status/src/java/org/jboss/forge/status/StatusNodeWatcher.java 2006-01-26 19:24:31 UTC (rev 2212) @@ -71,7 +71,7 @@ public Object nodeUpdate(String portalName, Object currentValue) { - if ((currentValue == null) || (rw.checkResources()) || (updateCounter == 9)) { + if ((currentValue == null) || (rw.checkResources()) || (updateCounter == 99)) { updateCounter = 0; return getDesc(portalName); Modified: trunk/forge/portal-extensions/forge-theme/jbossForgeLayout.war/images/graphs/g_colorbar.jpg =================================================================== (Binary files differ) Modified: trunk/forge/portal-extensions/forge-theme/jbossForgeLayout.war/images/graphs/g_colorbar2.jpg =================================================================== (Binary files differ) |
From: <jbo...@li...> - 2006-01-26 18:37:51
|
Author: wrzep Date: 2006-01-26 13:37:43 -0500 (Thu, 26 Jan 2006) New Revision: 2211 Modified: trunk/forge/portal-extensions/forge-status/src/java/org/jboss/forge/status/StatusNodeWatcher.java Log: Forced update every 10 "nodeUpdate" calls to ensure we've got up to date statistics. http://jira.jboss.com/jira/browse/JBLAB-595 Pawel Modified: trunk/forge/portal-extensions/forge-status/src/java/org/jboss/forge/status/StatusNodeWatcher.java =================================================================== --- trunk/forge/portal-extensions/forge-status/src/java/org/jboss/forge/status/StatusNodeWatcher.java 2006-01-26 18:13:06 UTC (rev 2210) +++ trunk/forge/portal-extensions/forge-status/src/java/org/jboss/forge/status/StatusNodeWatcher.java 2006-01-26 18:37:43 UTC (rev 2211) @@ -33,8 +33,11 @@ private ResourceWatcher rw; private ContentManager cm; + private int updateCounter; + public StatusNodeWatcher(ContentManager cm) { this.cm = cm; + updateCounter = 0; } private StatusDescriptor getDesc(String portalName) { @@ -68,10 +71,13 @@ public Object nodeUpdate(String portalName, Object currentValue) { - //TODO update from time to time - if ((currentValue == null) || (rw.checkResources())) + if ((currentValue == null) || (rw.checkResources()) || (updateCounter == 9)) { + + updateCounter = 0; return getDesc(portalName); - else + } else { + ++updateCounter; return null; + } } } |
From: <jbo...@li...> - 2006-01-26 18:13:11
|
Author: wrzep Date: 2006-01-26 13:13:06 -0500 (Thu, 26 Jan 2006) New Revision: 2210 Modified: trunk/forge/portal-extensions/forge-status/src/java/org/jboss/forge/status/StatusNodeWatcher.java trunk/forge/portal-extensions/forge-status/src/java/org/jboss/forge/status/plugins/Plugin.java Log: Finished computing project rating (project score/ highest score). http://jira.jboss.com/jira/browse/JBLAB-595 Pawel Modified: trunk/forge/portal-extensions/forge-status/src/java/org/jboss/forge/status/StatusNodeWatcher.java =================================================================== --- trunk/forge/portal-extensions/forge-status/src/java/org/jboss/forge/status/StatusNodeWatcher.java 2006-01-26 14:50:53 UTC (rev 2209) +++ trunk/forge/portal-extensions/forge-status/src/java/org/jboss/forge/status/StatusNodeWatcher.java 2006-01-26 18:13:06 UTC (rev 2210) @@ -68,6 +68,7 @@ public Object nodeUpdate(String portalName, Object currentValue) { + //TODO update from time to time if ((currentValue == null) || (rw.checkResources())) return getDesc(portalName); else Modified: trunk/forge/portal-extensions/forge-status/src/java/org/jboss/forge/status/plugins/Plugin.java =================================================================== --- trunk/forge/portal-extensions/forge-status/src/java/org/jboss/forge/status/plugins/Plugin.java 2006-01-26 14:50:53 UTC (rev 2209) +++ trunk/forge/portal-extensions/forge-status/src/java/org/jboss/forge/status/plugins/Plugin.java 2006-01-26 18:13:06 UTC (rev 2210) @@ -44,8 +44,6 @@ /** Projects present in the Status Matrix. */ protected Projects projects; - private long highScore; - /** * @param id Plugin id * @param properties plugin specyfic properties @@ -60,10 +58,6 @@ this.properties = properties; this.projects = projects; this.id = id; - - System.out.println("Plugin::init properites = " + properties); - - highScore = getHighScore(); } /** @@ -91,12 +85,16 @@ * with the given <code>projectId</code>. */ public int getRate(String projectId) { - + + long highScore = getHighScore(); + if (highScore == 0) { return 0; } - return (int) ((getValue(projectId) / highScore)); + float r = ((float) getValue(projectId) / (float) highScore); + + return (int) (100.0 * r); } /** |
From: <jbo...@li...> - 2006-01-26 08:25:41
|
Author: mic...@jb... Date: 2006-01-26 03:25:34 -0500 (Thu, 26 Jan 2006) New Revision: 2208 Modified: trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/RepositoryFactory.java trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/db/RepoProxyHandler.java Log: added DataSource capability Modified: trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/RepositoryFactory.java =================================================================== --- trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/RepositoryFactory.java 2006-01-26 03:51:31 UTC (rev 2207) +++ trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/RepositoryFactory.java 2006-01-26 08:25:34 UTC (rev 2208) @@ -4,6 +4,8 @@ import java.security.Principal; import java.security.acl.Permission; +import javax.sql.DataSource; + import org.drools.repository.db.RepoProxyHandler; @@ -52,7 +54,15 @@ return getRepo(currentUser, false); } - + /** + * This creates a repository manager session based on the JDBC datasource passed in. + * In this case, the close() method should be called when finished. + */ + public static RepositoryManager getRepository(Principal currentUser, DataSource dataSource) { + RepoProxyHandler handler = new RepoProxyHandler(dataSource); + handler.setCurrentUser(currentUser); + return getProxy(handler); + } private static RepositoryManager getProxy(RepoProxyHandler handler) { RepositoryManager manager = (RepositoryManager) Proxy.newProxyInstance(RepositoryFactory.class.getClassLoader(), @@ -70,4 +80,6 @@ } + + } Modified: trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/db/RepoProxyHandler.java =================================================================== --- trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/db/RepoProxyHandler.java 2006-01-26 03:51:31 UTC (rev 2207) +++ trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/db/RepoProxyHandler.java 2006-01-26 08:25:34 UTC (rev 2208) @@ -4,7 +4,10 @@ import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.security.Principal; +import java.sql.SQLException; +import javax.sql.DataSource; + import org.drools.repository.RepositoryException; import org.drools.repository.RepositoryManagerImpl; import org.hibernate.Session; @@ -59,6 +62,20 @@ } /** + * This version creates a new session from the given datasource. + * In this case, close() will need to be called, ideally. + */ + public RepoProxyHandler(DataSource datasource) { + this.stateful = true; + try { + this.session = HibernateUtil.getSessionFactory().openSession(datasource.getConnection()); + } + catch ( SQLException e ) { + throw new RepositoryException("Unable to get connection from datasource.", e); + } + } + + /** * This will initialise the session to the correct state. * Allows both stateless and stateful repository options. * |
From: <jbo...@li...> - 2006-01-26 03:52:09
|
Author: mic...@jb... Date: 2006-01-25 22:51:31 -0500 (Wed, 25 Jan 2006) New Revision: 2207 Added: trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/db/StoreInterceptor.java Removed: trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/db/StoreEventListener.java Modified: trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/ApplicationDataDef.java trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/Asset.java trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/FunctionDef.java trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/ImportDef.java trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/RuleDef.java trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/RuleSetAttachment.java trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/Tag.java trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/db/HibernateUtil.java trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/db/IVersionable.java trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/db/RepoProxyHandler.java trunk/labs/jbossrules/drools-repository/src/main/resources/org/drools/repository/ApplicationDataDef.hbm.xml trunk/labs/jbossrules/drools-repository/src/main/resources/org/drools/repository/FunctionDef.hbm.xml trunk/labs/jbossrules/drools-repository/src/main/resources/org/drools/repository/ImportDef.hbm.xml trunk/labs/jbossrules/drools-repository/src/main/resources/org/drools/repository/RuleDef.hbm.xml trunk/labs/jbossrules/drools-repository/src/main/resources/org/drools/repository/RuleSetAttachment.hbm.xml trunk/labs/jbossrules/drools-repository/src/main/resources/org/drools/repository/RuleSetDef.hbm.xml trunk/labs/jbossrules/drools-repository/src/main/resources/org/drools/repository/RuleSetVersionInfo.hbm.xml trunk/labs/jbossrules/drools-repository/src/test/java/org/drools/repository/RulePersistenceTest.java trunk/labs/jbossrules/drools-repository/src/test/java/org/drools/repository/db/PersistentCase.java Log: added auditing Modified: trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/ApplicationDataDef.java =================================================================== --- trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/ApplicationDataDef.java 2006-01-26 01:25:30 UTC (rev 2206) +++ trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/ApplicationDataDef.java 2006-01-26 03:51:31 UTC (rev 2207) @@ -19,6 +19,7 @@ private long versionNumber; private String identifier; private String type; + /** * @param identifier @@ -53,9 +54,11 @@ } public IVersionable copy() { - ApplicationDataDef clone = new ApplicationDataDef( this.getIdentifier(), + ApplicationDataDef copy = new ApplicationDataDef( this.getIdentifier(), this.getType() ); - return clone; + copy.setLastSavedByUser(this.getLastSavedByUser()); + copy.setLastSavedDate(this.getLastSavedDate()); + return copy; } public String getVersionComment() { Modified: trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/Asset.java =================================================================== --- trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/Asset.java 2006-01-26 01:25:30 UTC (rev 2206) +++ trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/Asset.java 2006-01-26 03:51:31 UTC (rev 2207) @@ -1,19 +1,41 @@ package org.drools.repository; import java.io.Serializable; +import java.util.Date; -/** The layer supertype for repository persistable classes. */ -public class Asset implements Serializable { - - private Long id; +/** The layer supertype for repository persistable classes. */ +public class Asset + implements + Serializable { - public Long getId(){ + private Long id; + private String lastSavedByUser; + private Date lastSavedDate; + + public Long getId() { return id; } - private void setId(Long id){ + private void setId(Long id) { this.id = id; } - + /** If the repository is audited, this will show the user who saved the record last. */ + public String getLastSavedByUser() { + return lastSavedByUser; + } + + void setLastSavedByUser(String lastSavedByUser) { + this.lastSavedByUser = lastSavedByUser; + } + + /** If auditing is enabled, this will be set on save */ + public Date getLastSavedDate() { + return lastSavedDate; + } + + void setLastSavedDate(Date lastSavedDate) { + this.lastSavedDate = lastSavedDate; + } + } Modified: trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/FunctionDef.java =================================================================== --- trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/FunctionDef.java 2006-01-26 01:25:30 UTC (rev 2206) +++ trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/FunctionDef.java 2006-01-26 03:51:31 UTC (rev 2207) @@ -38,11 +38,13 @@ FunctionDef() {} public IVersionable copy(){ - FunctionDef clone = new FunctionDef(this.functionContent, this.description); - clone.semantic = this.getSemantic(); - clone.versionNumber = this.getVersionNumber(); - clone.versionComment = this.getVersionComment(); - return clone; + FunctionDef copy = new FunctionDef(this.functionContent, this.description); + copy.semantic = this.getSemantic(); + copy.versionNumber = this.getVersionNumber(); + copy.versionComment = this.getVersionComment(); + copy.setLastSavedByUser(this.getLastSavedByUser()); + copy.setLastSavedDate(this.getLastSavedDate()); + return copy; } public String getDescription(){ Modified: trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/ImportDef.java =================================================================== --- trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/ImportDef.java 2006-01-26 01:25:30 UTC (rev 2206) +++ trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/ImportDef.java 2006-01-26 03:51:31 UTC (rev 2207) @@ -49,7 +49,10 @@ } public IVersionable copy() { - return new ImportDef(this.getType()); + ImportDef copy = new ImportDef(this.getType()); + copy.setLastSavedByUser(this.getLastSavedByUser()); + copy.setLastSavedDate(this.getLastSavedDate()); + return copy; } Modified: trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/RuleDef.java =================================================================== --- trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/RuleDef.java 2006-01-26 01:25:30 UTC (rev 2206) +++ trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/RuleDef.java 2006-01-26 03:51:31 UTC (rev 2207) @@ -217,6 +217,8 @@ newVersion.versionNumber = this.getVersionNumber(); newVersion.versionComment = this.getVersionComment(); newVersion.owningRuleSetName = this.getOwningRuleSetName(); + newVersion.setLastSavedByUser(this.getLastSavedByUser()); + newVersion.setLastSavedDate(this.getLastSavedDate()); return newVersion; } Modified: trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/RuleSetAttachment.java =================================================================== --- trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/RuleSetAttachment.java 2006-01-26 01:25:30 UTC (rev 2206) +++ trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/RuleSetAttachment.java 2006-01-26 03:51:31 UTC (rev 2207) @@ -136,6 +136,8 @@ this.getContent(), this.getOriginalFileName()); copy.setTags(Tag.copyTags(this.tags)); + copy.setLastSavedByUser(this.getLastSavedByUser()); + copy.setLastSavedDate(this.getLastSavedDate()); return copy; } Modified: trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/Tag.java =================================================================== --- trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/Tag.java 2006-01-26 01:25:30 UTC (rev 2206) +++ trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/Tag.java 2006-01-26 03:51:31 UTC (rev 2207) @@ -1,5 +1,6 @@ package org.drools.repository; +import java.io.Serializable; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; @@ -16,8 +17,13 @@ * @author <a href="mailto:mic...@gm..."> Michael Neale</a> * */ -public class Tag extends Asset { +public class Tag implements Serializable { + + private static final long serialVersionUID = 3830081066595663015L; + + private Long id; + private String tag; public Tag(String tag) { @@ -63,6 +69,14 @@ } return newTags; } + + public Long getId() { + return id; + } + + void setId(Long id) { + this.id = id; + } Modified: trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/db/HibernateUtil.java =================================================================== --- trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/db/HibernateUtil.java 2006-01-26 01:25:30 UTC (rev 2206) +++ trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/db/HibernateUtil.java 2006-01-26 03:51:31 UTC (rev 2207) @@ -51,7 +51,7 @@ /** Return the hibernate configuration as it stands */ public static Configuration getConfiguration() { Configuration cfg = new Configuration(); - cfg.setInterceptor( new StoreEventListener() ); + cfg.setInterceptor( new StoreInterceptor() ); registerPersistentClasses( cfg ); // cfg.setProperty("connection.username", "sa"); // cfg.setProperty("connection.password", ""); Modified: trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/db/IVersionable.java =================================================================== --- trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/db/IVersionable.java 2006-01-26 01:25:30 UTC (rev 2206) +++ trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/db/IVersionable.java 2006-01-26 03:51:31 UTC (rev 2207) @@ -1,39 +1,43 @@ package org.drools.repository.db; -/** - * All assets that support versioning must implement this. - * Versioning in this sense is "major" versioning, at the ruleset level. +import java.util.Date; + +/** + * All assets that support versioning must implement this. Versioning in this + * sense is "major" versioning, at the ruleset level. * * This is different to Save History versioning, which is implicit on save. * */ public interface IVersionable { - - /** - * This is used to indicate that the asset is un-attached to - * any ruleset. Basically deleted. - * TODO: enhance this to delete if no longer needed. + + /** + * This is used to indicate that the asset is un-attached to any ruleset. + * Basically deleted. TODO: enhance this to delete if no longer needed. */ public static final long NO_VERSION = -1; - - /** of course they have to have an id ! - * Ids are always assigned by the database. + + /** + * of course they have to have an id ! Ids are always assigned by the + * database. */ - Long getId(); - + Long getId(); + /** Must create a fresh copy OF THE SAME TYPE, with a null Id */ IVersionable copy(); - - /** - * The version number is used to group assets together in a RuleSet for instance - * The version number should ONLY be set by the repository, NOT by users. + + /** + * The version number is used to group assets together in a RuleSet for + * instance The version number should ONLY be set by the repository, NOT by + * users. */ void setVersionNumber(long versionNumber); /** The version comment is used when major versions are created */ void setVersionComment(String comment); - + String getVersionComment(); - + long getVersionNumber(); + } Modified: trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/db/RepoProxyHandler.java =================================================================== --- trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/db/RepoProxyHandler.java 2006-01-26 01:25:30 UTC (rev 2206) +++ trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/db/RepoProxyHandler.java 2006-01-26 03:51:31 UTC (rev 2207) @@ -104,8 +104,8 @@ private void cleanup() { this.repoImpl.injectSession(null); - StoreEventListener.setCurrentConnection(null); - StoreEventListener.setCurrentUser(null); + StoreInterceptor.setCurrentConnection(null); + StoreInterceptor.setCurrentUser(null); } /** @@ -127,8 +127,8 @@ */ private void handleCloseSession(Session session) { session.close(); - StoreEventListener.setCurrentConnection(null); - StoreEventListener.setCurrentUser(null); + StoreInterceptor.setCurrentConnection(null); + StoreInterceptor.setCurrentUser(null); } private void rollback(Transaction tx) { @@ -145,8 +145,8 @@ * Inject the currentUser for auditing etc as well. */ private void configure(Session session, Principal user) { - StoreEventListener.setCurrentConnection( session.connection() ); - StoreEventListener.setCurrentUser( user ); + StoreInterceptor.setCurrentConnection( session.connection() ); + StoreInterceptor.setCurrentUser( user ); repoImpl.enableHistoryFilter( session ); repoImpl.injectSession( session ); this.repoImpl.setCurrentUser(currentUser); Deleted: trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/db/StoreEventListener.java =================================================================== --- trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/db/StoreEventListener.java 2006-01-26 01:25:30 UTC (rev 2206) +++ trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/db/StoreEventListener.java 2006-01-26 03:51:31 UTC (rev 2207) @@ -1,86 +0,0 @@ -package org.drools.repository.db; - -import java.io.Serializable; -import java.security.Principal; -import java.sql.Connection; - -import org.hibernate.EmptyInterceptor; -import org.hibernate.LockMode; -import org.hibernate.Session; -import org.hibernate.SessionFactory; -import org.hibernate.type.Type; - -/** - * This event listener processes save history events. When an asset is updated - * that requires a history record, it asks the asset if a history record should - * be created. If it does then it will clone it, and save it as a history item - * (using an seperate session that is not related to the current session). - * - * @author <a href="mailto:mic...@gm..."> Michael Neale</a> - */ -public class StoreEventListener extends EmptyInterceptor { - - private static final long serialVersionUID = -5634072610999632779L; - - //use a threadlocal to get the currentConnection, - //as we may not always use currentSession semantics. - private static ThreadLocal currentConnection = new ThreadLocal(); - - private static ThreadLocal currentUser = new ThreadLocal(); - - public boolean onFlushDirty(Object entity, - Serializable id, - Object[] currentState, - Object[] previousState, - String[] propertyNames, - Type[] types) { - if ( entity instanceof ISaveHistory ) { - handleSaveHistory( entity ); - } - return false; - } - - /** - * This will load up the old copy, and save it as a history record - * (with a different identity). - * Filters stop the history records from popping up in unwanted places . - */ - private void handleSaveHistory(Object entity) { - ISaveHistory versionable = (ISaveHistory) entity; - - Session session = getSessionFactory().openSession( (Connection) currentConnection.get() ); - ISaveHistory prev = (ISaveHistory) session.load( entity.getClass(), - versionable.getId(), - LockMode.NONE ); - ISaveHistory copy = (ISaveHistory) prev.copy(); - copy.setHistoricalId( versionable.getId() ); - copy.setHistoricalRecord( true ); - //session.beginTransaction(); - session.save( copy ); - //session.getTransaction().commit(); - session.flush(); - session.close(); - } - - /** - * Used to set the current session so the interceptor can access it. - * The idea is to share the same connection that any current transactions - * are using. - */ - public static void setCurrentConnection(Connection conn) { - currentConnection.set(conn); - } - - /** - * Set the current user for auditing purposes. - * This is backed by a threadlocal. - */ - public static void setCurrentUser(Principal user) { - currentUser.set(user); - } - - private SessionFactory getSessionFactory() { - return HibernateUtil.getSessionFactory(); - } - -} Copied: trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/db/StoreInterceptor.java (from rev 2206, trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/db/StoreEventListener.java) =================================================================== --- trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/db/StoreEventListener.java 2006-01-26 01:25:30 UTC (rev 2206) +++ trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/db/StoreInterceptor.java 2006-01-26 03:51:31 UTC (rev 2207) @@ -0,0 +1,140 @@ +package org.drools.repository.db; + +import java.io.Serializable; +import java.security.Principal; +import java.sql.Connection; +import java.util.Date; + +import org.drools.repository.Asset; +import org.hibernate.EmptyInterceptor; +import org.hibernate.LockMode; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.type.Type; + +/** + * This event listener processes database events using an interceptor. + * + * When an asset is updated that requires a history record, a history record will be created by + * loading and then copying the old copy of the data. + * (using an seperate session that is not related to the current session, but sharing the same connection). + * + * Note that it will also save audit information about whom saved the data. + * + * This can be extended in future to provide additional audit trail information, or instance based security + * (to enforce ACLs on save etc). + * + * @author <a href="mailto:mic...@gm..."> Michael Neale</a> + */ +public class StoreInterceptor extends EmptyInterceptor { + + private static final long serialVersionUID = -5634072610999632779L; + + //use a threadlocal to get the currentConnection, + //as we may not always use currentSession semantics. + private static ThreadLocal currentConnection = new ThreadLocal(); + + //we also need the current user if it has been set. + private static ThreadLocal currentUser = new ThreadLocal(); + + /** + * Create historical records, and log events. + */ + public boolean onFlushDirty(Object entity, + Serializable id, + Object[] currentState, + Object[] previousState, + String[] propertyNames, + Type[] types) { + if ( entity instanceof ISaveHistory ) { + handleSaveHistory( entity ); + } + + return handleUserSaveInfo( entity, + currentState, + propertyNames ); + } + + /** record who and when */ + public boolean onSave(Object entity, + Serializable id, + Object[] currentState, + String[] propertyNames, + Type[] types) { + + return handleUserSaveInfo( entity, + currentState, + propertyNames ); + + } + + /** + * This will load up the old copy, and save it as a history record + * (with a different identity). + * Filters stop the history records from popping up in unwanted places . + */ + private void handleSaveHistory(Object entity) { + ISaveHistory versionable = (ISaveHistory) entity; + + Session session = getSessionFactory().openSession( (Connection) currentConnection.get() ); + ISaveHistory prev = (ISaveHistory) session.load( entity.getClass(), + versionable.getId(), + LockMode.NONE ); + ISaveHistory copy = (ISaveHistory) prev.copy(); + copy.setHistoricalId( versionable.getId() ); + copy.setHistoricalRecord( true ); + //session.beginTransaction(); + session.save( copy ); + //session.getTransaction().commit(); + session.flush(); + session.close(); + } + + /** + * Used to set the current session so the interceptor can access it. + * The idea is to share the same connection that any current transactions + * are using. + */ + public static void setCurrentConnection(Connection conn) { + currentConnection.set(conn); + } + + /** + * Set the current user for auditing purposes. + * This is backed by a threadlocal. + */ + public static void setCurrentUser(Principal user) { + currentUser.set(user); + } + + private SessionFactory getSessionFactory() { + return HibernateUtil.getSessionFactory(); + } + + + + /** Log who saved, what, when */ + private boolean handleUserSaveInfo(Object entity, + Object[] currentState, + String[] propertyNames) { + if (entity instanceof Asset) { + Principal user = (Principal) currentUser.get(); + boolean changed = false; + + for ( int i=0; i < propertyNames.length; i++ ) { + if ( "lastSavedDate".equals( propertyNames[i] ) ) { + currentState[i] = new Date(); + changed = true; + } else if (user != null && "lastSavedByUser".equals( propertyNames[i]) ) { + currentState[i] = user.getName(); + changed = true; + } + } + return changed; + } else { + return false; + } + + } + +} Modified: trunk/labs/jbossrules/drools-repository/src/main/resources/org/drools/repository/ApplicationDataDef.hbm.xml =================================================================== --- trunk/labs/jbossrules/drools-repository/src/main/resources/org/drools/repository/ApplicationDataDef.hbm.xml 2006-01-26 01:25:30 UTC (rev 2206) +++ trunk/labs/jbossrules/drools-repository/src/main/resources/org/drools/repository/ApplicationDataDef.hbm.xml 2006-01-26 03:51:31 UTC (rev 2207) @@ -11,6 +11,8 @@ <property name="type" column="CLASS_TYPE" length="64" /> <property name="identifier" column="DATA_IDENTIFIER" length="32" /> <property name="versionComment" column="VERSION_COMMENT" length="64" /> - <property name="versionNumber" column="VERSION_NUMBER" /> + <property name="versionNumber" column="VERSION_NUMBER" /> + <property name="lastSavedByUser" column="LAST_SAVED_USER" /> + <property name="lastSavedDate" column="LAST_SAVED_DATE" /> </class> </hibernate-mapping> \ No newline at end of file Modified: trunk/labs/jbossrules/drools-repository/src/main/resources/org/drools/repository/FunctionDef.hbm.xml =================================================================== --- trunk/labs/jbossrules/drools-repository/src/main/resources/org/drools/repository/FunctionDef.hbm.xml 2006-01-26 01:25:30 UTC (rev 2206) +++ trunk/labs/jbossrules/drools-repository/src/main/resources/org/drools/repository/FunctionDef.hbm.xml 2006-01-26 03:51:31 UTC (rev 2207) @@ -15,6 +15,9 @@ <property name="functionContent" column="FUNCTION_CONTENT" type="text"/> <property name="semantic" column="SEMANTIC" length="32" /> <property name="versionComment" column="VERSION_COMMENT" length="128" /> - <property name="versionNumber" column="VERSION_NUMBER" /> + <property name="versionNumber" column="VERSION_NUMBER" /> + <property name="lastSavedByUser" column="LAST_SAVED_USER" /> + <property name="lastSavedDate" column="LAST_SAVED_DATE" /> + </class> </hibernate-mapping> \ No newline at end of file Modified: trunk/labs/jbossrules/drools-repository/src/main/resources/org/drools/repository/ImportDef.hbm.xml =================================================================== --- trunk/labs/jbossrules/drools-repository/src/main/resources/org/drools/repository/ImportDef.hbm.xml 2006-01-26 01:25:30 UTC (rev 2206) +++ trunk/labs/jbossrules/drools-repository/src/main/resources/org/drools/repository/ImportDef.hbm.xml 2006-01-26 03:51:31 UTC (rev 2207) @@ -10,6 +10,8 @@ </id> <property name="type" column="CLASS_TYPE" length="64" /> <property name="versionComment" column="VERSION_COMMMENT" length="128" /> - <property name="versionNumber" column="VERSION_NUMBER" /> + <property name="versionNumber" column="VERSION_NUMBER" /> + <property name="lastSavedByUser" column="LAST_SAVED_USER" /> + <property name="lastSavedDate" column="LAST_SAVED_DATE" /> </class> </hibernate-mapping> \ No newline at end of file Modified: trunk/labs/jbossrules/drools-repository/src/main/resources/org/drools/repository/RuleDef.hbm.xml =================================================================== --- trunk/labs/jbossrules/drools-repository/src/main/resources/org/drools/repository/RuleDef.hbm.xml 2006-01-26 01:25:30 UTC (rev 2206) +++ trunk/labs/jbossrules/drools-repository/src/main/resources/org/drools/repository/RuleDef.hbm.xml 2006-01-26 03:51:31 UTC (rev 2207) @@ -27,6 +27,8 @@ <property name="historicalId" column="HISTORICAL_ID"/> <property name="historicalRecord" column="HISTORICAL_RECORD_FLAG"/> <property name="owningRuleSetName" column="OWNING_RULESET_NAME" /> + <property name="lastSavedByUser" column="LAST_SAVED_USER" /> + <property name="lastSavedDate" column="LAST_SAVED_DATE" /> <set name="tags" table="RULE_TAGS" lazy="false" cascade="all" optimistic-lock="false"> <key column="RULE_ID"/> Modified: trunk/labs/jbossrules/drools-repository/src/main/resources/org/drools/repository/RuleSetAttachment.hbm.xml =================================================================== --- trunk/labs/jbossrules/drools-repository/src/main/resources/org/drools/repository/RuleSetAttachment.hbm.xml 2006-01-26 01:25:30 UTC (rev 2206) +++ trunk/labs/jbossrules/drools-repository/src/main/resources/org/drools/repository/RuleSetAttachment.hbm.xml 2006-01-26 03:51:31 UTC (rev 2207) @@ -23,6 +23,8 @@ <property name="checkedOutBy" /> <property name="historicalRecord" column="HISTORICAL_RECORD_FLAG" /> <property name="historicalId" /> + <property name="lastSavedByUser" column="LAST_SAVED_USER" /> + <property name="lastSavedDate" column="LAST_SAVED_DATE" /> <set name="tags" table="RULESET_ATTACHMENT_TAGS" lazy="false" cascade="all" optimistic-lock="false"> <key column="RULESET_ATTACHMENT_ID"/> Modified: trunk/labs/jbossrules/drools-repository/src/main/resources/org/drools/repository/RuleSetDef.hbm.xml =================================================================== --- trunk/labs/jbossrules/drools-repository/src/main/resources/org/drools/repository/RuleSetDef.hbm.xml 2006-01-26 01:25:30 UTC (rev 2206) +++ trunk/labs/jbossrules/drools-repository/src/main/resources/org/drools/repository/RuleSetDef.hbm.xml 2006-01-26 03:51:31 UTC (rev 2207) @@ -12,7 +12,9 @@ </id> - <property name="name" not-null="true" /> + <property name="name" not-null="true" /> + <property name="lastSavedByUser" column="LAST_SAVED_USER" /> + <property name="lastSavedDate" column="LAST_SAVED_DATE" /> <component name="metaData"> <property name="title" /> Modified: trunk/labs/jbossrules/drools-repository/src/main/resources/org/drools/repository/RuleSetVersionInfo.hbm.xml =================================================================== --- trunk/labs/jbossrules/drools-repository/src/main/resources/org/drools/repository/RuleSetVersionInfo.hbm.xml 2006-01-26 01:25:30 UTC (rev 2206) +++ trunk/labs/jbossrules/drools-repository/src/main/resources/org/drools/repository/RuleSetVersionInfo.hbm.xml 2006-01-26 03:51:31 UTC (rev 2207) @@ -16,6 +16,8 @@ <property name="versionComment"/> <property name="createdOn"/> <property name="status" /> + <property name="lastSavedByUser" column="LAST_SAVED_USER" /> + <property name="lastSavedDate" column="LAST_SAVED_DATE" /> </class> Modified: trunk/labs/jbossrules/drools-repository/src/test/java/org/drools/repository/RulePersistenceTest.java =================================================================== --- trunk/labs/jbossrules/drools-repository/src/test/java/org/drools/repository/RulePersistenceTest.java 2006-01-26 01:25:30 UTC (rev 2206) +++ trunk/labs/jbossrules/drools-repository/src/test/java/org/drools/repository/RulePersistenceTest.java 2006-01-26 03:51:31 UTC (rev 2207) @@ -1,5 +1,6 @@ package org.drools.repository; +import java.security.Principal; import java.util.List; import java.util.Set; @@ -33,11 +34,34 @@ assertEquals(3, def.getTags().size()); def.removeTag("tag1"); repo.save(def); + def = repo.loadRule("myRule3", 1); - assertEquals(null, def.getOwningRuleSetName()); + assertEquals(null, def.getOwningRuleSetName()); + assertEquals(2, def.getTags().size()); - assertEquals(2, def.getTags().size()); + repo = RepositoryFactory.getRepository(getUserPrincipal(), true); + + def = repo.loadRule("myRule3", 1); + def.setContent("something else"); + repo.save(def); + + + assertNotNull(def.getLastSavedDate()); + assertEquals("michael", def.getLastSavedByUser()); + + repo.close(); } + + private Principal getUserPrincipal() { + return new Principal() { + + public String getName() { + return "michael"; + } + + + }; + } public void testRetreieveRuleWithTags() { RepositoryManager repo = getRepo(); @@ -66,7 +90,7 @@ RuleDef rule1 = new RuleDef("newVersionTest", "XXX"); rule1.addTag("HR").addTag("BOO"); - + rule1.setLastSavedByUser("blah"); MetaData meta = new MetaData(); meta.setCreator("Peter Jackson"); rule1.setMetaData(meta); @@ -76,7 +100,7 @@ assertEquals(null, ruleCopy.getId()); assertEquals(2, ruleCopy.getTags().size()); assertEquals("Peter Jackson", ruleCopy.getMetaData().getCreator()); - + assertEquals("blah", ruleCopy.getLastSavedByUser()); } public void testRuleRuleSetHistory() { Modified: trunk/labs/jbossrules/drools-repository/src/test/java/org/drools/repository/db/PersistentCase.java =================================================================== --- trunk/labs/jbossrules/drools-repository/src/test/java/org/drools/repository/db/PersistentCase.java 2006-01-26 01:25:30 UTC (rev 2206) +++ trunk/labs/jbossrules/drools-repository/src/test/java/org/drools/repository/db/PersistentCase.java 2006-01-26 03:51:31 UTC (rev 2207) @@ -16,5 +16,6 @@ return RepositoryFactory.getRepository(); } + } |
From: <jbo...@li...> - 2006-01-26 01:25:38
|
Author: mic...@jb... Date: 2006-01-25 20:25:30 -0500 (Wed, 25 Jan 2006) New Revision: 2206 Modified: trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/db/RepoProxyHandler.java trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/db/StoreEventListener.java Log: improved threadlocal handling Modified: trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/db/RepoProxyHandler.java =================================================================== --- trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/db/RepoProxyHandler.java 2006-01-25 23:32:28 UTC (rev 2205) +++ trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/db/RepoProxyHandler.java 2006-01-26 01:25:30 UTC (rev 2206) @@ -34,10 +34,10 @@ private RepositoryManagerImpl repoImpl = new RepositoryManagerImpl(); - private Session session = null; + private Session session = null; //for stateful sessions private boolean stateful = false; + private Principal currentUser; //the user context, for auditing (optional) - /** * This is essentially for stateless repository access. * Default implementation uses hibernates getCurrentSession to @@ -76,30 +76,38 @@ Session session = getCurrentSession(); + //here we implement the "close" if (this.stateful && method.getName().equals("close")) { - return handleCloseSession( session ); + handleCloseSession( session ); + return null; } Transaction tx = null; try { tx = session.beginTransaction(); - configureSession( session ); + configure( session, currentUser ); Object result = method.invoke(repoImpl, args); tx.commit(); - - if (!stateful) { - this.repoImpl.injectSession(null); //not really needed, but to prove it is stateless ! - } return result; } catch (InvocationTargetException e) { rollback( tx ); checkForRepositoryException( session, e ); throw e.getTargetException(); + } + finally { + cleanup( ); } } + + private void cleanup() { + this.repoImpl.injectSession(null); + StoreEventListener.setCurrentConnection(null); + StoreEventListener.setCurrentUser(null); + } + /** * If its an instance of RepositoryException, we don't want to close the session. * It may just be a validation message being thrown. @@ -108,7 +116,7 @@ InvocationTargetException e) { if (! (e.getTargetException() instanceof RepositoryException)) { try { - repoImpl.injectSession(null); //not really needed... but anyway + session.close(); } catch (Exception e2) { /*ignore*/ } } @@ -117,10 +125,10 @@ /** * Should really only be called for stateful repository instances. */ - private Object handleCloseSession(Session session) { + private void handleCloseSession(Session session) { session.close(); StoreEventListener.setCurrentConnection(null); - return null; + StoreEventListener.setCurrentUser(null); } private void rollback(Transaction tx) { @@ -134,11 +142,14 @@ * Set the connection for the listeners to use (they use their own session). * Enable the default filters for historical stuff * and then provide the session to the repo implementation. + * Inject the currentUser for auditing etc as well. */ - private void configureSession(Session session) { + private void configure(Session session, Principal user) { StoreEventListener.setCurrentConnection( session.connection() ); + StoreEventListener.setCurrentUser( user ); repoImpl.enableHistoryFilter( session ); - repoImpl.injectSession( session ); + repoImpl.injectSession( session ); + this.repoImpl.setCurrentUser(currentUser); } @@ -153,9 +164,9 @@ } } - /** Pass through the current user for auditing and control purposes. */ + /** The current user for auditing and control purposes. */ public void setCurrentUser(Principal user) { - this.repoImpl.setCurrentUser(user); + this.currentUser = user; } Modified: trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/db/StoreEventListener.java =================================================================== --- trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/db/StoreEventListener.java 2006-01-25 23:32:28 UTC (rev 2205) +++ trunk/labs/jbossrules/drools-repository/src/main/java/org/drools/repository/db/StoreEventListener.java 2006-01-26 01:25:30 UTC (rev 2206) @@ -1,6 +1,7 @@ package org.drools.repository.db; import java.io.Serializable; +import java.security.Principal; import java.sql.Connection; import org.hibernate.EmptyInterceptor; @@ -25,6 +26,8 @@ //as we may not always use currentSession semantics. private static ThreadLocal currentConnection = new ThreadLocal(); + private static ThreadLocal currentUser = new ThreadLocal(); + public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, @@ -67,6 +70,14 @@ public static void setCurrentConnection(Connection conn) { currentConnection.set(conn); } + + /** + * Set the current user for auditing purposes. + * This is backed by a threadlocal. + */ + public static void setCurrentUser(Principal user) { + currentUser.set(user); + } private SessionFactory getSessionFactory() { return HibernateUtil.getSessionFactory(); |