You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@clerezza.apache.org by re...@apache.org on 2013/12/04 16:21:18 UTC
[1/9] CLEREZZA-435: repaced tabs with spaces in scala files
Updated Branches:
refs/heads/master a7d9d0fc3 -> 35448624b
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/site/src/main/scala/HeadedPageRenderlet.scala
----------------------------------------------------------------------
diff --git a/site/src/main/scala/HeadedPageRenderlet.scala b/site/src/main/scala/HeadedPageRenderlet.scala
index 3862edf..70f8275 100644
--- a/site/src/main/scala/HeadedPageRenderlet.scala
+++ b/site/src/main/scala/HeadedPageRenderlet.scala
@@ -16,20 +16,20 @@ import org.apache.clerezza.rdf.ontologies.DC
*/
class HeadedPageRenderlet extends SRenderlet {
- val getRdfType = PLATFORM.HeadedPage
+ val getRdfType = PLATFORM.HeadedPage
- override def getModePattern = "(?!.*naked).*"
+ override def getModePattern = "(?!.*naked).*"
- override def renderedPage(arguments: XmlResult.Arguments) = {
- new XmlResult(arguments) {
- def menuLink(href: String, label: String) =
- if ((res*).endsWith(href) || (res*).endsWith(href+"index")) {
- <a href={href} class="active">{label}</a>
- } else {
- <a href={href}>{label}</a>
- }
- override def content = {
- resultDocModifier.addStyleSheet("/style/style.css");
+ override def renderedPage(arguments: XmlResult.Arguments) = {
+ new XmlResult(arguments) {
+ def menuLink(href: String, label: String) =
+ if ((res*).endsWith(href) || (res*).endsWith(href+"index")) {
+ <a href={href} class="active">{label}</a>
+ } else {
+ <a href={href}>{label}</a>
+ }
+ override def content = {
+ resultDocModifier.addStyleSheet("/style/style.css");
resultDocModifier.addScriptReference("/jquery/jquery-1.3.2.min.js");
/*resultDocModifier.addScriptReference("/jquery/jquery.menu.js");
resultDocModifier.addScriptReference("/jquery/jquery.panel.js");
@@ -37,93 +37,93 @@ resultDocModifier.addScriptReference("/style/scripts/panel.js");*/
resultDocModifier.addScriptReference("/scripts/modification-status.js");
resultDocModifier.addScriptReference("/scripts/status-message.js");
<html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- {(res/DISCOBITS.contains).find(e => ((e/DISCOBITS.pos*) == "0")) match {
- case Some(e) => <title>{render(e/DISCOBITS.holds, "naked")}</title>
- case None => <title>An incomplete titled content {res/DISCOBITS.contains*}</title>
- }
- }
- </head>
- <body>
- <div class="zz-header">
- <div class="bar"></div>
- <div class="logo">
- <a href="http://clerezza.apache.org/" style=""><img src="/images/logo.png" alt="logo" /></a>
- </div>
- <div class="module-info">
- <span id="tx-module">
- <div id="tx-page-actions">
- <ol id="tx-page-actions-ol">
- </ol>
- </div>
- </span>
- <div id="tx-module-tabs">
- <ol id="tx-module-tabs-ol">
- </ol>
-
- </div>
- </div>
-
- <div class="zz-control">
- <div class="login">
- {
- def platform(s: Any) = new UriRef("http://clerezza.org/2009/08/platform#"+s)
- val username = (context/platform("user")/platform("userName")*)
- if((username).equals("anonymous")) {
- <span>
- <a href="#" id="tx-login-button">login</a>
- </span>
- } else {
- <span><a href={"/user/" + username + "/control-panel"}>{username}</a>|<a href="/logout">logout</a></span>
- }
- }
- </div>
- <div class="actions" id="tx-contextual-buttons">
- <ol id="tx-contextual-buttons-ol">
- </ol>
- </div>
- <div id="tx-module-options">
- <ol id="tx-module-options-ol">
- </ol>
- </div>
-
-
- <div class="tx-panel" id="tx-panel">
- <div id="tx-panel-title"><h3></h3></div>
- <div class="tx-panel-window">
- <div class="tx-panel-tab-buttons" id="tx-panel-tab-buttons">
- <ol id="tx-panel-tab-buttons-ol">
- </ol>
- </div>
- <div class="tx-panel-tabs" id="tx-panel-tabs"></div>
- </div>
- </div>
-
- </div>
- </div>
- {render(context,"menu")}
- <div class="zz-content">
- {
- if (mode == null) {
- render(res, "naked")
- } else {
- render(res, mode + "-naked")
- }
- }
- </div>
- <div class="footer">
- <div class="logos"><img src="/images/feather.png" /><img src="/images/sw-vert-w3c.png" /><img src="/images/footer-logo.png" /></div>
+ <head>
+ {(res/DISCOBITS.contains).find(e => ((e/DISCOBITS.pos*) == "0")) match {
+ case Some(e) => <title>{render(e/DISCOBITS.holds, "naked")}</title>
+ case None => <title>An incomplete titled content {res/DISCOBITS.contains*}</title>
+ }
+ }
+ </head>
+ <body>
+ <div class="zz-header">
+ <div class="bar"></div>
+ <div class="logo">
+ <a href="http://clerezza.apache.org/" style=""><img src="/images/logo.png" alt="logo" /></a>
+ </div>
+ <div class="module-info">
+ <span id="tx-module">
+ <div id="tx-page-actions">
+ <ol id="tx-page-actions-ol">
+ </ol>
+ </div>
+ </span>
+ <div id="tx-module-tabs">
+ <ol id="tx-module-tabs-ol">
+ </ol>
+
+ </div>
+ </div>
+
+ <div class="zz-control">
+ <div class="login">
+ {
+ def platform(s: Any) = new UriRef("http://clerezza.org/2009/08/platform#"+s)
+ val username = (context/platform("user")/platform("userName")*)
+ if((username).equals("anonymous")) {
+ <span>
+ <a href="#" id="tx-login-button">login</a>
+ </span>
+ } else {
+ <span><a href={"/user/" + username + "/control-panel"}>{username}</a>|<a href="/logout">logout</a></span>
+ }
+ }
+ </div>
+ <div class="actions" id="tx-contextual-buttons">
+ <ol id="tx-contextual-buttons-ol">
+ </ol>
+ </div>
+ <div id="tx-module-options">
+ <ol id="tx-module-options-ol">
+ </ol>
+ </div>
+
+
+ <div class="tx-panel" id="tx-panel">
+ <div id="tx-panel-title"><h3></h3></div>
+ <div class="tx-panel-window">
+ <div class="tx-panel-tab-buttons" id="tx-panel-tab-buttons">
+ <ol id="tx-panel-tab-buttons-ol">
+ </ol>
+ </div>
+ <div class="tx-panel-tabs" id="tx-panel-tabs"></div>
+ </div>
+ </div>
+
+ </div>
+ </div>
+ {render(context,"menu")}
+ <div class="zz-content">
+ {
+ if (mode == null) {
+ render(res, "naked")
+ } else {
+ render(res, mode + "-naked")
+ }
+ }
+ </div>
+ <div class="footer">
+ <div class="logos"><img src="/images/feather.png" /><img src="/images/sw-vert-w3c.png" /><img src="/images/footer-logo.png" /></div>
- <div class="divider"></div>
- <div class="dark">
- <div class="copyright">Apache Clerezza, Clerezza, Apache, the Apache feather logo, and the Apache Clerezza project logo are trademarks of The Apache Software Foundation. <br></br>© 2011 The Apache Software Foundation.</div>
- </div>
- </div>
- </body>
+ <div class="divider"></div>
+ <div class="dark">
+ <div class="copyright">Apache Clerezza, Clerezza, Apache, the Apache feather logo, and the Apache Clerezza project logo are trademarks of The Apache Software Foundation. <br></br>© 2011 The Apache Software Foundation.</div>
+ </div>
+ </div>
+ </body>
</html>
-
- }
- }
- }
+
+ }
+ }
+ }
}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/site/src/main/scala/Ontology.scala
----------------------------------------------------------------------
diff --git a/site/src/main/scala/Ontology.scala b/site/src/main/scala/Ontology.scala
index 6f24e28..9fba93e 100644
--- a/site/src/main/scala/Ontology.scala
+++ b/site/src/main/scala/Ontology.scala
@@ -4,9 +4,9 @@ import org.apache.clerezza.rdf.core.UriRef
object Ontology {
- /**
- * The uri for the RDF type of HelloWordMessage
- */
- val HelloWordMessageType = new UriRef("http://example.org/skeleton#HelloWordMessage")
+ /**
+ * The uri for the RDF type of HelloWordMessage
+ */
+ val HelloWordMessageType = new UriRef("http://example.org/skeleton#HelloWordMessage")
}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/site/src/main/scala/TitledContentRenderlet.scala
----------------------------------------------------------------------
diff --git a/site/src/main/scala/TitledContentRenderlet.scala b/site/src/main/scala/TitledContentRenderlet.scala
index e61c7c5..366d7d9 100644
--- a/site/src/main/scala/TitledContentRenderlet.scala
+++ b/site/src/main/scala/TitledContentRenderlet.scala
@@ -16,124 +16,124 @@ import org.apache.clerezza.rdf.ontologies.DC
*/
class TitledContentRenderlet extends SRenderlet {
- val getRdfType = DISCOBITS.TitledContent
-
- override def getModePattern = null
-
- override def renderedPage(arguments: XmlResult.Arguments) = {
- new XmlResult(arguments) {
- def menuLink(href: String, label: String) =
- if ((res*).endsWith(href) || (res*).endsWith(href+"index")) {
- <a href={href} class="active">{label}</a>
- } else {
- <a href={href}>{label}</a>
- }
- override def content = {
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <link type="text/css" href="/style/style.css" rel="stylesheet" />
- {(res/DISCOBITS.contains).find(e => ((e/DISCOBITS.pos*) == "0")) match {
- case Some(e) => <title>{render(e/DISCOBITS.holds, "naked")}</title>
- case None => <title>An incomplete titled content {res/DISCOBITS.contains*}</title>
- }
- }
- </head>
- <body>
- <div class="zz-header">
-
- <div class="bar"></div>
- <div class="logo">
- <a href="http://clerezza.apache.org/" style=""><img src="/images/logo.png" alt="logo" /></a>
- </div>
- </div>
- <div class="column nav">
- <ul>
- <li class="top-nav-entry"><div class="title">Documentation</div>
-
- <ul class="nav-entries">
- <li>{menuLink("/getting-started/","Getting Started")}</li>
- <li>{menuLink("/architecture/","The Apache Clerezza Stack")}</li>
- <li><a href="http://clerezza.apache.org/apidocs/" target="_blank">API docs</a></li>
- <li>{menuLink("/faq/","FAQ")}</li>
- </ul>
- </li>
-
- <li class="top-nav-entry"><div class="title">Project Infos</div>
- <ul class="nav-entries">
- <li>{menuLink("/downloads/","Downloads")}</li>
- <li>{menuLink("/contributing/", "Contributing")}</li>
- <li><a href="http://www.apache.org/licenses/" target="_blank">License</a></li>
- <li>{menuLink("/mailinglists/","Mailing lists")}</li>
- <li><a href="http://issues.apache.org/jira/browse/CLEREZZA" target="_blank">Issue Tracker</a></li>
-
- <li><a href="http://svn.apache.org/viewvc/clerezza/trunk/" target="_blank">Source Repository</a></li>
- </ul>
- </li>
- <li class="top-nav-entry"><div class="title">Sponsorship</div>
- <ul class="nav-entries">
- <li><a href="/thanks/">Thanks</a></li>
- <li><a href="http://www.apache.org/foundation/sponsorship.html" target="_blank">Become a Sponsor</a></li>
- <li><a href="http://www.apache.org/foundation/buy_stuff.html" target="_blank">Buy Stuff</a></li>
- </ul>
- </li>
- </ul>
- </div>
-
- <div class="zz-content">
- {render(res, "naked")}
- </div>
- <div class="footer">
- <div class="logos"><img src="/images/feather.png" /><img src="/images/sw-vert-w3c.png" /><img src="/images/footer-logo.png" /></div>
-
- <div class="divider"></div>
- <div class="dark">
- <div class="sitemap">
- <div class="sitemap-title">Sitemap</div>
- <div class="sitemap-content">
- <div class="sitemap-column">
- <div class="title" >Documentation</div>
- <ul>
-
- <li><a href="/getting-started/">Getting Started</a></li>
- <li><a href="/architecture/">The Apache Clerezza Stack</a></li>
- <li><a href="http://clerezza,apache.org/apidocs/" target="_blank">API docs</a></li>
- <li><a href="/faq/">FAQ</a></li>
- </ul>
-
- </div>
- <div class="sitemap-column">
-
- <div class="title" >Project Infos</div>
- <ul >
- <li><a href="/downloads/">Downloads</a></li>
- <li><a href="/contributing/">Contributing</a></li>
- <li><a href="http://www.apache.org/licenses/" target="_blank">License</a></li>
- <li><a href="mailinglists/">Mailing lists</a></li>
- <li><a href="http://issues.apache.org/jira/browse/CLEREZZA" target="_blank">Issue Tracker</a></li>
-
- <li><a href="http://svn.apache.org/viewvc/clerezza/trunk/" target="_blank">Source Repository</a></li>
- </ul>
- </div>
- <div class="sitemap-column">
- <div class="title" >Sponsorship</div>
- <ul>
- <li><a href="/thanks/">Thanks</a></li>
- <li><a href="http://www.apache.org/foundation/sponsorship.html" target="_blank">Become a Sponsor</a></li>
- <li><a href="http://www.apache.org/foundation/buy_stuff.html" target="_blank">Buy Stuff</a></li>
- </ul>
- </div>
- </div>
-
- </div>
- <div class="copyright">Apache Clerezza, Clerezza, Apache, the Apache feather logo, and the Apache Clerezza project logo are trademarks of The Apache Software Foundation. <br></br>© 2011 The Apache Software Foundation.</div>
- </div>
- </div>
-
-
- </body>
- </html>
- }
- }
- }
+ val getRdfType = DISCOBITS.TitledContent
+
+ override def getModePattern = null
+
+ override def renderedPage(arguments: XmlResult.Arguments) = {
+ new XmlResult(arguments) {
+ def menuLink(href: String, label: String) =
+ if ((res*).endsWith(href) || (res*).endsWith(href+"index")) {
+ <a href={href} class="active">{label}</a>
+ } else {
+ <a href={href}>{label}</a>
+ }
+ override def content = {
+ <html xmlns="http://www.w3.org/1999/xhtml">
+ <head>
+ <link type="text/css" href="/style/style.css" rel="stylesheet" />
+ {(res/DISCOBITS.contains).find(e => ((e/DISCOBITS.pos*) == "0")) match {
+ case Some(e) => <title>{render(e/DISCOBITS.holds, "naked")}</title>
+ case None => <title>An incomplete titled content {res/DISCOBITS.contains*}</title>
+ }
+ }
+ </head>
+ <body>
+ <div class="zz-header">
+
+ <div class="bar"></div>
+ <div class="logo">
+ <a href="http://clerezza.apache.org/" style=""><img src="/images/logo.png" alt="logo" /></a>
+ </div>
+ </div>
+ <div class="column nav">
+ <ul>
+ <li class="top-nav-entry"><div class="title">Documentation</div>
+
+ <ul class="nav-entries">
+ <li>{menuLink("/getting-started/","Getting Started")}</li>
+ <li>{menuLink("/architecture/","The Apache Clerezza Stack")}</li>
+ <li><a href="http://clerezza.apache.org/apidocs/" target="_blank">API docs</a></li>
+ <li>{menuLink("/faq/","FAQ")}</li>
+ </ul>
+ </li>
+
+ <li class="top-nav-entry"><div class="title">Project Infos</div>
+ <ul class="nav-entries">
+ <li>{menuLink("/downloads/","Downloads")}</li>
+ <li>{menuLink("/contributing/", "Contributing")}</li>
+ <li><a href="http://www.apache.org/licenses/" target="_blank">License</a></li>
+ <li>{menuLink("/mailinglists/","Mailing lists")}</li>
+ <li><a href="http://issues.apache.org/jira/browse/CLEREZZA" target="_blank">Issue Tracker</a></li>
+
+ <li><a href="http://svn.apache.org/viewvc/clerezza/trunk/" target="_blank">Source Repository</a></li>
+ </ul>
+ </li>
+ <li class="top-nav-entry"><div class="title">Sponsorship</div>
+ <ul class="nav-entries">
+ <li><a href="/thanks/">Thanks</a></li>
+ <li><a href="http://www.apache.org/foundation/sponsorship.html" target="_blank">Become a Sponsor</a></li>
+ <li><a href="http://www.apache.org/foundation/buy_stuff.html" target="_blank">Buy Stuff</a></li>
+ </ul>
+ </li>
+ </ul>
+ </div>
+
+ <div class="zz-content">
+ {render(res, "naked")}
+ </div>
+ <div class="footer">
+ <div class="logos"><img src="/images/feather.png" /><img src="/images/sw-vert-w3c.png" /><img src="/images/footer-logo.png" /></div>
+
+ <div class="divider"></div>
+ <div class="dark">
+ <div class="sitemap">
+ <div class="sitemap-title">Sitemap</div>
+ <div class="sitemap-content">
+ <div class="sitemap-column">
+ <div class="title" >Documentation</div>
+ <ul>
+
+ <li><a href="/getting-started/">Getting Started</a></li>
+ <li><a href="/architecture/">The Apache Clerezza Stack</a></li>
+ <li><a href="http://clerezza,apache.org/apidocs/" target="_blank">API docs</a></li>
+ <li><a href="/faq/">FAQ</a></li>
+ </ul>
+
+ </div>
+ <div class="sitemap-column">
+
+ <div class="title" >Project Infos</div>
+ <ul >
+ <li><a href="/downloads/">Downloads</a></li>
+ <li><a href="/contributing/">Contributing</a></li>
+ <li><a href="http://www.apache.org/licenses/" target="_blank">License</a></li>
+ <li><a href="mailinglists/">Mailing lists</a></li>
+ <li><a href="http://issues.apache.org/jira/browse/CLEREZZA" target="_blank">Issue Tracker</a></li>
+
+ <li><a href="http://svn.apache.org/viewvc/clerezza/trunk/" target="_blank">Source Repository</a></li>
+ </ul>
+ </div>
+ <div class="sitemap-column">
+ <div class="title" >Sponsorship</div>
+ <ul>
+ <li><a href="/thanks/">Thanks</a></li>
+ <li><a href="http://www.apache.org/foundation/sponsorship.html" target="_blank">Become a Sponsor</a></li>
+ <li><a href="http://www.apache.org/foundation/buy_stuff.html" target="_blank">Buy Stuff</a></li>
+ </ul>
+ </div>
+ </div>
+
+ </div>
+ <div class="copyright">Apache Clerezza, Clerezza, Apache, the Apache feather logo, and the Apache Clerezza project logo are trademarks of The Apache Software Foundation. <br></br>© 2011 The Apache Software Foundation.</div>
+ </div>
+ </div>
+
+
+ </body>
+ </html>
+ }
+ }
+ }
}
[2/9] CLEREZZA-435: repaced tabs with spaces in scala files
Posted by re...@apache.org.
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/scala-scripting/script-engine/src/main/scala/org/apache/clerezza/scala/scripting/ScriptEngineFactory.scala
----------------------------------------------------------------------
diff --git a/scala-scripting/script-engine/src/main/scala/org/apache/clerezza/scala/scripting/ScriptEngineFactory.scala b/scala-scripting/script-engine/src/main/scala/org/apache/clerezza/scala/scripting/ScriptEngineFactory.scala
index f5f1e0b..5f66c77 100644
--- a/scala-scripting/script-engine/src/main/scala/org/apache/clerezza/scala/scripting/ScriptEngineFactory.scala
+++ b/scala-scripting/script-engine/src/main/scala/org/apache/clerezza/scala/scripting/ScriptEngineFactory.scala
@@ -34,8 +34,8 @@ import java.security.AccessController
import java.security.PrivilegedAction
import javax.script.ScriptContext
import javax.script.{ScriptEngineFactory => JavaxEngineFactory, Compilable,
- CompiledScript, ScriptEngine, AbstractScriptEngine, Bindings,
- SimpleBindings, ScriptException}
+ CompiledScript, ScriptEngine, AbstractScriptEngine, Bindings,
+ SimpleBindings, ScriptException}
//import scala.collection.immutable.Map
import scala.actors.DaemonActor
import scala.tools.nsc._;
@@ -50,266 +50,266 @@ import scala.actors.Actor._
class ScriptEngineFactory() extends JavaxEngineFactory with BundleListener {
- def bundleChanged(event: BundleEvent) = {
- MyScriptEngine.interpreterAction ! ScriptEngineFactory.RefreshInterpreter
- //_interpreter = null
- }
+ def bundleChanged(event: BundleEvent) = {
+ MyScriptEngine.interpreterAction ! ScriptEngineFactory.RefreshInterpreter
+ //_interpreter = null
+ }
- private var factory: InterpreterFactory = null
- private var compilerService: CompilerService = null
- var _interpreter : IMain = null;
- private var bundleContext: BundleContext = null
- def interpreter = {
- if (_interpreter == null) {
- this.synchronized {
- if (_interpreter == null) {
- _interpreter = factory.createInterpreter(new PrintWriter(System.out))
- }
- }
- }
- _interpreter
- }
+ private var factory: InterpreterFactory = null
+ private var compilerService: CompilerService = null
+ var _interpreter : IMain = null;
+ private var bundleContext: BundleContext = null
+ def interpreter = {
+ if (_interpreter == null) {
+ this.synchronized {
+ if (_interpreter == null) {
+ _interpreter = factory.createInterpreter(new PrintWriter(System.out))
+ }
+ }
+ }
+ _interpreter
+ }
- //methods from ScriptEngineFactory
- override def getEngineName() = "Scala Scripting Engine for OSGi"
- override def getEngineVersion() = "0.3/scala 2.9.2"
- override def getExtensions() = java.util.Collections.singletonList("scala")
- override def getMimeTypes() = java.util.Collections.singletonList("application/x-scala")
- override def getNames() = java.util.Collections.singletonList("scala")
- override def getLanguageName() = "Scala"
- override def getLanguageVersion ="2.8.1"
- override def getParameter(key : String) = {
- key match {
- case ScriptEngine.ENGINE => getEngineName
- case ScriptEngine.ENGINE_VERSION => getEngineVersion
- case ScriptEngine.NAME => getNames.get(0)
- case ScriptEngine.LANGUAGE => getLanguageName
- case ScriptEngine.LANGUAGE_VERSION => getLanguageVersion
- case _ => null
- }
- }
- override def getMethodCallSyntax(obj : String,
- m : String,
- args : String*) = {
- obj+"."+m+"("+args.mkString(",")+")"
- }
- override def getOutputStatement(toDisplay : String) = "println(\""+toDisplay+"\")"
- override def getProgram(statements : String*) = statements.mkString("\n")
- override def getScriptEngine : ScriptEngine = MyScriptEngine
+ //methods from ScriptEngineFactory
+ override def getEngineName() = "Scala Scripting Engine for OSGi"
+ override def getEngineVersion() = "0.3/scala 2.9.2"
+ override def getExtensions() = java.util.Collections.singletonList("scala")
+ override def getMimeTypes() = java.util.Collections.singletonList("application/x-scala")
+ override def getNames() = java.util.Collections.singletonList("scala")
+ override def getLanguageName() = "Scala"
+ override def getLanguageVersion ="2.8.1"
+ override def getParameter(key : String) = {
+ key match {
+ case ScriptEngine.ENGINE => getEngineName
+ case ScriptEngine.ENGINE_VERSION => getEngineVersion
+ case ScriptEngine.NAME => getNames.get(0)
+ case ScriptEngine.LANGUAGE => getLanguageName
+ case ScriptEngine.LANGUAGE_VERSION => getLanguageVersion
+ case _ => null
+ }
+ }
+ override def getMethodCallSyntax(obj : String,
+ m : String,
+ args : String*) = {
+ obj+"."+m+"("+args.mkString(",")+")"
+ }
+ override def getOutputStatement(toDisplay : String) = "println(\""+toDisplay+"\")"
+ override def getProgram(statements : String*) = statements.mkString("\n")
+ override def getScriptEngine : ScriptEngine = MyScriptEngine
- def activate(componentContext: ComponentContext)= {
- bundleContext = componentContext.getBundleContext
- bundleContext.addBundleListener(this)
- }
+ def activate(componentContext: ComponentContext)= {
+ bundleContext = componentContext.getBundleContext
+ bundleContext.addBundleListener(this)
+ }
- def deactivate(componentContext: ComponentContext) = {
- bundleContext = componentContext.getBundleContext
- bundleContext.removeBundleListener(this)
- }
+ def deactivate(componentContext: ComponentContext) = {
+ bundleContext = componentContext.getBundleContext
+ bundleContext.removeBundleListener(this)
+ }
- def bindInterpreterFactory(f: InterpreterFactory) = {
- factory = f
- }
+ def bindInterpreterFactory(f: InterpreterFactory) = {
+ factory = f
+ }
- def unbindInterpreterFactory(f: InterpreterFactory) = {
- factory = null
- _interpreter = null
- }
+ def unbindInterpreterFactory(f: InterpreterFactory) = {
+ factory = null
+ _interpreter = null
+ }
- def bindCompilerService(s: CompilerService) = {
- compilerService = s
- }
+ def bindCompilerService(s: CompilerService) = {
+ compilerService = s
+ }
- def unbindCompilerService(s: CompilerService) = {
- compilerService = null
- }
- /** Inner object as it accesse interpreter
- */
- object MyScriptEngine extends AbstractScriptEngine() with Compilable {
- override def eval(script : Reader, context : ScriptContext) : Object = {
- val scriptStringWriter = new StringWriter()
- var ch = script.read
- while (ch != -1) {
- scriptStringWriter.write(ch)
- ch = script.read
- }
- eval(scriptStringWriter.toString, context)
- }
+ def unbindCompilerService(s: CompilerService) = {
+ compilerService = null
+ }
+ /** Inner object as it accesse interpreter
+ */
+ object MyScriptEngine extends AbstractScriptEngine() with Compilable {
+ override def eval(script : Reader, context : ScriptContext) : Object = {
+ val scriptStringWriter = new StringWriter()
+ var ch = script.read
+ while (ch != -1) {
+ scriptStringWriter.write(ch)
+ ch = script.read
+ }
+ eval(scriptStringWriter.toString, context)
+ }
- val interpreterAction = new DaemonActor {
- def act() {
- //not using loop { react {, as this method doesn't seem to guarantee
- //asynchronous execution
- //also using react with a final invocation of act() different exception from interprter.bind have been seen
- while(true) {
- receive {
- case (script : String, context : ScriptContext) => {
- //not yet threadsafe, but the test isn't failing
- //should pass jobs to actor that guarantees they are executed sequentially
- //and binding to not inferfere
- try {
- val jTypeMap : java.util.Map[String, java.lang.reflect.Type] =
- new java.util.HashMap[String, java.lang.reflect.Type]()
- val valueMap = new java.util.HashMap[String, Any]()
- import _root_.scala.collection.JavaConversions._
- for (scope <- context.getScopes;
- if (context.getBindings(scope.intValue) != null);
- entry <- context.getBindings(scope.intValue)) {
- interpreter.bind(entry._1,
- getAccessibleClass(entry._2.getClass).getName, entry._2)
- }
- interpreter.interpret("val zzScriptResult = {"+script+"}")
- println("visible stuff:")
- System.out.println("stuff stuff stuff");
- println("interpreter.valueOfTerm(\"zzScriptResult\"): "+interpreter.valueOfTerm("zzScriptResult"))
- interpreter.visibleTermNames.foreach(println)
- if (interpreter.reporter.hasErrors) {
- throw new ScriptException("some error","script-file",1)
- }
- sender ! interpreter.valueOfTerm("zzScriptResult")
- } catch {
- case e: Exception => sender ! ScriptEngineFactory.ActorException(e)
- }
- }
- case ScriptEngineFactory.RefreshInterpreter => {
- _interpreter = null;
- }
- }
- }
- }
- }
- interpreterAction.start()
+ val interpreterAction = new DaemonActor {
+ def act() {
+ //not using loop { react {, as this method doesn't seem to guarantee
+ //asynchronous execution
+ //also using react with a final invocation of act() different exception from interprter.bind have been seen
+ while(true) {
+ receive {
+ case (script : String, context : ScriptContext) => {
+ //not yet threadsafe, but the test isn't failing
+ //should pass jobs to actor that guarantees they are executed sequentially
+ //and binding to not inferfere
+ try {
+ val jTypeMap : java.util.Map[String, java.lang.reflect.Type] =
+ new java.util.HashMap[String, java.lang.reflect.Type]()
+ val valueMap = new java.util.HashMap[String, Any]()
+ import _root_.scala.collection.JavaConversions._
+ for (scope <- context.getScopes;
+ if (context.getBindings(scope.intValue) != null);
+ entry <- context.getBindings(scope.intValue)) {
+ interpreter.bind(entry._1,
+ getAccessibleClass(entry._2.getClass).getName, entry._2)
+ }
+ interpreter.interpret("val zzScriptResult = {"+script+"}")
+ println("visible stuff:")
+ System.out.println("stuff stuff stuff");
+ println("interpreter.valueOfTerm(\"zzScriptResult\"): "+interpreter.valueOfTerm("zzScriptResult"))
+ interpreter.visibleTermNames.foreach(println)
+ if (interpreter.reporter.hasErrors) {
+ throw new ScriptException("some error","script-file",1)
+ }
+ sender ! interpreter.valueOfTerm("zzScriptResult")
+ } catch {
+ case e: Exception => sender ! ScriptEngineFactory.ActorException(e)
+ }
+ }
+ case ScriptEngineFactory.RefreshInterpreter => {
+ _interpreter = null;
+ }
+ }
+ }
+ }
+ }
+ interpreterAction.start()
- override def eval(script : String, context : ScriptContext) : Object = {
- /*val timeout = 180*1000
- interpreterAction !? (timeout, (script, context)) match {
- case Some(x : Object) => x
- case x => throw new RuntimeException("Timeout executing script")
- }*/
- interpreterAction !? ((script, context)) match {
- case ScriptEngineFactory.ActorException(e) => throw e
- case x : Object => x match {
- case Some(y:Object) => y
- case None => null
- }
- }
- }
-
- override def getFactory() = ScriptEngineFactory.this
- override def createBindings() : Bindings = new SimpleBindings
+ override def eval(script : String, context : ScriptContext) : Object = {
+ /*val timeout = 180*1000
+ interpreterAction !? (timeout, (script, context)) match {
+ case Some(x : Object) => x
+ case x => throw new RuntimeException("Timeout executing script")
+ }*/
+ interpreterAction !? ((script, context)) match {
+ case ScriptEngineFactory.ActorException(e) => throw e
+ case x : Object => x match {
+ case Some(y:Object) => y
+ case None => null
+ }
+ }
+ }
+
+ override def getFactory() = ScriptEngineFactory.this
+ override def createBindings() : Bindings = new SimpleBindings
- override def compile(script: Reader): CompiledScript = {
- val scriptStringWriter = new StringWriter()
- var ch = script.read
- while (ch != -1) {
- scriptStringWriter.write(ch)
- ch = script.read
- }
- compile(scriptStringWriter.toString)
- }
+ override def compile(script: Reader): CompiledScript = {
+ val scriptStringWriter = new StringWriter()
+ var ch = script.read
+ while (ch != -1) {
+ scriptStringWriter.write(ch)
+ ch = script.read
+ }
+ compile(scriptStringWriter.toString)
+ }
-
- var classCounter = 0
+
+ var classCounter = 0
- val virtualDirectory = new VirtualDirectory("(memory)", None)
- var msgWriter = new StringWriter
+ val virtualDirectory = new VirtualDirectory("(memory)", None)
+ var msgWriter = new StringWriter
-
- override def compile(script: String): CompiledScript = {
- try {
- AccessController.doPrivileged(new PrivilegedAction[CompiledScript]() {
- override def run() = {
- val objectName = "CompiledScript"+classCounter
- classCounter += 1
- val classCode = "class " + objectName + """ {
- | def run($: Map[String, Object]) = {
- |""".stripMargin + script +"""
- | }
- |}""".stripMargin
- val sources: List[Array[Char]] = List(classCode.toCharArray)
- val clazz = try {
- compilerService.compile(sources)(0)
- } catch {
- case e: CompileErrorsException => throw new ScriptException(e.getMessage, "script", -1);
- case e: Exception => throw e
- }
- val scriptObject = clazz.newInstance()
+
+ override def compile(script: String): CompiledScript = {
+ try {
+ AccessController.doPrivileged(new PrivilegedAction[CompiledScript]() {
+ override def run() = {
+ val objectName = "CompiledScript"+classCounter
+ classCounter += 1
+ val classCode = "class " + objectName + """ {
+ | def run($: Map[String, Object]) = {
+ |""".stripMargin + script +"""
+ | }
+ |}""".stripMargin
+ val sources: List[Array[Char]] = List(classCode.toCharArray)
+ val clazz = try {
+ compilerService.compile(sources)(0)
+ } catch {
+ case e: CompileErrorsException => throw new ScriptException(e.getMessage, "script", -1);
+ case e: Exception => throw e
+ }
+ val scriptObject = clazz.newInstance()
- new CompiledScript() {
- override def eval(context: ScriptContext) = {
+ new CompiledScript() {
+ override def eval(context: ScriptContext) = {
- var map = Map[String, Object]()
- import _root_.scala.collection.JavaConversions._
- for ( scope <- context.getScopes;
- if (context.getBindings(scope.intValue) != null);
- entry <- context.getBindings(scope.intValue)) {
- map = map + (entry._1 -> entry._2)
- }
- val runMethod = clazz.getMethod("run", classOf[Map[String, Object]])
- try {
- runMethod.invoke(scriptObject, map)
- } catch {
- case e: InvocationTargetException => {
- throw e.getCause
- }
- }
- }
- override def getEngine = MyScriptEngine.this
- }
- }
- })
- } catch {
- case e: PrivilegedActionException => throw e.getCause
- }
- }
+ var map = Map[String, Object]()
+ import _root_.scala.collection.JavaConversions._
+ for ( scope <- context.getScopes;
+ if (context.getBindings(scope.intValue) != null);
+ entry <- context.getBindings(scope.intValue)) {
+ map = map + (entry._1 -> entry._2)
+ }
+ val runMethod = clazz.getMethod("run", classOf[Map[String, Object]])
+ try {
+ runMethod.invoke(scriptObject, map)
+ } catch {
+ case e: InvocationTargetException => {
+ throw e.getCause
+ }
+ }
+ }
+ override def getEngine = MyScriptEngine.this
+ }
+ }
+ })
+ } catch {
+ case e: PrivilegedActionException => throw e.getCause
+ }
+ }
-
+
-
+
- /**
- * returns an accessible class or interface that is implemented by class,
- * is doesn't look for superinterfaces of implement interfaces
- */
- private def getAccessibleClass(clazz : Class[_]) : Class[_] = {
- if(isAccessible(clazz)) {
- return clazz
- } else {
- val foo : Class[_] = clazz.getInterfaces()(0)
- for (implementedInterface <- clazz.getInterfaces()) {
- if (isAccessible(implementedInterface)) return implementedInterface
- }
- }
- return getAccessibleSuperClass(clazz)
- }
+ /**
+ * returns an accessible class or interface that is implemented by class,
+ * is doesn't look for superinterfaces of implement interfaces
+ */
+ private def getAccessibleClass(clazz : Class[_]) : Class[_] = {
+ if(isAccessible(clazz)) {
+ return clazz
+ } else {
+ val foo : Class[_] = clazz.getInterfaces()(0)
+ for (implementedInterface <- clazz.getInterfaces()) {
+ if (isAccessible(implementedInterface)) return implementedInterface
+ }
+ }
+ return getAccessibleSuperClass(clazz)
+ }
- private def getAccessibleSuperClass(clazz : Class[_]) : Class[_] = {
- val superClass = clazz.getSuperclass
- if (superClass == null) {
- throw new RuntimeException("No upper class to be checked for accessibility for "+clazz)
- }
- if (isAccessible(superClass)) {
- superClass
- } else {
- getAccessibleSuperClass(superClass)
- }
- }
+ private def getAccessibleSuperClass(clazz : Class[_]) : Class[_] = {
+ val superClass = clazz.getSuperclass
+ if (superClass == null) {
+ throw new RuntimeException("No upper class to be checked for accessibility for "+clazz)
+ }
+ if (isAccessible(superClass)) {
+ superClass
+ } else {
+ getAccessibleSuperClass(superClass)
+ }
+ }
- private def isAccessible(clazz : Class[_]) = {
- try {
- Class.forName(clazz.getName)
- true
- } catch {
- case e: Exception => false
- }
- }
- }
+ private def isAccessible(clazz : Class[_]) = {
+ try {
+ Class.forName(clazz.getName)
+ true
+ } catch {
+ case e: Exception => false
+ }
+ }
+ }
}
object ScriptEngineFactory {
- case class ActorException(e: Throwable);
- case object RefreshInterpreter;
+ case class ActorException(e: Throwable);
+ case object RefreshInterpreter;
}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/scala-scripting/script-engine/src/main/scala/org/apache/clerezza/scala/scripting/TrackingCompiler.scala
----------------------------------------------------------------------
diff --git a/scala-scripting/script-engine/src/main/scala/org/apache/clerezza/scala/scripting/TrackingCompiler.scala b/scala-scripting/script-engine/src/main/scala/org/apache/clerezza/scala/scripting/TrackingCompiler.scala
index c20e264..11cf3f1 100644
--- a/scala-scripting/script-engine/src/main/scala/org/apache/clerezza/scala/scripting/TrackingCompiler.scala
+++ b/scala-scripting/script-engine/src/main/scala/org/apache/clerezza/scala/scripting/TrackingCompiler.scala
@@ -39,90 +39,90 @@ import java.net._
/** a compiler that keeps track of classes added to the directory
*/
class TrackingCompiler private (bundleContext : BundleContext,
- settings: Settings, reporter: Reporter, classLoaderBuilder: () => ClassLoader,
- writtenClasses: mutable.ListBuffer[AbstractFile])
- extends BundleContextScalaCompiler(bundleContext : BundleContext,
- settings: Settings, reporter: Reporter) {
+ settings: Settings, reporter: Reporter, classLoaderBuilder: () => ClassLoader,
+ writtenClasses: mutable.ListBuffer[AbstractFile])
+ extends BundleContextScalaCompiler(bundleContext : BundleContext,
+ settings: Settings, reporter: Reporter) {
- /**
- * compiles a list of classes to settings.outputDirs returning a
- * the generated AbstractFiles
- */
- @throws(classOf[CompileErrorsException])
- def compileToDir(sources: List[Array[Char]]): List[AbstractFile] = {
- writtenClasses.clear()
- var i = 0
- val sourceFiles: List[SourceFile] = for(chars <- sources) yield {
- i = i +1;
- new BatchSourceFile("<script"+i+">", chars)
- }
- (new Run).compileSources(sourceFiles)
- if (reporter.hasErrors) {
- reporter.reset
- throw new CompileErrorsException;
- }
- writtenClasses.toList
- }
+ /**
+ * compiles a list of classes to settings.outputDirs returning a
+ * the generated AbstractFiles
+ */
+ @throws(classOf[CompileErrorsException])
+ def compileToDir(sources: List[Array[Char]]): List[AbstractFile] = {
+ writtenClasses.clear()
+ var i = 0
+ val sourceFiles: List[SourceFile] = for(chars <- sources) yield {
+ i = i +1;
+ new BatchSourceFile("<script"+i+">", chars)
+ }
+ (new Run).compileSources(sourceFiles)
+ if (reporter.hasErrors) {
+ reporter.reset
+ throw new CompileErrorsException;
+ }
+ writtenClasses.toList
+ }
- /**
- * compiles a list of class sources returning a list of compiled classes
- */
- @throws(classOf[CompileErrorsException])
- def compile(sources: List[Array[Char]]): List[Class[_]] = {
- val classFiles = compileToDir(sources)
- val classLoader = classLoaderBuilder()
- val result: List[Class[_]] = for (classFile <- classFiles;
- if (!classFile.name.contains('$'))) yield {
- val path = classFile.path
- val relevantPath = path.substring(path.indexOf('/')+1,path.lastIndexOf('.'))
- val fqn = relevantPath.replace("/",".")
- classLoader.loadClass(fqn)
- }
- return result
- }
-
+ /**
+ * compiles a list of class sources returning a list of compiled classes
+ */
+ @throws(classOf[CompileErrorsException])
+ def compile(sources: List[Array[Char]]): List[Class[_]] = {
+ val classFiles = compileToDir(sources)
+ val classLoader = classLoaderBuilder()
+ val result: List[Class[_]] = for (classFile <- classFiles;
+ if (!classFile.name.contains('$'))) yield {
+ val path = classFile.path
+ val relevantPath = path.substring(path.indexOf('/')+1,path.lastIndexOf('.'))
+ val fqn = relevantPath.replace("/",".")
+ classLoader.loadClass(fqn)
+ }
+ return result
+ }
+
}
object TrackingCompiler {
- private class TrackingCompilerSplittingDirectory extends SplittingDirectory
+ private class TrackingCompilerSplittingDirectory extends SplittingDirectory
- private def createClassLoader(dir: AbstractFile) = new AbstractFileClassLoader(dir, this.getClass.getClassLoader())
+ private def createClassLoader(dir: AbstractFile) = new AbstractFileClassLoader(dir, this.getClass.getClassLoader())
- def apply(bundleContext : BundleContext, out: PrintWriter, outputDirectoryOption: Option[AbstractFile]) = {
- val (outputDirectory, classLoaderBuilder): (AbstractFile, () => ClassLoader) = outputDirectoryOption match {
- case Some(d) => (d, () => createClassLoader(d))
- case None => {
- val d = new TrackingCompilerSplittingDirectory
- d.currentTarget = new VirtualDirectory("(memory)", None)
- def createClassLoaderAndReset() = {
- val r = createClassLoader(d.currentTarget)
- //println("created class loader with "+(for (c <- d.currentTarget) yield c).mkString("-"))
- d.currentTarget = new VirtualDirectory("(memory)", None)
- r
- }
- (d, createClassLoaderAndReset _)
- }
- }
+ def apply(bundleContext : BundleContext, out: PrintWriter, outputDirectoryOption: Option[AbstractFile]) = {
+ val (outputDirectory, classLoaderBuilder): (AbstractFile, () => ClassLoader) = outputDirectoryOption match {
+ case Some(d) => (d, () => createClassLoader(d))
+ case None => {
+ val d = new TrackingCompilerSplittingDirectory
+ d.currentTarget = new VirtualDirectory("(memory)", None)
+ def createClassLoaderAndReset() = {
+ val r = createClassLoader(d.currentTarget)
+ //println("created class loader with "+(for (c <- d.currentTarget) yield c).mkString("-"))
+ d.currentTarget = new VirtualDirectory("(memory)", None)
+ r
+ }
+ (d, createClassLoaderAndReset _)
+ }
+ }
- val writtenClasses: mutable.ListBuffer[AbstractFile] = mutable.ListBuffer[AbstractFile]()
- val settings = {
- def outputListener(abtractFile: AbstractFile) {
- writtenClasses += abtractFile
- }
- val settings = new Settings
- settings.outputDirs setSingleOutput VirtualDirectoryWrapper.wrap(outputDirectory, outputListener)
- settings
- }
- new TrackingCompiler(bundleContext,
- settings,
- new ConsoleReporter(settings, null, out) {
- override def printMessage(msg: String) {
- out write msg
- out.flush()
- }
- }, classLoaderBuilder, writtenClasses)
- }
+ val writtenClasses: mutable.ListBuffer[AbstractFile] = mutable.ListBuffer[AbstractFile]()
+ val settings = {
+ def outputListener(abtractFile: AbstractFile) {
+ writtenClasses += abtractFile
+ }
+ val settings = new Settings
+ settings.outputDirs setSingleOutput VirtualDirectoryWrapper.wrap(outputDirectory, outputListener)
+ settings
+ }
+ new TrackingCompiler(bundleContext,
+ settings,
+ new ConsoleReporter(settings, null, out) {
+ override def printMessage(msg: String) {
+ out write msg
+ out.flush()
+ }
+ }, classLoaderBuilder, writtenClasses)
+ }
}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/scala-scripting/script-engine/src/main/scala/org/apache/clerezza/scala/scripting/util/FileWrapper.scala
----------------------------------------------------------------------
diff --git a/scala-scripting/script-engine/src/main/scala/org/apache/clerezza/scala/scripting/util/FileWrapper.scala b/scala-scripting/script-engine/src/main/scala/org/apache/clerezza/scala/scripting/util/FileWrapper.scala
index 5fb27d3..2cd55fe 100644
--- a/scala-scripting/script-engine/src/main/scala/org/apache/clerezza/scala/scripting/util/FileWrapper.scala
+++ b/scala-scripting/script-engine/src/main/scala/org/apache/clerezza/scala/scripting/util/FileWrapper.scala
@@ -30,18 +30,18 @@ import scala.tools.nsc.io.AbstractFile
class FileWrapper(val wrapped: AbstractFile, val childWrapper: (AbstractFile) => AbstractFile) extends AbstractFile with GenericFileWrapperTrait {
- /** overriding this here rather than in the trait as this is a var in VirtualDirectory
- */
- def lastModified = {
- wrapped.lastModified
- }
+ /** overriding this here rather than in the trait as this is a var in VirtualDirectory
+ */
+ def lastModified = {
+ wrapped.lastModified
+ }
- override protected def unsupported(msg: String) = {
- println("unsupported!")
- try {
- super.unsupported(msg)
- } catch {
- case e: Exception => e.printStackTrace(); throw e
- }
- }
+ override protected def unsupported(msg: String) = {
+ println("unsupported!")
+ try {
+ super.unsupported(msg)
+ } catch {
+ case e: Exception => e.printStackTrace(); throw e
+ }
+ }
}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/scala-scripting/script-engine/src/main/scala/org/apache/clerezza/scala/scripting/util/GenericFileWrapperTrait.scala
----------------------------------------------------------------------
diff --git a/scala-scripting/script-engine/src/main/scala/org/apache/clerezza/scala/scripting/util/GenericFileWrapperTrait.scala b/scala-scripting/script-engine/src/main/scala/org/apache/clerezza/scala/scripting/util/GenericFileWrapperTrait.scala
index 4e55feb..d443eaa 100644
--- a/scala-scripting/script-engine/src/main/scala/org/apache/clerezza/scala/scripting/util/GenericFileWrapperTrait.scala
+++ b/scala-scripting/script-engine/src/main/scala/org/apache/clerezza/scala/scripting/util/GenericFileWrapperTrait.scala
@@ -29,63 +29,63 @@ package org.apache.clerezza.scala.scripting.util
import scala.tools.nsc.io.AbstractFile
trait GenericFileWrapperTrait extends AbstractFile with Wrapper[AbstractFile] {
- override def lookupNameUnchecked(name: String,directory: Boolean) = {
- childWrapper(wrapped.lookupNameUnchecked(name, directory))
- }
- override def lookupName(name: String,directory: Boolean) = {
- wrapped.lookupName(name, directory)
- }
- override def iterator = {
- //TODO wrap
- wrapped.iterator
- }
- override def output = {
- wrapped.output
- }
- override def input = {
- wrapped.input
- }
-
- override def isDirectory = {
- wrapped.isDirectory
- }
- override def delete = {
- wrapped.delete
- }
- override def create = {
- wrapped.create
- }
- override def file = {
- wrapped.file
- }
- override def container = {
- childWrapper(wrapped.container)
- }
- override def absolute = {
- childWrapper(wrapped.absolute)
- }
- override def path = {
- wrapped.path
- }
- override def name = {
- wrapped.name
- }
+ override def lookupNameUnchecked(name: String,directory: Boolean) = {
+ childWrapper(wrapped.lookupNameUnchecked(name, directory))
+ }
+ override def lookupName(name: String,directory: Boolean) = {
+ wrapped.lookupName(name, directory)
+ }
+ override def iterator = {
+ //TODO wrap
+ wrapped.iterator
+ }
+ override def output = {
+ wrapped.output
+ }
+ override def input = {
+ wrapped.input
+ }
+
+ override def isDirectory = {
+ wrapped.isDirectory
+ }
+ override def delete = {
+ wrapped.delete
+ }
+ override def create = {
+ wrapped.create
+ }
+ override def file = {
+ wrapped.file
+ }
+ override def container = {
+ childWrapper(wrapped.container)
+ }
+ override def absolute = {
+ childWrapper(wrapped.absolute)
+ }
+ override def path = {
+ wrapped.path
+ }
+ override def name = {
+ wrapped.name
+ }
- override def sizeOption = {
- wrapped.sizeOption
- }
+ override def sizeOption = {
+ wrapped.sizeOption
+ }
- override def lookupPath(path: String, directory: Boolean): AbstractFile = {
- childWrapper(wrapped.lookupPath(path, directory))
- }
- override def lookupPathUnchecked(path: String, directory: Boolean): AbstractFile = {
- childWrapper(wrapped.lookupPathUnchecked(path, directory))
- }
- override def fileNamed(name: String): AbstractFile = {
- childWrapper(wrapped.fileNamed(name))
- }
+ override def lookupPath(path: String, directory: Boolean): AbstractFile = {
+ childWrapper(wrapped.lookupPath(path, directory))
+ }
+ override def lookupPathUnchecked(path: String, directory: Boolean): AbstractFile = {
+ childWrapper(wrapped.lookupPathUnchecked(path, directory))
+ }
+ override def fileNamed(name: String): AbstractFile = {
+ childWrapper(wrapped.fileNamed(name))
+ }
- override def subdirectoryNamed(name: String): AbstractFile = {
- childWrapper(wrapped.subdirectoryNamed(name))
- }
+ override def subdirectoryNamed(name: String): AbstractFile = {
+ childWrapper(wrapped.subdirectoryNamed(name))
+ }
}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/scala-scripting/script-engine/src/main/scala/org/apache/clerezza/scala/scripting/util/SplittingDirectory.scala
----------------------------------------------------------------------
diff --git a/scala-scripting/script-engine/src/main/scala/org/apache/clerezza/scala/scripting/util/SplittingDirectory.scala b/scala-scripting/script-engine/src/main/scala/org/apache/clerezza/scala/scripting/util/SplittingDirectory.scala
index d28c29c..2d318c0 100644
--- a/scala-scripting/script-engine/src/main/scala/org/apache/clerezza/scala/scripting/util/SplittingDirectory.scala
+++ b/scala-scripting/script-engine/src/main/scala/org/apache/clerezza/scala/scripting/util/SplittingDirectory.scala
@@ -30,52 +30,52 @@ import scala.tools.nsc.io.AbstractFile
import scala.tools.nsc.io.VirtualDirectory
class SplittingDirectory()
- extends VirtualDirectory(null, None) with GenericFileWrapperTrait {
+ extends VirtualDirectory(null, None) with GenericFileWrapperTrait {
- var currentTarget: VirtualDirectory = null
+ var currentTarget: VirtualDirectory = null
- protected def wrapped: VirtualDirectory = {
- if (currentTarget == null) {
- throw new RuntimeException("No current Target set, SplittingDirectory not usable")
- }
- currentTarget
- }
+ protected def wrapped: VirtualDirectory = {
+ if (currentTarget == null) {
+ throw new RuntimeException("No current Target set, SplittingDirectory not usable")
+ }
+ currentTarget
+ }
- private def wrap(f: AbstractFile): AbstractFile = {
- f match {
- case d: VirtualDirectory => new VirtualDirectoryWrapper(d, wrap) {
- override def output = d.output
- }
- case o => new FileWrapper(o, wrap)
- }
- }
- val childWrapper: (AbstractFile) => AbstractFile = wrap
+ private def wrap(f: AbstractFile): AbstractFile = {
+ f match {
+ case d: VirtualDirectory => new VirtualDirectoryWrapper(d, wrap) {
+ override def output = d.output
+ }
+ case o => new FileWrapper(o, wrap)
+ }
+ }
+ val childWrapper: (AbstractFile) => AbstractFile = wrap
- //lastModified = wrapped.lastModified
+ //lastModified = wrapped.lastModified
- override def output = {
- wrapped.asInstanceOf[VirtualDirectory].output
- }
- override def input = {
- wrapped.asInstanceOf[VirtualDirectory].input
- }
- override def file = {
- wrapped.asInstanceOf[VirtualDirectory].file
- }
- override def container = {
- wrapped.asInstanceOf[VirtualDirectory].container
- }
- override def absolute = {
- wrapped.asInstanceOf[VirtualDirectory].absolute
- }
- override val name = "(splitting)"
-
- override def lookupPath(path: String, directory: Boolean): AbstractFile = {
- childWrapper(wrapped.lookupPath(path, directory))
- }
- override def lookupPathUnchecked(path: String, directory: Boolean): AbstractFile = {
- childWrapper(wrapped.lookupPathUnchecked(path, directory))
- }
+ override def output = {
+ wrapped.asInstanceOf[VirtualDirectory].output
+ }
+ override def input = {
+ wrapped.asInstanceOf[VirtualDirectory].input
+ }
+ override def file = {
+ wrapped.asInstanceOf[VirtualDirectory].file
+ }
+ override def container = {
+ wrapped.asInstanceOf[VirtualDirectory].container
+ }
+ override def absolute = {
+ wrapped.asInstanceOf[VirtualDirectory].absolute
+ }
+ override val name = "(splitting)"
+
+ override def lookupPath(path: String, directory: Boolean): AbstractFile = {
+ childWrapper(wrapped.lookupPath(path, directory))
+ }
+ override def lookupPathUnchecked(path: String, directory: Boolean): AbstractFile = {
+ childWrapper(wrapped.lookupPathUnchecked(path, directory))
+ }
}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/scala-scripting/script-engine/src/main/scala/org/apache/clerezza/scala/scripting/util/VirtualDirectoryWrapper.scala
----------------------------------------------------------------------
diff --git a/scala-scripting/script-engine/src/main/scala/org/apache/clerezza/scala/scripting/util/VirtualDirectoryWrapper.scala b/scala-scripting/script-engine/src/main/scala/org/apache/clerezza/scala/scripting/util/VirtualDirectoryWrapper.scala
index 7b43344..b56de63 100644
--- a/scala-scripting/script-engine/src/main/scala/org/apache/clerezza/scala/scripting/util/VirtualDirectoryWrapper.scala
+++ b/scala-scripting/script-engine/src/main/scala/org/apache/clerezza/scala/scripting/util/VirtualDirectoryWrapper.scala
@@ -30,67 +30,67 @@ import scala.reflect.io.AbstractFile
import scala.reflect.io.VirtualDirectory
class VirtualDirectoryWrapper(val wrapped: AbstractFile,
- val childWrapper: (AbstractFile) => AbstractFile) extends VirtualDirectory(null, None)
- with GenericFileWrapperTrait {
- lastModified =wrapped.lastModified
+ val childWrapper: (AbstractFile) => AbstractFile) extends VirtualDirectory(null, None)
+ with GenericFileWrapperTrait {
+ lastModified =wrapped.lastModified
- override def output = {
- wrapped.asInstanceOf[VirtualDirectory].output
- }
- override def input = {
- wrapped.asInstanceOf[VirtualDirectory].input
- }
- override def file = {
- wrapped.asInstanceOf[VirtualDirectory].file
- }
- override def container = {
- wrapped.asInstanceOf[VirtualDirectory].container
- }
- override def absolute = {
- wrapped.asInstanceOf[VirtualDirectory].absolute
- }
- override val name = {
- wrapped.name
- }
- override def lookupPath(path: String, directory: Boolean): AbstractFile = {
- childWrapper(wrapped.lookupPath(path, directory))
- }
- override def lookupPathUnchecked(path: String, directory: Boolean): AbstractFile = {
- childWrapper(wrapped.lookupPathUnchecked(path, directory))
- }
+ override def output = {
+ wrapped.asInstanceOf[VirtualDirectory].output
+ }
+ override def input = {
+ wrapped.asInstanceOf[VirtualDirectory].input
+ }
+ override def file = {
+ wrapped.asInstanceOf[VirtualDirectory].file
+ }
+ override def container = {
+ wrapped.asInstanceOf[VirtualDirectory].container
+ }
+ override def absolute = {
+ wrapped.asInstanceOf[VirtualDirectory].absolute
+ }
+ override val name = {
+ wrapped.name
+ }
+ override def lookupPath(path: String, directory: Boolean): AbstractFile = {
+ childWrapper(wrapped.lookupPath(path, directory))
+ }
+ override def lookupPathUnchecked(path: String, directory: Boolean): AbstractFile = {
+ childWrapper(wrapped.lookupPathUnchecked(path, directory))
+ }
}
object VirtualDirectoryWrapper {
- trait VirtualDirectoryFlavour extends VirtualDirectoryWrapper {
- abstract override def output = {
- println("unexpected call to output "+name)
- super.output
- }
- }
+ trait VirtualDirectoryFlavour extends VirtualDirectoryWrapper {
+ abstract override def output = {
+ println("unexpected call to output "+name)
+ super.output
+ }
+ }
- def wrap(f: AbstractFile, outputListenerParam: (AbstractFile) => Unit): AbstractFile = {
- def innerWrap(f: AbstractFile) = wrap(f, outputListenerParam)
- f match {
- case d: VirtualDirectory => new VirtualDirectoryWrapper(d,
- innerWrap)
- with LoggingFileWrapper with VirtualDirectoryFlavour {
- override def output = d.output
- val outputListener = outputListenerParam
- }
- case o => new FileWrapper(o, innerWrap) with LoggingFileWrapper {
- val outputListener = outputListenerParam
- }
- }
- }
+ def wrap(f: AbstractFile, outputListenerParam: (AbstractFile) => Unit): AbstractFile = {
+ def innerWrap(f: AbstractFile) = wrap(f, outputListenerParam)
+ f match {
+ case d: VirtualDirectory => new VirtualDirectoryWrapper(d,
+ innerWrap)
+ with LoggingFileWrapper with VirtualDirectoryFlavour {
+ override def output = d.output
+ val outputListener = outputListenerParam
+ }
+ case o => new FileWrapper(o, innerWrap) with LoggingFileWrapper {
+ val outputListener = outputListenerParam
+ }
+ }
+ }
- trait LoggingFileWrapper extends GenericFileWrapperTrait {
+ trait LoggingFileWrapper extends GenericFileWrapperTrait {
- val outputListener: (AbstractFile) => Unit
+ val outputListener: (AbstractFile) => Unit
- abstract override def output = {
- outputListener(this)
- super.output
- }
- }
+ abstract override def output = {
+ outputListener(this)
+ super.output
+ }
+ }
}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/scala-scripting/script-engine/src/main/scala/org/apache/clerezza/scala/scripting/util/Wrapper.scala
----------------------------------------------------------------------
diff --git a/scala-scripting/script-engine/src/main/scala/org/apache/clerezza/scala/scripting/util/Wrapper.scala b/scala-scripting/script-engine/src/main/scala/org/apache/clerezza/scala/scripting/util/Wrapper.scala
index 473fe6d..97d3dfd 100644
--- a/scala-scripting/script-engine/src/main/scala/org/apache/clerezza/scala/scripting/util/Wrapper.scala
+++ b/scala-scripting/script-engine/src/main/scala/org/apache/clerezza/scala/scripting/util/Wrapper.scala
@@ -27,6 +27,6 @@
package org.apache.clerezza.scala.scripting.util
trait Wrapper[T] {
- protected def wrapped: T
- protected def childWrapper: (T) => T
+ protected def wrapped: T
+ protected def childWrapper: (T) => T
}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/scala-scripting/tests/src/test/scala/org/apache/clerezza/scala/tests/CompilerServiceTest.scala
----------------------------------------------------------------------
diff --git a/scala-scripting/tests/src/test/scala/org/apache/clerezza/scala/tests/CompilerServiceTest.scala b/scala-scripting/tests/src/test/scala/org/apache/clerezza/scala/tests/CompilerServiceTest.scala
index 74dabb2..3832804 100644
--- a/scala-scripting/tests/src/test/scala/org/apache/clerezza/scala/tests/CompilerServiceTest.scala
+++ b/scala-scripting/tests/src/test/scala/org/apache/clerezza/scala/tests/CompilerServiceTest.scala
@@ -49,177 +49,177 @@ import scala.math.random
class CompilerServiceTest {
-
- @Inject
- private var bundleContext: BundleContext = null;
-
- private var webServerExist = false;
-
- private var service: CompilerService = null;
-
- @Before
- def getService() : Unit = {
- /*webServerExist = waitForWebserver();*/
- service = waitFor(classOf[CompilerService], 300000);
- }
-
- private def waitFor[T](aClass: Class[T], timeout: Long): T = {
- System.out.println("waiting for a " + aClass);
- val tracker = new ServiceTracker(bundleContext,
- aClass.getName(), null);
- tracker.open();
- val service = tracker.waitForService(timeout);
- return service.asInstanceOf[T];
- }
+
+ @Inject
+ private var bundleContext: BundleContext = null;
+
+ private var webServerExist = false;
+
+ private var service: CompilerService = null;
+
+ @Before
+ def getService() : Unit = {
+ /*webServerExist = waitForWebserver();*/
+ service = waitFor(classOf[CompilerService], 300000);
+ }
+
+ private def waitFor[T](aClass: Class[T], timeout: Long): T = {
+ System.out.println("waiting for a " + aClass);
+ val tracker = new ServiceTracker(bundleContext,
+ aClass.getName(), null);
+ tracker.open();
+ val service = tracker.waitForService(timeout);
+ return service.asInstanceOf[T];
+ }
//disabled, interpretation not currently working
-// @Test
-// def checkEngine(): Unit = {
-// Assert.assertNotNull(service);
-// //do it once
-// val testClassClass1 = {
-// val s = """
-// package foo {
-// class TestClass() {
-// println("constructing TestClass");
-// }
-// object TestClass {
-// println("constructing TestClass Object");
-// val msg = "Hello"
-// }
-// }
-// """
-// val compileResult = priv(service.compile(List(s.toCharArray)))
-// println("finished compiling")
-// Assert.assertEquals(1, compileResult.size)
-// val testClassClass: Class[_] = compileResult(0)
-// //Assert.assertEquals("foo.TestClass", testClassClass.getName)
-// testClassClass
-// }
-// //compile different class with same name
-// {
-// val s = """
-// package foo {
-// class TestClass() {
-// println("constructing a different TestClass");
-// }
-// object TestClass {
-// println("constructing TestClass Object");
-// val msg = "Hello2"
-// }
-// }
-// """
-// //and another class
-// val s2 = """
-// package foo {
-// class TestClass2() {
-// println("constructing TestClass2");
-// }
-// object TestClass2 {
-// println("constructing TestClass2 Object");
-// val msg = "Hello2b"
-// }
-// }
-// """
-// val compileResult = priv(service.compile(List(s.toCharArray, s2.toCharArray)))
-// Assert.assertEquals(2, compileResult.size)
-// val nameMsg = for (cr <- compileResult) yield
-// (cr.getName, {
-// val method = cr.getMethod("msg")
-// method.invoke(null)
-// })
-// val nameMsgMap = Map(nameMsg: _*)
-// Assert.assertTrue(nameMsgMap.contains("foo.TestClass"))
-// Assert.assertTrue(nameMsgMap.contains("foo.TestClass2"))
+// @Test
+// def checkEngine(): Unit = {
+// Assert.assertNotNull(service);
+// //do it once
+// val testClassClass1 = {
+// val s = """
+// package foo {
+// class TestClass() {
+// println("constructing TestClass");
+// }
+// object TestClass {
+// println("constructing TestClass Object");
+// val msg = "Hello"
+// }
+// }
+// """
+// val compileResult = priv(service.compile(List(s.toCharArray)))
+// println("finished compiling")
+// Assert.assertEquals(1, compileResult.size)
+// val testClassClass: Class[_] = compileResult(0)
+// //Assert.assertEquals("foo.TestClass", testClassClass.getName)
+// testClassClass
+// }
+// //compile different class with same name
+// {
+// val s = """
+// package foo {
+// class TestClass() {
+// println("constructing a different TestClass");
+// }
+// object TestClass {
+// println("constructing TestClass Object");
+// val msg = "Hello2"
+// }
+// }
+// """
+// //and another class
+// val s2 = """
+// package foo {
+// class TestClass2() {
+// println("constructing TestClass2");
+// }
+// object TestClass2 {
+// println("constructing TestClass2 Object");
+// val msg = "Hello2b"
+// }
+// }
+// """
+// val compileResult = priv(service.compile(List(s.toCharArray, s2.toCharArray)))
+// Assert.assertEquals(2, compileResult.size)
+// val nameMsg = for (cr <- compileResult) yield
+// (cr.getName, {
+// val method = cr.getMethod("msg")
+// method.invoke(null)
+// })
+// val nameMsgMap = Map(nameMsg: _*)
+// Assert.assertTrue(nameMsgMap.contains("foo.TestClass"))
+// Assert.assertTrue(nameMsgMap.contains("foo.TestClass2"))
//
-// Assert.assertEquals("Hello2", nameMsgMap("foo.TestClass"))
-// Assert.assertEquals("Hello2b", nameMsgMap("foo.TestClass2"))
-// }
-// val methodFrom1Again = testClassClass1.getMethod("msg")
-// Assert.assertEquals("Hello", methodFrom1Again.invoke(null))
-// }
-
- @Test
- def testConcurrency : Unit = {
- val startTime = System.currentTimeMillis
- import scala.actors.Actor._
- val actorsCount = 5
- val iterationsCount = 9
- val testRunner = self
- for (i <- 1 to actorsCount) {
- object ValueVerifier extends Actor {
- def act() {
- try {
- for (i <- 1 to iterationsCount) {
- val uniqueToken = (for (i <-1 to 12) yield ((random*('z'-'a'+1))+'a').asInstanceOf[Char]).mkString
- val objectName = "MyClass"
- val message = "Hello from "+uniqueToken
-
- val source = """
+// Assert.assertEquals("Hello2", nameMsgMap("foo.TestClass"))
+// Assert.assertEquals("Hello2b", nameMsgMap("foo.TestClass2"))
+// }
+// val methodFrom1Again = testClassClass1.getMethod("msg")
+// Assert.assertEquals("Hello", methodFrom1Again.invoke(null))
+// }
+
+ @Test
+ def testConcurrency : Unit = {
+ val startTime = System.currentTimeMillis
+ import scala.actors.Actor._
+ val actorsCount = 5
+ val iterationsCount = 9
+ val testRunner = self
+ for (i <- 1 to actorsCount) {
+ object ValueVerifier extends Actor {
+ def act() {
+ try {
+ for (i <- 1 to iterationsCount) {
+ val uniqueToken = (for (i <-1 to 12) yield ((random*('z'-'a'+1))+'a').asInstanceOf[Char]).mkString
+ val objectName = "MyClass"
+ val message = "Hello from "+uniqueToken
+
+ val source = """
object """+objectName+""" {
- println("constructing TestClass Object");
- val msg = """"+message+""""
+ println("constructing TestClass Object");
+ val msg = """"+message+""""
}"""
- //println("compiling: "+source)
- val sources = List(source.toCharArray)
- val compiled = priv(service.compile(sources))
- val clazz = compiled(0)
- val className = clazz.getName
- testRunner ! (objectName, className)
- val method = clazz.getMethod("msg")
- val receivedMessage = method.invoke(null)
- testRunner ! (message, receivedMessage)
- }
- } catch {
- case t: Throwable => testRunner ! t
- }
- }
- }
- ValueVerifier.start()
- }
- for (i <- 1 to (actorsCount*iterationsCount*2)) {
- self.receive {
- case (expected, got) => {
- Assert.assertEquals(expected, got)
- }
- case t : Throwable => throw t
- }
- }
- val duration = System.currentTimeMillis - startTime
- println("running the tests took "+duration)
-
- }
-
- def priv[T](action: => T): T = {
- try {
- AccessController.doPrivileged(
- new PrivilegedExceptionAction[T]() {
- def run = action
- })
- } catch {
- case e: PrivilegedActionException => throw e.getCause
- case e: Throwable => throw e
- }
- }
+ //println("compiling: "+source)
+ val sources = List(source.toCharArray)
+ val compiled = priv(service.compile(sources))
+ val clazz = compiled(0)
+ val className = clazz.getName
+ testRunner ! (objectName, className)
+ val method = clazz.getMethod("msg")
+ val receivedMessage = method.invoke(null)
+ testRunner ! (message, receivedMessage)
+ }
+ } catch {
+ case t: Throwable => testRunner ! t
+ }
+ }
+ }
+ ValueVerifier.start()
+ }
+ for (i <- 1 to (actorsCount*iterationsCount*2)) {
+ self.receive {
+ case (expected, got) => {
+ Assert.assertEquals(expected, got)
+ }
+ case t : Throwable => throw t
+ }
+ }
+ val duration = System.currentTimeMillis - startTime
+ println("running the tests took "+duration)
+
+ }
+
+ def priv[T](action: => T): T = {
+ try {
+ AccessController.doPrivileged(
+ new PrivilegedExceptionAction[T]() {
+ def run = action
+ })
+ } catch {
+ case e: PrivilegedActionException => throw e.getCause
+ case e: Throwable => throw e
+ }
+ }
}
object CompilerServiceTest {
- protected val testHttpPort = 8976;
-
- @Configuration
- def configuration() : Array[Option] = {
- return options(
- mavenConfiguration(),
- dsProfile(),
- configProfile(),
- //webProfile(),
- junitBundles(),
- frameworks(
- felix()),
- systemProperty("org.osgi.service.http.port").value(
- Integer.toString(testHttpPort)));
- }
+ protected val testHttpPort = 8976;
+
+ @Configuration
+ def configuration() : Array[Option] = {
+ return options(
+ mavenConfiguration(),
+ dsProfile(),
+ configProfile(),
+ //webProfile(),
+ junitBundles(),
+ frameworks(
+ felix()),
+ systemProperty("org.osgi.service.http.port").value(
+ Integer.toString(testHttpPort)));
+ }
}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/scala-scripting/tests/src/test/scala/org/apache/clerezza/scala/tests/ScriptEngineFactoryTest.scala
----------------------------------------------------------------------
diff --git a/scala-scripting/tests/src/test/scala/org/apache/clerezza/scala/tests/ScriptEngineFactoryTest.scala b/scala-scripting/tests/src/test/scala/org/apache/clerezza/scala/tests/ScriptEngineFactoryTest.scala
index 9a17897..8fa62fb 100644
--- a/scala-scripting/tests/src/test/scala/org/apache/clerezza/scala/tests/ScriptEngineFactoryTest.scala
+++ b/scala-scripting/tests/src/test/scala/org/apache/clerezza/scala/tests/ScriptEngineFactoryTest.scala
@@ -44,169 +44,169 @@ import scala.math.random
*/
@RunWith(classOf[JUnit4TestRunner])
class ScriptEngineFactoryTest {
-
+
-
- @Inject
- private var bundleContext: BundleContext = null;
-
- private var webServerExist = false;
+
+ @Inject
+ private var bundleContext: BundleContext = null;
+
+ private var webServerExist = false;
- private var factory: ScriptEngineFactory = null;
+ private var factory: ScriptEngineFactory = null;
- @Before
- def getService() : Unit = {
- /*webServerExist = waitForWebserver();*/
- factory = waitFor(classOf[ScriptEngineFactory], 300000);
- }
+ @Before
+ def getService() : Unit = {
+ /*webServerExist = waitForWebserver();*/
+ factory = waitFor(classOf[ScriptEngineFactory], 300000);
+ }
- private def waitFor[T](aClass: Class[T], timeout: Long): T = {
- System.out.println("waiting for a " + aClass);
- val tracker = new ServiceTracker(bundleContext,
- aClass.getName(), null);
- tracker.open();
- val service = tracker.waitForService(timeout);
- return service.asInstanceOf[T];
- }
+ private def waitFor[T](aClass: Class[T], timeout: Long): T = {
+ System.out.println("waiting for a " + aClass);
+ val tracker = new ServiceTracker(bundleContext,
+ aClass.getName(), null);
+ tracker.open();
+ val service = tracker.waitForService(timeout);
+ return service.asInstanceOf[T];
+ }
-//disabled, interpretation not currently working
-// @Test
-// def checkEngine(): Unit = {
-// Assert.assertNotNull(factory)
-// Assert.assertEquals("Scala Scripting Engine for OSGi", factory.getEngineName);
-// val s = "hello"
-// val engine = factory.getScriptEngine
-// Assert.assertEquals(s, engine.eval("\""+s+"\""))
-// val bindings = engine.createBindings
-// bindings.put("s",s)
-// Assert.assertEquals(s, engine.eval("s", bindings))
-// }
+//disabled, interpretation not currently working
+// @Test
+// def checkEngine(): Unit = {
+// Assert.assertNotNull(factory)
+// Assert.assertEquals("Scala Scripting Engine for OSGi", factory.getEngineName);
+// val s = "hello"
+// val engine = factory.getScriptEngine
+// Assert.assertEquals(s, engine.eval("\""+s+"\""))
+// val bindings = engine.createBindings
+// bindings.put("s",s)
+// Assert.assertEquals(s, engine.eval("s", bindings))
+// }
//
-// @Test
-// def testConcurrency : Unit = {
-// val startTime = System.currentTimeMillis
-// import scala.actors.Actor._
-// val actorsCount = 5
-// val iterationsCount = 9
-// val testRunner = self
-// for (i <- 1 to actorsCount) {
-// object ValueVerifier extends Actor {
-// def act() {
-// try {
-// for (i <- 1 to iterationsCount) {
-// val s = "r: "+random.toString
-// val engine = factory.getScriptEngine
-// val bindings = engine.createBindings
-// bindings.put("s",s)
-// val script = """
+// @Test
+// def testConcurrency : Unit = {
+// val startTime = System.currentTimeMillis
+// import scala.actors.Actor._
+// val actorsCount = 5
+// val iterationsCount = 9
+// val testRunner = self
+// for (i <- 1 to actorsCount) {
+// object ValueVerifier extends Actor {
+// def act() {
+// try {
+// for (i <- 1 to iterationsCount) {
+// val s = "r: "+random.toString
+// val engine = factory.getScriptEngine
+// val bindings = engine.createBindings
+// bindings.put("s",s)
+// val script = """
//import scala.math.random
//Thread.sleep((random*10).toInt)
//s"""
-// testRunner ! (s, engine.eval(script, bindings))
-// }
-// } catch {
-// case t => testRunner ! t
-// }
-// }
-// }
-// ValueVerifier.start()
-// }
-// for (i <- 1 to (actorsCount*iterationsCount)) {
-// self.receive {
-// case (expected, got) => {
-// Assert.assertEquals(expected, got)
-// }
-// case t : Throwable => throw t
-// }
-// }
-// val duration = System.currentTimeMillis - startTime
-// println("running the tests took "+duration)
+// testRunner ! (s, engine.eval(script, bindings))
+// }
+// } catch {
+// case t => testRunner ! t
+// }
+// }
+// }
+// ValueVerifier.start()
+// }
+// for (i <- 1 to (actorsCount*iterationsCount)) {
+// self.receive {
+// case (expected, got) => {
+// Assert.assertEquals(expected, got)
+// }
+// case t : Throwable => throw t
+// }
+// }
+// val duration = System.currentTimeMillis - startTime
+// println("running the tests took "+duration)
//
-// }
+// }
//
-// @Test
-// def classFromNewlyAddedBundle(): Unit = {
-// val s = "hello"
-// val engine = factory.getScriptEngine
-// val bindings = engine.createBindings
-// bindings.put("s",s)
-// Assert.assertEquals(s, engine.eval("s", bindings))
-// bundleContext.installBundle("http://repo2.maven.org/maven2/org/wymiwyg/wrhapi/0.8.2/wrhapi-0.8.2.jar");
-// Thread.sleep(100)
-// val script = """
-// |import org.wymiwyg.wrhapi._
-// |val h : Handler = null
-// |s""".stripMargin
-// Assert.assertEquals(s, engine.eval(script, bindings))
-// }
+// @Test
+// def classFromNewlyAddedBundle(): Unit = {
+// val s = "hello"
+// val engine = factory.getScriptEngine
+// val bindings = engine.createBindings
+// bindings.put("s",s)
+// Assert.assertEquals(s, engine.eval("s", bindings))
+// bundleContext.installBundle("http://repo2.maven.org/maven2/org/wymiwyg/wrhapi/0.8.2/wrhapi-0.8.2.jar");
+// Thread.sleep(100)
+// val script = """
+// |import org.wymiwyg.wrhapi._
+// |val h : Handler = null
+// |s""".stripMargin
+// Assert.assertEquals(s, engine.eval(script, bindings))
+// }
- @Test
- def compiledScript(): Unit = {
- val string = "hello"
- val script = "\""+string+"\""
- val engine = factory.getScriptEngine.asInstanceOf[Compilable]
- val compiledScript = engine.compile(script)
- Assert.assertEquals(string, compiledScript.eval())
- }
-
- @Test(expected=classOf[ScriptException])
- def compileErrorScript(): Unit = {
- val script = "this is not real scala !"
- val engine = factory.getScriptEngine.asInstanceOf[Compilable]
- val compiledScript = engine.compile(script)
- }
-
- @Test(expected=classOf[ScriptException])
- def compileUnfinishedScript(): Unit = {
- val script = "if (true) {"
- val engine = factory.getScriptEngine.asInstanceOf[Compilable]
- val compiledScript = engine.compile(script)
- }
+ @Test
+ def compiledScript(): Unit = {
+ val string = "hello"
+ val script = "\""+string+"\""
+ val engine = factory.getScriptEngine.asInstanceOf[Compilable]
+ val compiledScript = engine.compile(script)
+ Assert.assertEquals(string, compiledScript.eval())
+ }
+
+ @Test(expected=classOf[ScriptException])
+ def compileErrorScript(): Unit = {
+ val script = "this is not real scala !"
+ val engine = factory.getScriptEngine.asInstanceOf[Compilable]
+ val compiledScript = engine.compile(script)
+ }
+
+ @Test(expected=classOf[ScriptException])
+ def compileUnfinishedScript(): Unit = {
+ val script = "if (true) {"
+ val engine = factory.getScriptEngine.asInstanceOf[Compilable]
+ val compiledScript = engine.compile(script)
+ }
-
- def compileNormalAfterErrorScript(): Unit = {
- val script = "this is not real scala !"
- val engine = factory.getScriptEngine.asInstanceOf[Compilable]
- try {
- val compiledScript = engine.compile(script)
- } catch {
- case e: Throwable => Assert.assertEquals(classOf[ScriptException], e.getClass)
- }
- val string = "hello"
- val script2 = "\""+string+"\""
- val compiledScript2 = engine.compile(script2)
- Assert.assertEquals(string, compiledScript2.eval())
- }
- //This seems hard to realize before https://lampsvn.epfl.ch/trac/scala/ticket/3513 is fixed
- /*@Test
- def checkException(): Unit = {
- val s = """val s="hello"
- illegal.do"""
- val engine = factory.getScriptEngine
- try {
- Assert.assertEquals("should have exception",engine.eval(s))
- } catch {
- case e : ScriptException => Assert.assertEquals(2, e.getLineNumber)
- }
- }*/
+
+ def compileNormalAfterErrorScript(): Unit = {
+ val script = "this is not real scala !"
+ val engine = factory.getScriptEngine.asInstanceOf[Compilable]
+ try {
+ val compiledScript = engine.compile(script)
+ } catch {
+ case e: Throwable => Assert.assertEquals(classOf[ScriptException], e.getClass)
+ }
+ val string = "hello"
+ val script2 = "\""+string+"\""
+ val compiledScript2 = engine.compile(script2)
+ Assert.assertEquals(string, compiledScript2.eval())
+ }
+ //This seems hard to realize before https://lampsvn.epfl.ch/trac/scala/ticket/3513 is fixed
+ /*@Test
+ def checkException(): Unit = {
+ val s = """val s="hello"
+ illegal.do"""
+ val engine = factory.getScriptEngine
+ try {
+ Assert.assertEquals("should have exception",engine.eval(s))
+ } catch {
+ case e : ScriptException => Assert.assertEquals(2, e.getLineNumber)
+ }
+ }*/
}
object ScriptEngineFactoryTest {
- protected val testHttpPort = 8976;
+ protected val testHttpPort = 8976;
- @Configuration
- def configuration() : Array[Option] = {
- return options(
- mavenConfiguration(),
- //using old ds because of issues with 1.0.8
- dsProfile(),
- configProfile(),
- webProfile(),
- junitBundles(),
- frameworks(
- felix()),
- systemProperty("org.osgi.service.http.port").value(
- Integer.toString(testHttpPort)));
- }
+ @Configuration
+ def configuration() : Array[Option] = {
+ return options(
+ mavenConfiguration(),
+ //using old ds because of issues with 1.0.8
+ dsProfile(),
+ configProfile(),
+ webProfile(),
+ junitBundles(),
+ frameworks(
+ felix()),
+ systemProperty("org.osgi.service.http.port").value(
+ Integer.toString(testHttpPort)));
+ }
}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/shell.felixshellcommand/src/main/scala/org/apache/clerezza/shell/felixshellcommand/FelixShellCommand.scala
----------------------------------------------------------------------
diff --git a/shell.felixshellcommand/src/main/scala/org/apache/clerezza/shell/felixshellcommand/FelixShellCommand.scala b/shell.felixshellcommand/src/main/scala/org/apache/clerezza/shell/felixshellcommand/FelixShellCommand.scala
index db6ae4b..591c105 100644
--- a/shell.felixshellcommand/src/main/scala/org/apache/clerezza/shell/felixshellcommand/FelixShellCommand.scala
+++ b/shell.felixshellcommand/src/main/scala/org/apache/clerezza/shell/felixshellcommand/FelixShellCommand.scala
@@ -24,27 +24,27 @@ import org.apache.clerezza.shell.ShellCommand
import org.apache.felix.shell.ShellService
class FelixShellCommand extends ShellCommand {
- private var felixShell: ShellService = null
-
- def command: String = "felix"
- def description: String = "execute a felix shell command"
- /**
- * Extecutes the command an return (keepRunning,Option[lineToRecord])
- */
- def execute(line: String, out: OutputStream): (Boolean, Option[String]) = {
- val printStream = new PrintStream(out)
- felixShell.executeCommand(line, printStream, printStream)
- printStream.flush()
- (true, None)
- }
-
- def bindFelixShell(felixShell: ShellService) {
- this.felixShell = felixShell
- }
-
- def unbindFelixShell(felixShell: ShellService) {
- this.felixShell = null
- }
+ private var felixShell: ShellService = null
+
+ def command: String = "felix"
+ def description: String = "execute a felix shell command"
+ /**
+ * Extecutes the command an return (keepRunning,Option[lineToRecord])
+ */
+ def execute(line: String, out: OutputStream): (Boolean, Option[String]) = {
+ val printStream = new PrintStream(out)
+ felixShell.executeCommand(line, printStream, printStream)
+ printStream.flush()
+ (true, None)
+ }
+
+ def bindFelixShell(felixShell: ShellService) {
+ this.felixShell = felixShell
+ }
+
+ def unbindFelixShell(felixShell: ShellService) {
+ this.felixShell = null
+ }
}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/shell/src/main/scala/org/apache/clerezza/shell/ConsoleShell.scala
----------------------------------------------------------------------
diff --git a/shell/src/main/scala/org/apache/clerezza/shell/ConsoleShell.scala b/shell/src/main/scala/org/apache/clerezza/shell/ConsoleShell.scala
index 835d9e1..cd3c13d 100644
--- a/shell/src/main/scala/org/apache/clerezza/shell/ConsoleShell.scala
+++ b/shell/src/main/scala/org/apache/clerezza/shell/ConsoleShell.scala
@@ -37,57 +37,57 @@ class ConsoleShell() {
- var factory: ShellFactory = null
- var bundleContext: BundleContext = null
- var stoppedBundle: Option[Bundle] = None
- var shellOption: Option[Shell] = None
- var interruptibleIn: InterruptibleInputStream = null
+ var factory: ShellFactory = null
+ var bundleContext: BundleContext = null
+ var stoppedBundle: Option[Bundle] = None
+ var shellOption: Option[Shell] = None
+ var interruptibleIn: InterruptibleInputStream = null
- def activate(componentContext: ComponentContext)= {
- bundleContext = componentContext.getBundleContext
- if (("true" != bundleContext.getProperty("clerezza.shell.disable")) &&
- (System.console != null)) {
- for (bundle <- bundleContext.getBundles;
- if (bundle.getSymbolicName == "org.apache.felix.shell.tui");
- if (bundle.getState == Bundle.ACTIVE)) {
- println("stopping "+bundle);
- bundle.stop()
- stoppedBundle = Some(bundle)
- }
- //this call sets the console terminal to the right settings
- //and it must not be invoked when there is no console input, or the system will stop
- val terminalOption = Some(scala.tools.jline.TerminalFactory.create())
- val in = Channels.newInputStream(
- (new FileInputStream(FileDescriptor.in)).getChannel());
- interruptibleIn = new InterruptibleInputStream(in)
- val shell = factory.createShell(interruptibleIn, System.out, terminalOption)
- shell.start()
- shellOption = Some(shell)
- }
- }
+ def activate(componentContext: ComponentContext)= {
+ bundleContext = componentContext.getBundleContext
+ if (("true" != bundleContext.getProperty("clerezza.shell.disable")) &&
+ (System.console != null)) {
+ for (bundle <- bundleContext.getBundles;
+ if (bundle.getSymbolicName == "org.apache.felix.shell.tui");
+ if (bundle.getState == Bundle.ACTIVE)) {
+ println("stopping "+bundle);
+ bundle.stop()
+ stoppedBundle = Some(bundle)
+ }
+ //this call sets the console terminal to the right settings
+ //and it must not be invoked when there is no console input, or the system will stop
+ val terminalOption = Some(scala.tools.jline.TerminalFactory.create())
+ val in = Channels.newInputStream(
+ (new FileInputStream(FileDescriptor.in)).getChannel());
+ interruptibleIn = new InterruptibleInputStream(in)
+ val shell = factory.createShell(interruptibleIn, System.out, terminalOption)
+ shell.start()
+ shellOption = Some(shell)
+ }
+ }
- def deactivate(componentContext: ComponentContext) = {
- bundleContext = componentContext.getBundleContext
- stoppedBundle match {
- case Some(bundle) => bundle.start()
- case _ =>
- }
- shellOption match {
- case Some(shell) => shell.stop()
- case _ =>
- }
- if (interruptibleIn != null) {
- interruptibleIn.terminate()
- }
- }
+ def deactivate(componentContext: ComponentContext) = {
+ bundleContext = componentContext.getBundleContext
+ stoppedBundle match {
+ case Some(bundle) => bundle.start()
+ case _ =>
+ }
+ shellOption match {
+ case Some(shell) => shell.stop()
+ case _ =>
+ }
+ if (interruptibleIn != null) {
+ interruptibleIn.terminate()
+ }
+ }
- def bindShellFactory(f: ShellFactory) = {
- factory = f
- }
+ def bindShellFactory(f: ShellFactory) = {
+ factory = f
+ }
- def unbindShellFactory(f: ShellFactory) = {
- factory = null
- }
-
+ def unbindShellFactory(f: ShellFactory) = {
+ factory = null
+ }
+
}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/shell/src/main/scala/org/apache/clerezza/shell/InterruptibleInputStream.scala
----------------------------------------------------------------------
diff --git a/shell/src/main/scala/org/apache/clerezza/shell/InterruptibleInputStream.scala b/shell/src/main/scala/org/apache/clerezza/shell/InterruptibleInputStream.scala
index fcd0e0f..d4db45b 100644
--- a/shell/src/main/scala/org/apache/clerezza/shell/InterruptibleInputStream.scala
+++ b/shell/src/main/scala/org/apache/clerezza/shell/InterruptibleInputStream.scala
@@ -24,47 +24,47 @@ import scala.actors.Actor
import scala.actors.Actor._
class InterruptibleInputStream(base: InputStream) extends InputStream {
- private case object Stop
- private case object Read
+ private case object Stop
+ private case object Read
- private var readingThread: Thread = null
+ private var readingThread: Thread = null
- val readerActor = new Actor() {
- def act() {
- loop {
- react {
- case Stop => exit()
- case Read => {
- readingThread = Thread.currentThread
- val ch = try {
- base.read()
- } catch {
- case e: ClosedByInterruptException => {
- -1
- }
- }
- readingThread = null
- sender ! ch
- }
- }
- }
- }
- }
- readerActor.start()
+ val readerActor = new Actor() {
+ def act() {
+ loop {
+ react {
+ case Stop => exit()
+ case Read => {
+ readingThread = Thread.currentThread
+ val ch = try {
+ base.read()
+ } catch {
+ case e: ClosedByInterruptException => {
+ -1
+ }
+ }
+ readingThread = null
+ sender ! ch
+ }
+ }
+ }
+ }
+ }
+ readerActor.start()
- def read() = {
- readerActor ! Read
- self.receive {
- case x: Int => x
- }
- }
+ def read() = {
+ readerActor ! Read
+ self.receive {
+ case x: Int => x
+ }
+ }
- def terminate() {
- readerActor ! Stop
- val currentReadingThread = readingThread
- if (currentReadingThread != null) {
- currentReadingThread.interrupt()
- }
- }
+ def terminate() {
+ readerActor ! Stop
+ val currentReadingThread = readingThread
+ if (currentReadingThread != null) {
+ currentReadingThread.interrupt()
+ }
+ }
}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/shell/src/main/scala/org/apache/clerezza/shell/Shell.scala
----------------------------------------------------------------------
diff --git a/shell/src/main/scala/org/apache/clerezza/shell/Shell.scala b/shell/src/main/scala/org/apache/clerezza/shell/Shell.scala
index fce3200..412819d 100644
--- a/shell/src/main/scala/org/apache/clerezza/shell/Shell.scala
+++ b/shell/src/main/scala/org/apache/clerezza/shell/Shell.scala
@@ -184,9 +184,9 @@ class Shell(factory: InterpreterFactory, val inStream: InputStream,
import Properties._
val welcomeMsg =
"""|Welcome to the Apache Clerezza Console
- |Console is based on Scala %s (%s, Java %s).
- |Type in expressions to have them evaluated.
- |Type :help for more information.""".
+ |Console is based on Scala %s (%s, Java %s).
+ |Type in expressions to have them evaluated.
+ |Type :help for more information.""".
stripMargin.format(versionString, javaVmName, javaVersion)
echo(welcomeMsg)
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/shell/src/main/scala/org/apache/clerezza/shell/ShellCommand.scala
----------------------------------------------------------------------
diff --git a/shell/src/main/scala/org/apache/clerezza/shell/ShellCommand.scala b/shell/src/main/scala/org/apache/clerezza/shell/ShellCommand.scala
index b83a269..d6dcd29 100644
--- a/shell/src/main/scala/org/apache/clerezza/shell/ShellCommand.scala
+++ b/shell/src/main/scala/org/apache/clerezza/shell/ShellCommand.scala
@@ -21,10 +21,10 @@ package org.apache.clerezza.shell
import java.io.OutputStream
trait ShellCommand {
- def command: String
- def description: String
- /**
- * Extecutes the command an return (keepRunning,Option[lineToRecord])
- */
- def execute(line: String, out: OutputStream): (Boolean, Option[String])
+ def command: String
+ def description: String
+ /**
+ * Extecutes the command an return (keepRunning,Option[lineToRecord])
+ */
+ def execute(line: String, out: OutputStream): (Boolean, Option[String])
}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/shell/src/main/scala/org/apache/clerezza/shell/ShellCustomizer.scala
----------------------------------------------------------------------
diff --git a/shell/src/main/scala/org/apache/clerezza/shell/ShellCustomizer.scala b/shell/src/main/scala/org/apache/clerezza/shell/ShellCustomizer.scala
index 80d02d8..d5487e6 100644
--- a/shell/src/main/scala/org/apache/clerezza/shell/ShellCustomizer.scala
+++ b/shell/src/main/scala/org/apache/clerezza/shell/ShellCustomizer.scala
@@ -29,14 +29,14 @@ import org.osgi.service.component.ComponentContext
*/
trait ShellCustomizer {
- /**
- * A list of bindings that will be available in the shell
- * The tuple consist of: bindingName, typeName, value
- */
- def bindings(e: Shell.Environment): List[(String, String, Any)]
+ /**
+ * A list of bindings that will be available in the shell
+ * The tuple consist of: bindingName, typeName, value
+ */
+ def bindings(e: Shell.Environment): List[(String, String, Any)]
- /**
- * A list of imports that will be available in the shell
- */
- def imports: List[String]
+ /**
+ * A list of imports that will be available in the shell
+ */
+ def imports: List[String]
}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/shell/src/main/scala/org/apache/clerezza/shell/ShellPermission.scala
----------------------------------------------------------------------
diff --git a/shell/src/main/scala/org/apache/clerezza/shell/ShellPermission.scala b/shell/src/main/scala/org/apache/clerezza/shell/ShellPermission.scala
index 018ca19..d0a2cb1 100644
--- a/shell/src/main/scala/org/apache/clerezza/shell/ShellPermission.scala
+++ b/shell/src/main/scala/org/apache/clerezza/shell/ShellPermission.scala
@@ -22,18 +22,18 @@ package org.apache.clerezza.shell
import java.security.Permission
class ShellPermission(t: String, a: String) extends Permission(t) {
- def this() = this(null,null)
+ def this() = this(null,null)
- def getActions = ""
+ def getActions = ""
- def implies(p: Permission) = {
- p match {
- case sp: ShellPermission => true
- case _ => false
- }
- }
+ def implies(p: Permission) = {
+ p match {
+ case sp: ShellPermission => true
+ case _ => false
+ }
+ }
- override def hashCode = 67823
+ override def hashCode = 67823
- override def equals(other: Any) = other.isInstanceOf[ShellPermission]
+ override def equals(other: Any) = other.isInstanceOf[ShellPermission]
}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/site/src/main/scala/Activator.scala
----------------------------------------------------------------------
diff --git a/site/src/main/scala/Activator.scala b/site/src/main/scala/Activator.scala
index 41260dc..7b9224b 100644
--- a/site/src/main/scala/Activator.scala
+++ b/site/src/main/scala/Activator.scala
@@ -16,76 +16,76 @@ import java.io.{FileOutputStream, FileInputStream, File}
*/
class Activator extends BundleActivator {
- var renderletRegistration,
- titledContentRenderletRegistration,
- globalMenuRenderletRegistration: ServiceRegistration[TypeRenderlet] = null
- var graphListenerOption: Option[GraphListener] = null
+ var renderletRegistration,
+ titledContentRenderletRegistration,
+ globalMenuRenderletRegistration: ServiceRegistration[TypeRenderlet] = null
+ var graphListenerOption: Option[GraphListener] = null
- /**
- * called when the bundle is started, this method initializes the provided service
- */
- def start(context: BundleContext) {
- val servicesDsl = new ServicesDsl(context)
- import servicesDsl._
+ /**
+ * called when the bundle is started, this method initializes the provided service
+ */
+ def start(context: BundleContext) {
+ val servicesDsl = new ServicesDsl(context)
+ import servicesDsl._
- val renderlet = new HeadedPageRenderlet
- renderletRegistration = context.registerService(classOf[TypeRenderlet],
- renderlet, null)
- titledContentRenderletRegistration = context.registerService(classOf[TypeRenderlet],
- new TitledContentRenderlet, null)
- globalMenuRenderletRegistration = context.registerService(classOf[TypeRenderlet],
- new GlobalMenuRenderlet, null)
- context.installBundle("mvn:org.apache.clerezza/rdf.stable.serializer").start();
- context.installBundle("mvn:org.apache.clerezza/tools.offline").start();
- val path = {
- val bl = context.getBundle.getLocation
- bl.substring(bl.indexOf(':')+1)
- }
- val graphFile = new File(new File(path), "graph.nt");
- doWith {
- (tcManager: TcManager, parser: Parser) => {
- val contentGraph = tcManager.getMGraph(Constants.CONTENT_GRAPH_URI)
- val fileGraph = parser.parse(new FileInputStream(graphFile), SupportedFormat.N_TRIPLE)
- if (contentGraph.size > fileGraph.size) {
- println("content graph if bigger than the graph from file, not replacing with the content from file and not " +
- "writing any data to the file, you should manually either write the content graph to the file or clear " +
- "the content graph. Restart this bundle after resolving the issue.")
- graphListenerOption = None
- } else {
- contentGraph.clear
- contentGraph.addAll(fileGraph)
- println("the content graph has been replaced with "+graphFile)
- object graphListener extends GraphListener {
- val serializer = $[Serializer]
- override def graphChanged(events: java.util.List[GraphEvent]) {
- serializer.serialize(new FileOutputStream(graphFile), contentGraph,SupportedFormat.N_TRIPLE)
- }
- }
- contentGraph.addGraphListener(graphListener, new FilterTriple(null, null, null), 2000)
- graphListenerOption = Some(graphListener)
- println("A GraphListener has been added that writes changes to the content graph to graph.nt")
- }
- }
- }
- }
+ val renderlet = new HeadedPageRenderlet
+ renderletRegistration = context.registerService(classOf[TypeRenderlet],
+ renderlet, null)
+ titledContentRenderletRegistration = context.registerService(classOf[TypeRenderlet],
+ new TitledContentRenderlet, null)
+ globalMenuRenderletRegistration = context.registerService(classOf[TypeRenderlet],
+ new GlobalMenuRenderlet, null)
+ context.installBundle("mvn:org.apache.clerezza/rdf.stable.serializer").start();
+ context.installBundle("mvn:org.apache.clerezza/tools.offline").start();
+ val path = {
+ val bl = context.getBundle.getLocation
+ bl.substring(bl.indexOf(':')+1)
+ }
+ val graphFile = new File(new File(path), "graph.nt");
+ doWith {
+ (tcManager: TcManager, parser: Parser) => {
+ val contentGraph = tcManager.getMGraph(Constants.CONTENT_GRAPH_URI)
+ val fileGraph = parser.parse(new FileInputStream(graphFile), SupportedFormat.N_TRIPLE)
+ if (contentGraph.size > fileGraph.size) {
+ println("content graph if bigger than the graph from file, not replacing with the content from file and not " +
+ "writing any data to the file, you should manually either write the content graph to the file or clear " +
+ "the content graph. Restart this bundle after resolving the issue.")
+ graphListenerOption = None
+ } else {
+ contentGraph.clear
+ contentGraph.addAll(fileGraph)
+ println("the content graph has been replaced with "+graphFile)
+ object graphListener extends GraphListener {
+ val serializer = $[Serializer]
+ override def graphChanged(events: java.util.List[GraphEvent]) {
+ serializer.serialize(new FileOutputStream(graphFile), contentGraph,SupportedFormat.N_TRIPLE)
+ }
+ }
+ contentGraph.addGraphListener(graphListener, new FilterTriple(null, null, null), 2000)
+ graphListenerOption = Some(graphListener)
+ println("A GraphListener has been added that writes changes to the content graph to graph.nt")
+ }
+ }
+ }
+ }
- /**
- * called when the bundle is stopped, this method unregisters the provided service
- */
- def stop(context: BundleContext) {
- renderletRegistration.unregister()
- titledContentRenderletRegistration.unregister()
- globalMenuRenderletRegistration.unregister()
- val servicesDsl = new ServicesDsl(context)
- import servicesDsl._
- val tcManager = $[TcManager]
- val contentGraph = tcManager.getMGraph(Constants.CONTENT_GRAPH_URI)
- graphListenerOption match {
- case Some(l) => contentGraph.removeGraphListener(l)
- case None => ;
- }
- println("bye")
- }
+ /**
+ * called when the bundle is stopped, this method unregisters the provided service
+ */
+ def stop(context: BundleContext) {
+ renderletRegistration.unregister()
+ titledContentRenderletRegistration.unregister()
+ globalMenuRenderletRegistration.unregister()
+ val servicesDsl = new ServicesDsl(context)
+ import servicesDsl._
+ val tcManager = $[TcManager]
+ val contentGraph = tcManager.getMGraph(Constants.CONTENT_GRAPH_URI)
+ graphListenerOption match {
+ case Some(l) => contentGraph.removeGraphListener(l)
+ case None => ;
+ }
+ println("bye")
+ }
}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/site/src/main/scala/GlobalMenuRenderlet.scala
----------------------------------------------------------------------
diff --git a/site/src/main/scala/GlobalMenuRenderlet.scala b/site/src/main/scala/GlobalMenuRenderlet.scala
index 6c5493c..7f6e26b 100644
--- a/site/src/main/scala/GlobalMenuRenderlet.scala
+++ b/site/src/main/scala/GlobalMenuRenderlet.scala
@@ -16,20 +16,20 @@ import org.apache.clerezza.rdf.ontologies.DC
*/
class GlobalMenuRenderlet extends SRenderlet {
- val getRdfType = RDFS.Resource
+ val getRdfType = RDFS.Resource
- override def getModePattern = "menu"
+ override def getModePattern = "menu"
- override def renderedPage(arguments: XmlResult.Arguments) = {
- new XmlResult(arguments) {
- def menuLink(href: String, label: String) =
- if ((res*).endsWith(href) || (res*).endsWith(href+"index")) {
- <a href={href} class="active">{label}</a>
- } else {
- <a href={href}>{label}</a>
- }
- override def content = {
- def menu(s: Any) = new UriRef("http://clerezza.org/2009/11/global-menu#"+s)
+ override def renderedPage(arguments: XmlResult.Arguments) = {
+ new XmlResult(arguments) {
+ def menuLink(href: String, label: String) =
+ if ((res*).endsWith(href) || (res*).endsWith(href+"index")) {
+ <a href={href} class="active">{label}</a>
+ } else {
+ <a href={href}>{label}</a>
+ }
+ override def content = {
+ def menu(s: Any) = new UriRef("http://clerezza.org/2009/11/global-menu#"+s)
def rdfs(s: Any) = new UriRef("http://www.w3.org/2000/01/rdf-schema#"+s)
def platform(s: Any) = new UriRef("http://clerezza.org/2009/08/platform#"+s)
def dct(s: Any) = new UriRef("http://purl.org/dc/terms/"+s)
@@ -38,38 +38,38 @@ resultDocModifier.addScriptReference("/style/scripts/login.js");
<div class="column nav">
- <ul>
-
+ <ul>
+
- {for (menuItem <- res/menu("globalMenu")!!) yield
- <li class="top-nav-entry"><div class="title">
- {
- if ((menuItem/menu("path")).length > 0) {
- <a href={menuItem/menu("path")*}>{(menuItem/rdfs("label")*)}</a>
- } else {
- <a href="#" onclick="return false">{(menuItem/rdfs("label")*)}</a>
- }
- }
- </div>
- {
- ifx ((menuItem/menu("children")).length > 0) {
- <div>
- <ul class="nav-entries">
- {
- for (childMenuItem <- menuItem/menu("children")!!) yield {
- <li><a href={childMenuItem/menu("path")*}>{childMenuItem/rdfs("label")*}</a><span>{childMenuItem/dct("description")*}</span></li>
- }
- }
- </ul>
- </div>
- }
- }
- </li>
- }
- </ul>
+ {for (menuItem <- res/menu("globalMenu")!!) yield
+ <li class="top-nav-entry"><div class="title">
+ {
+ if ((menuItem/menu("path")).length > 0) {
+ <a href={menuItem/menu("path")*}>{(menuItem/rdfs("label")*)}</a>
+ } else {
+ <a href="#" onclick="return false">{(menuItem/rdfs("label")*)}</a>
+ }
+ }
+ </div>
+ {
+ ifx ((menuItem/menu("children")).length > 0) {
+ <div>
+ <ul class="nav-entries">
+ {
+ for (childMenuItem <- menuItem/menu("children")!!) yield {
+ <li><a href={childMenuItem/menu("path")*}>{childMenuItem/rdfs("label")*}</a><span>{childMenuItem/dct("description")*}</span></li>
+ }
+ }
+ </ul>
+ </div>
+ }
+ }
+ </li>
+ }
+ </ul>
</div>
- }
- }
- }
+ }
+ }
+ }
}
[9/9] git commit: CLEREZZA-435: repaced tabs with spaces in scala
files
Posted by re...@apache.org.
CLEREZZA-435: repaced tabs with spaces in scala files
Project: http://git-wip-us.apache.org/repos/asf/clerezza/repo
Commit: http://git-wip-us.apache.org/repos/asf/clerezza/commit/35448624
Tree: http://git-wip-us.apache.org/repos/asf/clerezza/tree/35448624
Diff: http://git-wip-us.apache.org/repos/asf/clerezza/diff/35448624
Branch: refs/heads/master
Commit: 35448624b85f7bfaac87a7db202d2d68a555cbcc
Parents: a7d9d0f
Author: retobg <re...@apache.org>
Authored: Wed Dec 4 16:20:01 2013 +0100
Committer: retobg <re...@apache.org>
Committed: Wed Dec 4 16:20:01 2013 +0100
----------------------------------------------------------------------
.../src/main/scala/Activator.scala | 4 +-
.../src/main/scala/HelloWorld.scala | 20 +-
.../main/scala/HelloWorldMessageRenderlet.scala | 26 +-
.../src/main/scala/Ontology.scala | 8 +-
.../clerezza/bundledevtool/BundleRoot.scala | 502 +++----
.../apache/clerezza/bundledevtool/DevDsl.scala | 116 +-
.../bundledevtool/DevShellCustomizer.scala | 10 +-
.../PermissionGrantingPathNode.scala | 8 +-
.../UnavailableSkeletonException.scala | 2 +-
.../src/main/scala/sbt/ErrorHandling.scala | 30 +-
bundledevtool/src/main/scala/sbt/io/Hash.scala | 130 +-
bundledevtool/src/main/scala/sbt/io/IO.scala | 1138 +++++++--------
bundledevtool/src/main/scala/sbt/io/IPC.scala | 116 +-
.../src/main/scala/sbt/io/NameFilter.scala | 60 +-
bundledevtool/src/main/scala/sbt/io/Pack.scala | 120 +-
bundledevtool/src/main/scala/sbt/io/Path.scala | 704 +++++-----
.../src/main/scala/sbt/io/PathMapper.scala | 84 +-
.../src/main/scala/sbt/io/Resources.scala | 98 +-
.../scala/sbt/io/SourceModificationWatch.scala | 62 +-
bundledevtool/src/main/scala/sbt/io/Using.scala | 130 +-
.../webfragements/WebFragmentRunner.scala | 64 +-
.../osgi/services/ActivationHelper.scala | 142 +-
.../clerezza/osgi/services/ServicesDsl.scala | 134 +-
.../AcpPermissionDescriptionsProvider.scala | 58 +-
.../accountcontrolpanel/MenuItemProvider.scala | 48 +-
.../accountcontrolpanel/ProfilePanel.scala | 794 +++++------
.../accountcontrolpanel/SettingsPanel.scala | 1026 +++++++-------
.../html/ContactConfirmRenderlet.scala | 136 +-
.../accountcontrolpanel/html/PersonBox.scala | 56 +-
.../accountcontrolpanel/html/ProfilePanel.scala | 514 +++----
.../html/RenderingUtility.scala | 92 +-
.../html/SettingsPanel.scala | 210 +--
.../accountcontrolpanel/permissions.scala | 66 +-
.../default404/DefaultPageNotFoundService.scala | 48 +-
.../content/fsadaptor/BundleFsLoader.scala | 472 +++----
.../content/fsadaptor/DirectoryOverlay.scala | 88 +-
.../platform/content/fsadaptor/Logger.scala | 4 +-
.../content/fsadaptor/PathNode2MGraph.scala | 192 +--
.../renderlets/HtmlInfoDicobitRDFaNaked.scala | 16 +-
.../renderlets/OrderedContentRDFaNaked.scala | 16 +-
.../renderlets/TitledContentRDFaNaked.scala | 16 +-
.../graphnodeprovider/GraphNodeProvider.scala | 350 ++---
.../logging/initializer/Activator.scala | 90 +-
.../foafssl/auth/FoafSslAuthentication.scala | 16 +-
.../clerezza/foafssl/auth/WebIDClaim.scala | 294 ++--
.../clerezza/foafssl/auth/X509Claim.scala | 22 +-
.../apache/clerezza/foafssl/ssl/Activator.scala | 90 +-
.../ssl/X509TrustManagerWrapperService.scala | 50 +-
.../clerezza/foafssl/test/WebIDTester.scala | 1306 +++++++++---------
.../foafssl/test/pages/WebIDClaimPg.scala | 208 +--
.../platform/shellcustomizer/PlatformDsl.scala | 18 +-
.../src/main/scala/Activator.scala | 10 +-
.../src/main/scala/CollectionHeader.scala | 4 +-
.../src/main/scala/GlobalMenuRenderlet.scala | 86 +-
.../src/main/scala/HeadedPageRenderlet.scala | 210 +--
.../src/main/scala/RdfListRenderlet.scala | 30 +-
.../src/main/scala/Activator.scala | 150 +-
.../src/main/scala/Ontology.scala | 18 +-
.../scala/RenderletDescriptionRenderlet.scala | 34 +-
.../typerendering/scala/AbstractRenderlet.scala | 62 +-
.../typerendering/scala/PageRenderlet.scala | 32 +-
.../typerendering/scala/RenderedPage.scala | 230 +--
.../typerendering/scala/SRenderlet.scala | 58 +-
.../typerendering/scala/XmlResult.scala | 226 +--
.../UserGraphAcessPermissionProvider.scala | 28 +-
.../platform/users/WebIdGraphsService.scala | 328 ++---
.../clerezza/platform/users/WebIdInfo.scala | 52 +-
.../rdf/scala/utils/CollectedIter.scala | 114 +-
.../clerezza/rdf/scala/utils/EzLiteral.scala | 34 +-
.../clerezza/rdf/scala/utils/EzMGraph.scala | 76 +-
.../clerezza/rdf/scala/utils/NameSpace.scala | 16 +-
.../clerezza/rdf/scala/utils/Preamble.scala | 64 +-
.../rdf/scala/utils/RichGraphNode.scala | 386 +++---
.../clerezza/rdf/scala/utils/EzMGraphTest.scala | 224 +--
.../rdf/scala/utils/RichGraphNodeTest.scala | 268 ++--
.../rdf/scala/utils/TypeConversionTest.scala | 70 +-
rdf.storage.web/src/main/scala/WebProxy.scala | 444 +++---
.../scripting/BundleContextScalaCompiler.scala | 50 +-
.../BundleContextScalaInterpreter.scala | 22 +-
.../clerezza/scala/scripting/BundleFS.scala | 308 ++---
.../scala/scripting/CompilerService.scala | 2 +-
.../scala/scripting/InterpreterFactory.scala | 28 +-
.../scala/scripting/ScriptEngineFactory.scala | 474 +++----
.../scala/scripting/TrackingCompiler.scala | 150 +-
.../scala/scripting/util/FileWrapper.scala | 26 +-
.../util/GenericFileWrapperTrait.scala | 112 +-
.../scripting/util/SplittingDirectory.scala | 82 +-
.../util/VirtualDirectoryWrapper.scala | 108 +-
.../clerezza/scala/scripting/util/Wrapper.scala | 4 +-
.../scala/tests/CompilerServiceTest.scala | 324 ++---
.../scala/tests/ScriptEngineFactoryTest.scala | 294 ++--
.../felixshellcommand/FelixShellCommand.scala | 42 +-
.../apache/clerezza/shell/ConsoleShell.scala | 96 +-
.../shell/InterruptibleInputStream.scala | 76 +-
.../scala/org/apache/clerezza/shell/Shell.scala | 6 +-
.../apache/clerezza/shell/ShellCommand.scala | 12 +-
.../apache/clerezza/shell/ShellCustomizer.scala | 18 +-
.../apache/clerezza/shell/ShellPermission.scala | 20 +-
site/src/main/scala/Activator.scala | 134 +-
site/src/main/scala/GlobalMenuRenderlet.scala | 86 +-
site/src/main/scala/HeadedPageRenderlet.scala | 196 +--
site/src/main/scala/Ontology.scala | 8 +-
.../src/main/scala/TitledContentRenderlet.scala | 238 ++--
103 files changed, 8087 insertions(+), 8087 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/bundledevtool/src/main/resources/org/apache/clerezza/bundledevtool/skeletons/scala_with_activator/src/main/scala/Activator.scala
----------------------------------------------------------------------
diff --git a/bundledevtool/src/main/resources/org/apache/clerezza/bundledevtool/skeletons/scala_with_activator/src/main/scala/Activator.scala b/bundledevtool/src/main/resources/org/apache/clerezza/bundledevtool/skeletons/scala_with_activator/src/main/scala/Activator.scala
index 6390a35..3e9a4be 100644
--- a/bundledevtool/src/main/resources/org/apache/clerezza/bundledevtool/skeletons/scala_with_activator/src/main/scala/Activator.scala
+++ b/bundledevtool/src/main/resources/org/apache/clerezza/bundledevtool/skeletons/scala_with_activator/src/main/scala/Activator.scala
@@ -27,6 +27,6 @@ import org.apache.clerezza.osgi.services.ActivationHelper
* Activator for a bundle using Apache Clerezza.
*/
class Activator extends ActivationHelper {
- registerRootResource(new HelloWorld(context))
- registerRenderlet(new HelloWorldMessageRenderlet)
+ registerRootResource(new HelloWorld(context))
+ registerRenderlet(new HelloWorldMessageRenderlet)
}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/bundledevtool/src/main/resources/org/apache/clerezza/bundledevtool/skeletons/scala_with_activator/src/main/scala/HelloWorld.scala
----------------------------------------------------------------------
diff --git a/bundledevtool/src/main/resources/org/apache/clerezza/bundledevtool/skeletons/scala_with_activator/src/main/scala/HelloWorld.scala b/bundledevtool/src/main/resources/org/apache/clerezza/bundledevtool/skeletons/scala_with_activator/src/main/scala/HelloWorld.scala
index 3980bbc..e45976a 100644
--- a/bundledevtool/src/main/resources/org/apache/clerezza/bundledevtool/skeletons/scala_with_activator/src/main/scala/HelloWorld.scala
+++ b/bundledevtool/src/main/resources/org/apache/clerezza/bundledevtool/skeletons/scala_with_activator/src/main/scala/HelloWorld.scala
@@ -35,15 +35,15 @@ import org.apache.clerezza.platform.graphprovider.content.ContentGraphProvider
*/
@Path("hello-world")
class HelloWorld(context: BundleContext) {
- val servicesDsl = new ServicesDsl(context)
- import servicesDsl._
- @GET def get() = {
- val resultMGraph = new SimpleMGraph();
- val graphNode = new GraphNode(new BNode(), resultMGraph);
- graphNode.addProperty(RDF.`type` , Ontology.HelloWordMessageType);
- val cgp: ContentGraphProvider = $[ContentGraphProvider]
- graphNode.addPropertyValue(DC.description,"Hello world of "+cgp.getContentGraph.size);
- graphNode;
+ val servicesDsl = new ServicesDsl(context)
+ import servicesDsl._
+ @GET def get() = {
+ val resultMGraph = new SimpleMGraph();
+ val graphNode = new GraphNode(new BNode(), resultMGraph);
+ graphNode.addProperty(RDF.`type` , Ontology.HelloWordMessageType);
+ val cgp: ContentGraphProvider = $[ContentGraphProvider]
+ graphNode.addPropertyValue(DC.description,"Hello world of "+cgp.getContentGraph.size);
+ graphNode;
- }
+ }
}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/bundledevtool/src/main/resources/org/apache/clerezza/bundledevtool/skeletons/scala_with_activator/src/main/scala/HelloWorldMessageRenderlet.scala
----------------------------------------------------------------------
diff --git a/bundledevtool/src/main/resources/org/apache/clerezza/bundledevtool/skeletons/scala_with_activator/src/main/scala/HelloWorldMessageRenderlet.scala b/bundledevtool/src/main/resources/org/apache/clerezza/bundledevtool/skeletons/scala_with_activator/src/main/scala/HelloWorldMessageRenderlet.scala
index 04da6de..6e41732 100644
--- a/bundledevtool/src/main/resources/org/apache/clerezza/bundledevtool/skeletons/scala_with_activator/src/main/scala/HelloWorldMessageRenderlet.scala
+++ b/bundledevtool/src/main/resources/org/apache/clerezza/bundledevtool/skeletons/scala_with_activator/src/main/scala/HelloWorldMessageRenderlet.scala
@@ -37,20 +37,20 @@ import org.apache.clerezza.rdf.ontologies.DC
*/
class HelloWorldMessageRenderlet extends SRenderlet {
- val getRdfType = Ontology.HelloWordMessageType
+ val getRdfType = Ontology.HelloWordMessageType
- override def getModePattern = "naked"
+ override def getModePattern = "naked"
- override def renderedPage(arguments: XmlResult.Arguments) = {
- new XmlResult(arguments) {
- override def content = {
- resultDocModifier.addStyleSheet("/styles/hello-world/style.css")
- <div xmlns="http://www.w3.org/1999/xhtml" id="tx-content">
- <h2>A Message</h2>
- <div class="message">{res/DC.description*}</div>
- </div>
- }
- }
- }
+ override def renderedPage(arguments: XmlResult.Arguments) = {
+ new XmlResult(arguments) {
+ override def content = {
+ resultDocModifier.addStyleSheet("/styles/hello-world/style.css")
+ <div xmlns="http://www.w3.org/1999/xhtml" id="tx-content">
+ <h2>A Message</h2>
+ <div class="message">{res/DC.description*}</div>
+ </div>
+ }
+ }
+ }
}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/bundledevtool/src/main/resources/org/apache/clerezza/bundledevtool/skeletons/scala_with_activator/src/main/scala/Ontology.scala
----------------------------------------------------------------------
diff --git a/bundledevtool/src/main/resources/org/apache/clerezza/bundledevtool/skeletons/scala_with_activator/src/main/scala/Ontology.scala b/bundledevtool/src/main/resources/org/apache/clerezza/bundledevtool/skeletons/scala_with_activator/src/main/scala/Ontology.scala
index 924df22..c831e8e 100644
--- a/bundledevtool/src/main/resources/org/apache/clerezza/bundledevtool/skeletons/scala_with_activator/src/main/scala/Ontology.scala
+++ b/bundledevtool/src/main/resources/org/apache/clerezza/bundledevtool/skeletons/scala_with_activator/src/main/scala/Ontology.scala
@@ -25,9 +25,9 @@ import org.apache.clerezza.rdf.core.UriRef
object Ontology {
- /**
- * The uri for the RDF type of HelloWordMessage
- */
- val HelloWordMessageType = new UriRef("http://example.org/skeleton#HelloWordMessage")
+ /**
+ * The uri for the RDF type of HelloWordMessage
+ */
+ val HelloWordMessageType = new UriRef("http://example.org/skeleton#HelloWordMessage")
}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/bundledevtool/src/main/scala/org/apache/clerezza/bundledevtool/BundleRoot.scala
----------------------------------------------------------------------
diff --git a/bundledevtool/src/main/scala/org/apache/clerezza/bundledevtool/BundleRoot.scala b/bundledevtool/src/main/scala/org/apache/clerezza/bundledevtool/BundleRoot.scala
index 0186850..51cb6f8 100644
--- a/bundledevtool/src/main/scala/org/apache/clerezza/bundledevtool/BundleRoot.scala
+++ b/bundledevtool/src/main/scala/org/apache/clerezza/bundledevtool/BundleRoot.scala
@@ -48,261 +48,261 @@ import org.wymiwyg.commons.util.dirbrowser.{PathNode, FilePathNode}
*/
class BundleRoot {
- private var compilerService: CompilerService = null
- private var packageAdmin: PackageAdmin = null
-
- private var bundleContext: BundleContext = null
-
- private val skeletonsPath = "org/apache/clerezza/bundledevtool/skeletons"
-
- val sourceBundles = mutable.ListBuffer[SourceBundle]()
-
- protected def activate(c: ComponentContext) {
- this.bundleContext = c.getBundleContext
- sourceBundles.clear()
- for (bundle <- bundleContext.getBundles) {
- val location = bundle.getLocation
- if (location.startsWith(BundleRoot.sourceBundleUriPrefix)) {
- val dir = new File(location.substring(
- BundleRoot.sourceBundleUriPrefix.length))
- //TODO encode fileFastUpdate in location
- val sourceBundle = new SourceBundle(dir, bundle, true)
- sourceBundle.start()
- sourceBundles += sourceBundle
- }
- }
- }
-
- protected def deactivate(c: ComponentContext) {
- for (sb <- sourceBundles) sb.stop()
- }
-
- /**
- * adds a SourceBundle for the sources in the specified dir
- */
- def addSourceBundle(dir: File, fileFastUpdate: Boolean) = {
- val sourceBundle = new SourceBundle(dir, fileFastUpdate)
- sourceBundle.start()
- sourceBundles += sourceBundle
- sourceBundle
- }
-
-
- /**
- * list of the available skletons
- */
- def availableSkeletons: Seq[Symbol] = {
- val skeletonsNode = new BundlePathNode(bundleContext.getBundle, skeletonsPath)
- for (name <- skeletonsNode.list) yield {
- Symbol(name.substring(1,name.length-1))
- }
- }
-
- /**
- * Creates and adds a new SourceBundle from a skeleton, no existing file is
- * replaced
- */
- def createSourceBundle(skeleton: Symbol, dir: File) = {
- dir.mkdirs
- val skeletonsNode = new BundlePathNode(bundleContext.getBundle, skeletonsPath)
- val skeletonNode = skeletonsNode.getSubPath(skeleton.name)
- if (!skeletonNode.exists) {
- throw new UnavailableSkeletonException(skeleton, availableSkeletons)
- }
- def processFile(p: PathNode, f: File) {
- if (!f.exists) {
- val in = scala.io.Source.fromInputStream(p.getInputStream)
- val out = new java.io.PrintWriter(f)
- try { in.getLines().foreach(out.println(_)) }
- finally { out.close }
- }
- }
- def processDir(p: PathNode, f: File) {
- f.mkdir()
- for (subPathString <- p.list()) {
- val subPathNode: PathNode = p.getSubPath(subPathString)
- val subFile: File = new File(f, subPathString)
- if (subPathNode.isDirectory) {
- processDir(subPathNode, subFile)
- } else {
- processFile(subPathNode, subFile)
- }
- }
- }
-
- processDir(skeletonNode, dir)
- addSourceBundle(dir, true)
- }
-
- def bindCompilerService(cs: CompilerService) {
- compilerService = cs;
- }
-
- def unbindCompilerService(cs: CompilerService) {
- compilerService = null;
- }
-
- def bindPackageAdmin(pa: PackageAdmin) {
- packageAdmin = pa
- }
-
- def unbindPackageAdmin(pa: PackageAdmin) {
- packageAdmin = null
- }
-
- class SourceBundle(dir: File, existingBundle: Bundle, fileFastUpdate: Boolean) extends DaemonActor {
-
- def this(dir: File, fileFastUpdate: Boolean) {
- this(dir, null, fileFastUpdate)
- }
-
- var stopped = false
- var logger = LoggerFactory.getLogger(classOf[SourceBundle])
-
- val sourcePath = Path.fromFile(new File(dir,"src"))
- var watchState = WatchState.empty
- var bundle: Bundle = existingBundle
- if (fileFastUpdate) {
- val pathNode = new PermissionGrantingPathNode(new FilePathNode(new File(dir,"src/main/resources/CLEREZZA-INF/web-resources/")))
- val registration = bundleContext.registerService(Array(classOf[PathNode].getName), pathNode, null: java.util.Dictionary[String, _])
- //println("registered "+classOf[PathNode].getName+": "+registration)
- }
-
- def getFilesAsCharArrays(file: File): List[Array[Char]] = {
- logger.debug("getting sources in "+file)
- var result: List[Array[Char]] = Nil
- if (file.isDirectory) {
- val children = file.listFiles
- import scala.collection.JavaConversions._
- for(child <- children) {
- if (!child.getName.startsWith(".")) {
- result = getFilesAsCharArrays(child) ::: result
- }
- }
- } else {
- if (file.getName.endsWith(".scala")) {
- val in = Source.fromFile(file, "utf-8")
- val stream = in.toStream
- result = stream.toArray :: result
- }
- }
- result
- }
-
- private[this] def updateBundle() {
- logger.info("updating source bundle with root "+dir)
-
- val tinyBundle: TinyBundle = newBundle()
-
- def compileDir(sourceDir: File): Option[String] = {
-
- val charArrays = getFilesAsCharArrays(sourceDir)
- logger.debug("compiling "+charArrays.size+" files")
-
- val vdPathPrefix = "(memory)"
- val virtualDirectory = new VirtualDirectory(vdPathPrefix, None)
- //val wrappedDirectory = VirtualDirectoryWrapper.wrap(virtualDirectory, outputListener)
-
- val writtenClasses = compilerService.compileToDir(charArrays, virtualDirectory)
- logger.debug("virtualDirectory "+virtualDirectory.size)
- var potentialActivator: Option[String] = None
- for (writtenClass <- writtenClasses) {
- val fullPath = writtenClass.path
- val path = fullPath.substring(vdPathPrefix.length+1)
- if (path.endsWith("Activator.class")) {
- potentialActivator = Some(path.substring(0, path.lastIndexOf('.')).replace('/', '.'))
- }
- tinyBundle.add(path, new ByteArrayInputStream(writtenClass.toByteArray))
- }
- potentialActivator
- }
-
- def copyResource(resourcesDir: File) {
- def copyResource(resourcesDir: File, prefix: String) {
- val children = resourcesDir.listFiles
- import scala.collection.JavaConversions._
- for(child <- children) {
- val childName = child.getName
- if (!childName.startsWith(".")) {
- if (child.isDirectory) {
- copyResource(child, prefix+childName+"/")
- } else {
- tinyBundle.add(prefix+childName, new FileInputStream(child))
- }
- }
- }
- }
- copyResource(resourcesDir, "")
- }
-
- val symName = dir.getPath.substring(1).replace(File.separatorChar, '.')
-
- tinyBundle.set("Bundle-SymbolicName", symName)
-
- val scalaSourceDir = new File(dir, "src/main/scala")
-
- val potentialActivator = if (scalaSourceDir.exists) {
- compileDir(scalaSourceDir)
- } else {
- logger.debug("No source dir "+scalaSourceDir)
- None
- }
- val resourcesDir = new File(dir, "src/main/resources")
- if (resourcesDir.exists) {
- copyResource(resourcesDir)
- } else {
- logger.debug("No resources dir "+resourcesDir)
- }
- val serviceComponentsFile = new File(resourcesDir, "OSGI-INF/serviceComponents.xml")
- if (serviceComponentsFile.exists) {
- tinyBundle.set("Service-Component", "OSGI-INF/serviceComponents.xml")
- tinyBundle.set(Constants.EXPORT_PACKAGE, "!OSGI-INF, *" )
- }
- potentialActivator match {
- case Some(s) => tinyBundle.set("Bundle-Activator", s)
- case _ => ;
- }
- tinyBundle.set(Constants.IMPORT_PACKAGE, "*" );
- val in = tinyBundle.build(
- withBnd()
- )
-
-
- if (bundle == null) {
- bundle = bundleContext.installBundle(BundleRoot.sourceBundleUriPrefix+dir.toString, in)
- bundle.start()
- } else {
- bundle.update(in)
- }
-
- }
-
- def act() {
- while (!stopped) {
- logger.debug("wathcing "+dir)
- val (triggered, newWatchState) =
- SourceModificationWatch.watch(sourcePath**(-HiddenFileFilter), 1, watchState)(stopped)
- logger.debug("watching got "+triggered+", "+newWatchState)
- if (!stopped) {
- try {
- updateBundle()
- } catch {
- case e => logger.warn("Exception compiling", e)
- }
- watchState = newWatchState
- }
- }
- }
-
- def stop() {
- stopped = true
- }
- }
+ private var compilerService: CompilerService = null
+ private var packageAdmin: PackageAdmin = null
+
+ private var bundleContext: BundleContext = null
+
+ private val skeletonsPath = "org/apache/clerezza/bundledevtool/skeletons"
+
+ val sourceBundles = mutable.ListBuffer[SourceBundle]()
+
+ protected def activate(c: ComponentContext) {
+ this.bundleContext = c.getBundleContext
+ sourceBundles.clear()
+ for (bundle <- bundleContext.getBundles) {
+ val location = bundle.getLocation
+ if (location.startsWith(BundleRoot.sourceBundleUriPrefix)) {
+ val dir = new File(location.substring(
+ BundleRoot.sourceBundleUriPrefix.length))
+ //TODO encode fileFastUpdate in location
+ val sourceBundle = new SourceBundle(dir, bundle, true)
+ sourceBundle.start()
+ sourceBundles += sourceBundle
+ }
+ }
+ }
+
+ protected def deactivate(c: ComponentContext) {
+ for (sb <- sourceBundles) sb.stop()
+ }
+
+ /**
+ * adds a SourceBundle for the sources in the specified dir
+ */
+ def addSourceBundle(dir: File, fileFastUpdate: Boolean) = {
+ val sourceBundle = new SourceBundle(dir, fileFastUpdate)
+ sourceBundle.start()
+ sourceBundles += sourceBundle
+ sourceBundle
+ }
+
+
+ /**
+ * list of the available skletons
+ */
+ def availableSkeletons: Seq[Symbol] = {
+ val skeletonsNode = new BundlePathNode(bundleContext.getBundle, skeletonsPath)
+ for (name <- skeletonsNode.list) yield {
+ Symbol(name.substring(1,name.length-1))
+ }
+ }
+
+ /**
+ * Creates and adds a new SourceBundle from a skeleton, no existing file is
+ * replaced
+ */
+ def createSourceBundle(skeleton: Symbol, dir: File) = {
+ dir.mkdirs
+ val skeletonsNode = new BundlePathNode(bundleContext.getBundle, skeletonsPath)
+ val skeletonNode = skeletonsNode.getSubPath(skeleton.name)
+ if (!skeletonNode.exists) {
+ throw new UnavailableSkeletonException(skeleton, availableSkeletons)
+ }
+ def processFile(p: PathNode, f: File) {
+ if (!f.exists) {
+ val in = scala.io.Source.fromInputStream(p.getInputStream)
+ val out = new java.io.PrintWriter(f)
+ try { in.getLines().foreach(out.println(_)) }
+ finally { out.close }
+ }
+ }
+ def processDir(p: PathNode, f: File) {
+ f.mkdir()
+ for (subPathString <- p.list()) {
+ val subPathNode: PathNode = p.getSubPath(subPathString)
+ val subFile: File = new File(f, subPathString)
+ if (subPathNode.isDirectory) {
+ processDir(subPathNode, subFile)
+ } else {
+ processFile(subPathNode, subFile)
+ }
+ }
+ }
+
+ processDir(skeletonNode, dir)
+ addSourceBundle(dir, true)
+ }
+
+ def bindCompilerService(cs: CompilerService) {
+ compilerService = cs;
+ }
+
+ def unbindCompilerService(cs: CompilerService) {
+ compilerService = null;
+ }
+
+ def bindPackageAdmin(pa: PackageAdmin) {
+ packageAdmin = pa
+ }
+
+ def unbindPackageAdmin(pa: PackageAdmin) {
+ packageAdmin = null
+ }
+
+ class SourceBundle(dir: File, existingBundle: Bundle, fileFastUpdate: Boolean) extends DaemonActor {
+
+ def this(dir: File, fileFastUpdate: Boolean) {
+ this(dir, null, fileFastUpdate)
+ }
+
+ var stopped = false
+ var logger = LoggerFactory.getLogger(classOf[SourceBundle])
+
+ val sourcePath = Path.fromFile(new File(dir,"src"))
+ var watchState = WatchState.empty
+ var bundle: Bundle = existingBundle
+ if (fileFastUpdate) {
+ val pathNode = new PermissionGrantingPathNode(new FilePathNode(new File(dir,"src/main/resources/CLEREZZA-INF/web-resources/")))
+ val registration = bundleContext.registerService(Array(classOf[PathNode].getName), pathNode, null: java.util.Dictionary[String, _])
+ //println("registered "+classOf[PathNode].getName+": "+registration)
+ }
+
+ def getFilesAsCharArrays(file: File): List[Array[Char]] = {
+ logger.debug("getting sources in "+file)
+ var result: List[Array[Char]] = Nil
+ if (file.isDirectory) {
+ val children = file.listFiles
+ import scala.collection.JavaConversions._
+ for(child <- children) {
+ if (!child.getName.startsWith(".")) {
+ result = getFilesAsCharArrays(child) ::: result
+ }
+ }
+ } else {
+ if (file.getName.endsWith(".scala")) {
+ val in = Source.fromFile(file, "utf-8")
+ val stream = in.toStream
+ result = stream.toArray :: result
+ }
+ }
+ result
+ }
+
+ private[this] def updateBundle() {
+ logger.info("updating source bundle with root "+dir)
+
+ val tinyBundle: TinyBundle = newBundle()
+
+ def compileDir(sourceDir: File): Option[String] = {
+
+ val charArrays = getFilesAsCharArrays(sourceDir)
+ logger.debug("compiling "+charArrays.size+" files")
+
+ val vdPathPrefix = "(memory)"
+ val virtualDirectory = new VirtualDirectory(vdPathPrefix, None)
+ //val wrappedDirectory = VirtualDirectoryWrapper.wrap(virtualDirectory, outputListener)
+
+ val writtenClasses = compilerService.compileToDir(charArrays, virtualDirectory)
+ logger.debug("virtualDirectory "+virtualDirectory.size)
+ var potentialActivator: Option[String] = None
+ for (writtenClass <- writtenClasses) {
+ val fullPath = writtenClass.path
+ val path = fullPath.substring(vdPathPrefix.length+1)
+ if (path.endsWith("Activator.class")) {
+ potentialActivator = Some(path.substring(0, path.lastIndexOf('.')).replace('/', '.'))
+ }
+ tinyBundle.add(path, new ByteArrayInputStream(writtenClass.toByteArray))
+ }
+ potentialActivator
+ }
+
+ def copyResource(resourcesDir: File) {
+ def copyResource(resourcesDir: File, prefix: String) {
+ val children = resourcesDir.listFiles
+ import scala.collection.JavaConversions._
+ for(child <- children) {
+ val childName = child.getName
+ if (!childName.startsWith(".")) {
+ if (child.isDirectory) {
+ copyResource(child, prefix+childName+"/")
+ } else {
+ tinyBundle.add(prefix+childName, new FileInputStream(child))
+ }
+ }
+ }
+ }
+ copyResource(resourcesDir, "")
+ }
+
+ val symName = dir.getPath.substring(1).replace(File.separatorChar, '.')
+
+ tinyBundle.set("Bundle-SymbolicName", symName)
+
+ val scalaSourceDir = new File(dir, "src/main/scala")
+
+ val potentialActivator = if (scalaSourceDir.exists) {
+ compileDir(scalaSourceDir)
+ } else {
+ logger.debug("No source dir "+scalaSourceDir)
+ None
+ }
+ val resourcesDir = new File(dir, "src/main/resources")
+ if (resourcesDir.exists) {
+ copyResource(resourcesDir)
+ } else {
+ logger.debug("No resources dir "+resourcesDir)
+ }
+ val serviceComponentsFile = new File(resourcesDir, "OSGI-INF/serviceComponents.xml")
+ if (serviceComponentsFile.exists) {
+ tinyBundle.set("Service-Component", "OSGI-INF/serviceComponents.xml")
+ tinyBundle.set(Constants.EXPORT_PACKAGE, "!OSGI-INF, *" )
+ }
+ potentialActivator match {
+ case Some(s) => tinyBundle.set("Bundle-Activator", s)
+ case _ => ;
+ }
+ tinyBundle.set(Constants.IMPORT_PACKAGE, "*" );
+ val in = tinyBundle.build(
+ withBnd()
+ )
+
+
+ if (bundle == null) {
+ bundle = bundleContext.installBundle(BundleRoot.sourceBundleUriPrefix+dir.toString, in)
+ bundle.start()
+ } else {
+ bundle.update(in)
+ }
+
+ }
+
+ def act() {
+ while (!stopped) {
+ logger.debug("wathcing "+dir)
+ val (triggered, newWatchState) =
+ SourceModificationWatch.watch(sourcePath**(-HiddenFileFilter), 1, watchState)(stopped)
+ logger.debug("watching got "+triggered+", "+newWatchState)
+ if (!stopped) {
+ try {
+ updateBundle()
+ } catch {
+ case e => logger.warn("Exception compiling", e)
+ }
+ watchState = newWatchState
+ }
+ }
+ }
+
+ def stop() {
+ stopped = true
+ }
+ }
}
object BundleRoot {
- val sourceBundleUriPrefix = "bundledevtool:"
+ val sourceBundleUriPrefix = "bundledevtool:"
}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/bundledevtool/src/main/scala/org/apache/clerezza/bundledevtool/DevDsl.scala
----------------------------------------------------------------------
diff --git a/bundledevtool/src/main/scala/org/apache/clerezza/bundledevtool/DevDsl.scala b/bundledevtool/src/main/scala/org/apache/clerezza/bundledevtool/DevDsl.scala
index 13df54c..f69eef7 100644
--- a/bundledevtool/src/main/scala/org/apache/clerezza/bundledevtool/DevDsl.scala
+++ b/bundledevtool/src/main/scala/org/apache/clerezza/bundledevtool/DevDsl.scala
@@ -28,66 +28,66 @@ import org.apache.clerezza.osgi.services.ServicesDsl
class DevDsl(outputStream: OutputStream, bundleContext: BundleContext) {
- sealed class FastUpdateMode;
+ sealed class FastUpdateMode;
- var fastUpdate = new FastUpdateMode;
- var noFastUpdate = new FastUpdateMode();
-
- case class LocationSpec(location: String, fastUpdateMode: FastUpdateMode) {
- def this(location: String) {
- this(location, fastUpdate)
- }
- }
-
- implicit def locationSpecBuilder(location: String) = new LocationSpec(location)
-
- object Dev {
- private val serviceDsl = new ServicesDsl(bundleContext)
- import serviceDsl._
- private lazy val out = new PrintWriter(new OutputStreamWriter(outputStream, "utf-8"), true)
+ var fastUpdate = new FastUpdateMode;
+ var noFastUpdate = new FastUpdateMode();
+
+ case class LocationSpec(location: String, fastUpdateMode: FastUpdateMode) {
+ def this(location: String) {
+ this(location, fastUpdate)
+ }
+ }
+
+ implicit def locationSpecBuilder(location: String) = new LocationSpec(location)
+
+ object Dev {
+ private val serviceDsl = new ServicesDsl(bundleContext)
+ import serviceDsl._
+ private lazy val out = new PrintWriter(new OutputStreamWriter(outputStream, "utf-8"), true)
- def listArchetypes() {
- out println "The following archetypes are available"
- for (a <- $[BundleRoot].availableSkeletons) {
- out println " - "+a
- }
- }
-
- def create(archetype: Symbol) = new Object() {
- def in(location: String): Unit = try {
- $[BundleRoot].createSourceBundle(archetype, new File(location))
- } catch {
- case u: UnavailableSkeletonException => {
- out println "FAILURE: no archetype "+archetype+" is available"
- listArchetypes()
- }
- }
- }
+ def listArchetypes() {
+ out println "The following archetypes are available"
+ for (a <- $[BundleRoot].availableSkeletons) {
+ out println " - "+a
+ }
+ }
+
+ def create(archetype: Symbol) = new Object() {
+ def in(location: String): Unit = try {
+ $[BundleRoot].createSourceBundle(archetype, new File(location))
+ } catch {
+ case u: UnavailableSkeletonException => {
+ out println "FAILURE: no archetype "+archetype+" is available"
+ listArchetypes()
+ }
+ }
+ }
- def load(locationSpec: LocationSpec) {
- val dir = new File(locationSpec.location)
- if (!dir.isDirectory) {
- out println "No directory "+locationSpec.location+" found"
- } else {
- $[BundleRoot].addSourceBundle(dir, locationSpec.fastUpdateMode == fastUpdate)
- }
- }
-
- def help() {
- out println "The Dev utitly can be used as follows:"
- out println "Dev listArchetypes"
- out println "\tlists the available archetypes"
- out println "Dev create <archetype-name> in \"/path/to/directory\""
- out println "\tCreates a new project in /path/to/directory using the specified archetype"
- out println "Dev load \"/path/to/directory\""
- out println "\tLoads the project in /path/to/directory"
- out println "Dev load \"/path/to/directory\""
- out println "\tLoads the project in /path/to/directory enabling fast-updating of static files"
- out println "Dev load LocationSpec(\"/path/to/directory\",fastUpdate|noFastUpdate)"
- out println "\tLoads the project in /path/to/directory enabling or diabling fast-updating of static files"
- }
-
- override def toString = "Run 'Dev help' for usage instructions"
- }
+ def load(locationSpec: LocationSpec) {
+ val dir = new File(locationSpec.location)
+ if (!dir.isDirectory) {
+ out println "No directory "+locationSpec.location+" found"
+ } else {
+ $[BundleRoot].addSourceBundle(dir, locationSpec.fastUpdateMode == fastUpdate)
+ }
+ }
+
+ def help() {
+ out println "The Dev utitly can be used as follows:"
+ out println "Dev listArchetypes"
+ out println "\tlists the available archetypes"
+ out println "Dev create <archetype-name> in \"/path/to/directory\""
+ out println "\tCreates a new project in /path/to/directory using the specified archetype"
+ out println "Dev load \"/path/to/directory\""
+ out println "\tLoads the project in /path/to/directory"
+ out println "Dev load \"/path/to/directory\""
+ out println "\tLoads the project in /path/to/directory enabling fast-updating of static files"
+ out println "Dev load LocationSpec(\"/path/to/directory\",fastUpdate|noFastUpdate)"
+ out println "\tLoads the project in /path/to/directory enabling or diabling fast-updating of static files"
+ }
+
+ override def toString = "Run 'Dev help' for usage instructions"
+ }
}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/bundledevtool/src/main/scala/org/apache/clerezza/bundledevtool/DevShellCustomizer.scala
----------------------------------------------------------------------
diff --git a/bundledevtool/src/main/scala/org/apache/clerezza/bundledevtool/DevShellCustomizer.scala b/bundledevtool/src/main/scala/org/apache/clerezza/bundledevtool/DevShellCustomizer.scala
index 05cc7f9..2acaa8c 100644
--- a/bundledevtool/src/main/scala/org/apache/clerezza/bundledevtool/DevShellCustomizer.scala
+++ b/bundledevtool/src/main/scala/org/apache/clerezza/bundledevtool/DevShellCustomizer.scala
@@ -22,9 +22,9 @@ import org.apache.clerezza.shell.Shell
import org.apache.clerezza.shell.ShellCustomizer
class DevShellCustomizer extends ShellCustomizer {
- def bindings(e: Shell.Environment): List[(String, String, Any)] = {
- List(("devDsl", classOf[DevDsl].getName, new DevDsl(e.out,
- e.componentContext.getBundleContext)))
- }
- def imports: List[String] = List("devDsl._")
+ def bindings(e: Shell.Environment): List[(String, String, Any)] = {
+ List(("devDsl", classOf[DevDsl].getName, new DevDsl(e.out,
+ e.componentContext.getBundleContext)))
+ }
+ def imports: List[String] = List("devDsl._")
}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/bundledevtool/src/main/scala/org/apache/clerezza/bundledevtool/PermissionGrantingPathNode.scala
----------------------------------------------------------------------
diff --git a/bundledevtool/src/main/scala/org/apache/clerezza/bundledevtool/PermissionGrantingPathNode.scala b/bundledevtool/src/main/scala/org/apache/clerezza/bundledevtool/PermissionGrantingPathNode.scala
index 3ddb9bc..aaaab91 100644
--- a/bundledevtool/src/main/scala/org/apache/clerezza/bundledevtool/PermissionGrantingPathNode.scala
+++ b/bundledevtool/src/main/scala/org/apache/clerezza/bundledevtool/PermissionGrantingPathNode.scala
@@ -8,10 +8,10 @@ class PermissionGrantingPathNode(wrapped: PathNode) extends PathNode {
def doPrivileged[T](m: => T): T = {
AccessController.doPrivileged(new PrivilegedAction[T] {
- def run: T = {
- m
- }
- })
+ def run: T = {
+ m
+ }
+ })
}
def exists(): Boolean = doPrivileged(wrapped.exists())
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/bundledevtool/src/main/scala/org/apache/clerezza/bundledevtool/UnavailableSkeletonException.scala
----------------------------------------------------------------------
diff --git a/bundledevtool/src/main/scala/org/apache/clerezza/bundledevtool/UnavailableSkeletonException.scala b/bundledevtool/src/main/scala/org/apache/clerezza/bundledevtool/UnavailableSkeletonException.scala
index de8f696..5cb86e1 100644
--- a/bundledevtool/src/main/scala/org/apache/clerezza/bundledevtool/UnavailableSkeletonException.scala
+++ b/bundledevtool/src/main/scala/org/apache/clerezza/bundledevtool/UnavailableSkeletonException.scala
@@ -20,6 +20,6 @@
package org.apache.clerezza.bundledevtool
class UnavailableSkeletonException(val requested: Symbol, val available: Seq[Symbol])
- extends RuntimeException("The Skeleton "+requested.name+" is not avialble") {
+ extends RuntimeException("The Skeleton "+requested.name+" is not avialble") {
}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/bundledevtool/src/main/scala/sbt/ErrorHandling.scala
----------------------------------------------------------------------
diff --git a/bundledevtool/src/main/scala/sbt/ErrorHandling.scala b/bundledevtool/src/main/scala/sbt/ErrorHandling.scala
index d2566a1..ff31430 100644
--- a/bundledevtool/src/main/scala/sbt/ErrorHandling.scala
+++ b/bundledevtool/src/main/scala/sbt/ErrorHandling.scala
@@ -26,24 +26,24 @@ package sbt
object ErrorHandling
{
- def translate[T](msg: => String)(f: => T) =
- try { f }
- catch { case e: Exception => throw new TranslatedException(msg + e.toString, e) }
+ def translate[T](msg: => String)(f: => T) =
+ try { f }
+ catch { case e: Exception => throw new TranslatedException(msg + e.toString, e) }
- def wideConvert[T](f: => T): Either[Throwable, T] =
- try { Right(f) }
- catch
- {
- case ex @ (_: Exception | _: StackOverflowError) => Left(ex)
- case err @ (_: ThreadDeath | _: VirtualMachineError) => throw err
- case x => Left(x)
- }
+ def wideConvert[T](f: => T): Either[Throwable, T] =
+ try { Right(f) }
+ catch
+ {
+ case ex @ (_: Exception | _: StackOverflowError) => Left(ex)
+ case err @ (_: ThreadDeath | _: VirtualMachineError) => throw err
+ case x => Left(x)
+ }
- def convert[T](f: => T): Either[Exception, T] =
- try { Right(f) }
- catch { case e: Exception => Left(e) }
+ def convert[T](f: => T): Either[Exception, T] =
+ try { Right(f) }
+ catch { case e: Exception => Left(e) }
}
final class TranslatedException private[sbt](msg: String, cause: Throwable) extends RuntimeException(msg, cause)
{
- override def toString = msg
+ override def toString = msg
}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/bundledevtool/src/main/scala/sbt/io/Hash.scala
----------------------------------------------------------------------
diff --git a/bundledevtool/src/main/scala/sbt/io/Hash.scala b/bundledevtool/src/main/scala/sbt/io/Hash.scala
index 3f3bcf6..59aa5a3 100644
--- a/bundledevtool/src/main/scala/sbt/io/Hash.scala
+++ b/bundledevtool/src/main/scala/sbt/io/Hash.scala
@@ -28,70 +28,70 @@ import java.io.{ByteArrayInputStream, File, InputStream}
object Hash
{
- private val BufferSize = 8192
- def toHex(bytes: Array[Byte]): String =
- {
- val buffer = new StringBuilder(bytes.length * 2)
- for(i <- 0 until bytes.length)
- {
- val b = bytes(i)
- val bi: Int = if(b < 0) b + 256 else b
- buffer append toHex((bi >>> 4).asInstanceOf[Byte])
- buffer append toHex((bi & 0x0F).asInstanceOf[Byte])
- }
- buffer.toString
- }
- def fromHex(hex: String): Array[Byte] =
- {
- require((hex.length & 1) == 0, "Hex string must have length 2n.")
- val array = new Array[Byte](hex.length >> 1)
- for(i <- 0 until hex.length by 2)
- {
- val c1 = hex.charAt(i)
- val c2 = hex.charAt(i+1)
- array(i >> 1) = ((fromHex(c1) << 4) | fromHex(c2)).asInstanceOf[Byte]
- }
- array
- }
- /** Calculates the SHA-1 hash of the given String.*/
- def apply(s: String): Array[Byte] = apply(new ByteArrayInputStream(s.getBytes("UTF-8")))
- /** Calculates the SHA-1 hash of the given file.*/
- def apply(file: File): Array[Byte] = Using.fileInputStream(file)(apply)
- /** Calculates the SHA-1 hash of the given stream, closing it when finished.*/
- def apply(stream: InputStream): Array[Byte] =
- {
- import java.security.{MessageDigest, DigestInputStream}
- val digest = MessageDigest.getInstance("SHA")
- try
- {
- val dis = new DigestInputStream(stream, digest)
- val buffer = new Array[Byte](BufferSize)
- while(dis.read(buffer) >= 0) {}
- dis.close()
- digest.digest
- }
- finally { stream.close() }
- }
+ private val BufferSize = 8192
+ def toHex(bytes: Array[Byte]): String =
+ {
+ val buffer = new StringBuilder(bytes.length * 2)
+ for(i <- 0 until bytes.length)
+ {
+ val b = bytes(i)
+ val bi: Int = if(b < 0) b + 256 else b
+ buffer append toHex((bi >>> 4).asInstanceOf[Byte])
+ buffer append toHex((bi & 0x0F).asInstanceOf[Byte])
+ }
+ buffer.toString
+ }
+ def fromHex(hex: String): Array[Byte] =
+ {
+ require((hex.length & 1) == 0, "Hex string must have length 2n.")
+ val array = new Array[Byte](hex.length >> 1)
+ for(i <- 0 until hex.length by 2)
+ {
+ val c1 = hex.charAt(i)
+ val c2 = hex.charAt(i+1)
+ array(i >> 1) = ((fromHex(c1) << 4) | fromHex(c2)).asInstanceOf[Byte]
+ }
+ array
+ }
+ /** Calculates the SHA-1 hash of the given String.*/
+ def apply(s: String): Array[Byte] = apply(new ByteArrayInputStream(s.getBytes("UTF-8")))
+ /** Calculates the SHA-1 hash of the given file.*/
+ def apply(file: File): Array[Byte] = Using.fileInputStream(file)(apply)
+ /** Calculates the SHA-1 hash of the given stream, closing it when finished.*/
+ def apply(stream: InputStream): Array[Byte] =
+ {
+ import java.security.{MessageDigest, DigestInputStream}
+ val digest = MessageDigest.getInstance("SHA")
+ try
+ {
+ val dis = new DigestInputStream(stream, digest)
+ val buffer = new Array[Byte](BufferSize)
+ while(dis.read(buffer) >= 0) {}
+ dis.close()
+ digest.digest
+ }
+ finally { stream.close() }
+ }
- private def toHex(b: Byte): Char =
- {
- require(b >= 0 && b <= 15, "Byte " + b + " was not between 0 and 15")
- if(b < 10)
- ('0'.asInstanceOf[Int] + b).asInstanceOf[Char]
- else
- ('a'.asInstanceOf[Int] + (b-10)).asInstanceOf[Char]
- }
- private def fromHex(c: Char): Int =
- {
- val b =
- if(c >= '0' && c <= '9')
- (c - '0')
- else if(c >= 'a' && c <= 'f')
- (c - 'a') + 10
- else if(c >= 'A' && c <= 'F')
- (c - 'A') + 10
- else
- throw new RuntimeException("Invalid hex character: '" + c + "'.")
- b
- }
+ private def toHex(b: Byte): Char =
+ {
+ require(b >= 0 && b <= 15, "Byte " + b + " was not between 0 and 15")
+ if(b < 10)
+ ('0'.asInstanceOf[Int] + b).asInstanceOf[Char]
+ else
+ ('a'.asInstanceOf[Int] + (b-10)).asInstanceOf[Char]
+ }
+ private def fromHex(c: Char): Int =
+ {
+ val b =
+ if(c >= '0' && c <= '9')
+ (c - '0')
+ else if(c >= 'a' && c <= 'f')
+ (c - 'a') + 10
+ else if(c >= 'A' && c <= 'F')
+ (c - 'A') + 10
+ else
+ throw new RuntimeException("Invalid hex character: '" + c + "'.")
+ b
+ }
}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/bundledevtool/src/main/scala/sbt/io/IO.scala
----------------------------------------------------------------------
diff --git a/bundledevtool/src/main/scala/sbt/io/IO.scala b/bundledevtool/src/main/scala/sbt/io/IO.scala
index a360338..f4d8d73 100644
--- a/bundledevtool/src/main/scala/sbt/io/IO.scala
+++ b/bundledevtool/src/main/scala/sbt/io/IO.scala
@@ -40,573 +40,573 @@ import Function.tupled
object IO
{
- /** The maximum number of times a unique temporary filename is attempted to be created.*/
- private val MaximumTries = 10
- /** The producer of randomness for unique name generation.*/
- private lazy val random = new java.util.Random
- val temporaryDirectory = new File(System.getProperty("java.io.tmpdir"))
- /** The size of the byte or char buffer used in various methods.*/
- private val BufferSize = 8192
- val Newline = System.getProperty("line.separator")
-
- val utf8 = Charset.forName("UTF-8")
-
- def classLocation(cl: Class[_]): URL =
- {
- val codeSource = cl.getProtectionDomain.getCodeSource
- if(codeSource == null) error("No class location for " + cl)
- else codeSource.getLocation
- }
- def classLocationFile(cl: Class[_]): File = toFile(classLocation(cl))
- def classLocation[T](implicit mf: SManifest[T]): URL = classLocation(mf.erasure)
- def classLocationFile[T](implicit mf: SManifest[T]): File = classLocationFile(mf.erasure)
-
- def toFile(url: URL) =
- try { new File(url.toURI) }
- catch { case _: URISyntaxException => new File(url.getPath) }
-
- /** Converts the given URL to a File. If the URL is for an entry in a jar, the File for the jar is returned. */
- def asFile(url: URL): File =
- {
- url.getProtocol match
- {
- case "file" => toFile(url)
- case "jar" =>
- val path = url.getPath
- val end = path.indexOf('!')
- new File(new URI(if(end == -1) path else path.substring(0, end)))
- case _ => error("Invalid protocol " + url.getProtocol)
- }
- }
- def assertDirectory(file: File) { assert(file.isDirectory, (if(file.exists) "Not a directory: " else "Directory not found: ") + file) }
- def assertDirectories(file: File*) { file.foreach(assertDirectory) }
-
- // "base.extension" -> (base, extension)
- def split(name: String): (String, String) =
- {
- val lastDot = name.lastIndexOf('.')
- if(lastDot >= 0)
- (name.substring(0, lastDot), name.substring(lastDot+1))
- else
- (name, "")
- }
-
- def touch(files: Traversable[File]): Unit = files.foreach(touch)
- /** Creates a file at the given location.*/
- def touch(file: File)
- {
- createDirectory(file.getParentFile)
- val created = translate("Could not create file " + file) { file.createNewFile() }
- if(created || file.isDirectory)
- ()
- else if(!file.setLastModified(System.currentTimeMillis))
- error("Could not update last modified time for file " + file)
- }
- def createDirectories(dirs: Traversable[File]): Unit =
- dirs.foreach(createDirectory)
- def createDirectory(dir: File): Unit =
- {
- def failBase = "Could not create directory " + dir
- if(dir.isDirectory || dir.mkdirs())
- ()
- else if(dir.exists)
- error(failBase + ": file exists and is not a directory.")
- else
- error(failBase)
- }
-
- /** Gzips the file 'in' and writes it to 'out'. 'in' cannot be the same file as 'out'. */
- def gzip(in: File, out: File)
- {
- require(in != out, "Input file cannot be the same as the output file.")
- Using.fileInputStream(in) { inputStream =>
- Using.fileOutputStream()(out) { outputStream =>
- gzip(inputStream, outputStream)
- }
- }
- }
- /** Gzips the InputStream 'in' and writes it to 'output'. Neither stream is closed.*/
- def gzip(input: InputStream, output: OutputStream): Unit =
- gzipOutputStream(output) { gzStream => transfer(input, gzStream) }
-
- /** Gunzips the file 'in' and writes it to 'out'. 'in' cannot be the same file as 'out'. */
- def gunzip(in: File, out: File)
- {
- require(in != out, "Input file cannot be the same as the output file.")
- Using.fileInputStream(in) { inputStream =>
- Using.fileOutputStream()(out) { outputStream =>
- gunzip(inputStream, outputStream)
- }
- }
- }
- /** Gunzips the InputStream 'input' and writes it to 'output'. Neither stream is closed.*/
- def gunzip(input: InputStream, output: OutputStream): Unit =
- gzipInputStream(input) { gzStream => transfer(gzStream, output) }
-
- def unzip(from: File, toDirectory: File, filter: NameFilter = AllPassFilter): Set[File] = fileInputStream(from)(in => unzipStream(in, toDirectory, filter))
- def unzipURL(from: URL, toDirectory: File, filter: NameFilter = AllPassFilter): Set[File] = urlInputStream(from)(in => unzipStream(in, toDirectory, filter))
- def unzipStream(from: InputStream, toDirectory: File, filter: NameFilter = AllPassFilter): Set[File] =
- {
- createDirectory(toDirectory)
- zipInputStream(from) { zipInput => extract(zipInput, toDirectory, filter) }
- }
- private def extract(from: ZipInputStream, toDirectory: File, filter: NameFilter) =
- {
- val set = new HashSet[File]
- def next()
- {
- val entry = from.getNextEntry
- if(entry == null)
- ()
- else
- {
- val name = entry.getName
- if(filter.accept(name))
- {
- val target = new File(toDirectory, name)
- //log.debug("Extracting zip entry '" + name + "' to '" + target + "'")
- if(entry.isDirectory)
- createDirectory(target)
- else
- {
- set += target
- translate("Error extracting zip entry '" + name + "' to '" + target + "': ") {
- fileOutputStream(false)(target) { out => transfer(from, out) }
- }
- }
- //target.setLastModified(entry.getTime)
- }
- else
- {
- //log.debug("Ignoring zip entry '" + name + "'")
- }
- from.closeEntry()
- next()
- }
- }
- next()
- Set() ++ set
- }
-
- /** Retrieves the content of the given URL and writes it to the given File. */
- def download(url: URL, to: File) =
- Using.urlInputStream(url) { inputStream =>
- transfer(inputStream, to)
- }
-
- def transfer(in: File, out: File): Unit =
- fileInputStream(in){ in => transfer(in, out) }
-
- def transfer(in: File, out: OutputStream): Unit =
- fileInputStream(in){ in => transfer(in, out) }
-
- /** Copies all bytes from the given input stream to the given File.*/
- def transfer(in: InputStream, to: File): Unit =
- Using.fileOutputStream()(to) { outputStream =>
- transfer(in, outputStream)
- }
-
- /** Copies all bytes from the given input stream to the given output stream.
- * Neither stream is closed.*/
- def transfer(in: InputStream, out: OutputStream): Unit = transferImpl(in, out, false)
- /** Copies all bytes from the given input stream to the given output stream. The
- * input stream is closed after the method completes.*/
- def transferAndClose(in: InputStream, out: OutputStream): Unit = transferImpl(in, out, true)
- private def transferImpl(in: InputStream, out: OutputStream, close: Boolean)
- {
- try
- {
- val buffer = new Array[Byte](BufferSize)
- def read()
- {
- val byteCount = in.read(buffer)
- if(byteCount >= 0)
- {
- out.write(buffer, 0, byteCount)
- read()
- }
- }
- read()
- }
- finally { if(close) in.close }
- }
-
- /** Creates a temporary directory and provides its location to the given function. The directory
- * is deleted after the function returns.*/
- def withTemporaryDirectory[T](action: File => T): T =
- {
- val dir = createTemporaryDirectory
- try { action(dir) }
- finally { delete(dir) }
- }
- def createTemporaryDirectory: File =
- {
- def create(tries: Int): File =
- {
- if(tries > MaximumTries)
- error("Could not create temporary directory.")
- else
- {
- val randomName = "sbt_" + java.lang.Integer.toHexString(random.nextInt)
- val f = new File(temporaryDirectory, randomName)
-
- try { createDirectory(f); f }
- catch { case e: Exception => create(tries + 1) }
- }
- }
- create(0)
- }
- def withTemporaryFile[T](prefix: String, postfix: String)(action: File => T): T =
- {
- val file = File.createTempFile(prefix, postfix)
- try { action(file) }
- finally { file.delete() }
- }
-
- private[sbt] def jars(dir: File): Iterable[File] = listFiles(dir, GlobFilter("*.jar"))
-
- def deleteIfEmpty(dirs: collection.Set[File]): Unit =
- {
- val isEmpty = new HashMap[File, Boolean]
- def visit(f: File): Boolean = isEmpty.getOrElseUpdate(f, dirs(f) && f.isDirectory && (f.listFiles forall visit) )
-
- dirs foreach visit
- for( (f, true) <- isEmpty) f.delete
- }
-
- def delete(files: Iterable[File]): Unit = files.foreach(delete)
- def delete(file: File)
- {
- translate("Error deleting file " + file + ": ")
- {
- if(file.isDirectory)
- {
- delete(listFiles(file))
- file.delete
- }
- else if(file.exists)
- file.delete
- }
- }
- def listFiles(filter: java.io.FileFilter)(dir: File): Array[File] = wrapNull(dir.listFiles(filter))
- def listFiles(dir: File, filter: java.io.FileFilter): Array[File] = wrapNull(dir.listFiles(filter))
- def listFiles(dir: File): Array[File] = wrapNull(dir.listFiles())
- private[sbt] def wrapNull(a: Array[File]) =
- {
- if(a == null)
- new Array[File](0)
- else
- a
- }
-
-
- /** Creates a jar file.
- * @param sources The files to include in the jar file paired with the entry name in the jar.
- * @param outputJar The file to write the jar to.
- * @param manifest The manifest for the jar.*/
- def jar(sources: Traversable[(File,String)], outputJar: File, manifest: Manifest): Unit =
- archive(sources.toSeq, outputJar, Some(manifest))
- /** Creates a zip file.
- * @param sources The files to include in the zip file paired with the entry name in the zip.
- * @param outputZip The file to write the zip to.*/
- def zip(sources: Traversable[(File,String)], outputZip: File): Unit =
- archive(sources.toSeq, outputZip, None)
-
- private def archive(sources: Seq[(File,String)], outputFile: File, manifest: Option[Manifest])
- {
- if(outputFile.isDirectory)
- error("Specified output file " + outputFile + " is a directory.")
- else
- {
- val outputDir = outputFile.getParentFile
- createDirectory(outputDir)
- withZipOutput(outputFile, manifest)
- { output =>
- val createEntry: (String => ZipEntry) = if(manifest.isDefined) new JarEntry(_) else new ZipEntry(_)
- writeZip(sources, output)(createEntry)
- }
- }
- }
- private def writeZip(sources: Seq[(File,String)], output: ZipOutputStream)(createEntry: String => ZipEntry)
- {
- import Path.{lazyPathFinder => pf}
- val files = sources.collect { case (file,name) if file.isFile => (file, normalizeName(name)) }
- val now = System.currentTimeMillis
- // The CRC32 for an empty value, needed to store directories in zip files
- val emptyCRC = new CRC32().getValue()
-
- def addDirectoryEntry(name: String)
- {
- output putNextEntry makeDirectoryEntry(name)
- output.closeEntry()
- }
-
- def makeDirectoryEntry(name: String) =
- {
-// log.debug("\tAdding directory " + relativePath + " ...")
- val e = createEntry(name)
- e setTime now
- e setSize 0
- e setMethod ZipEntry.STORED
- e setCrc emptyCRC
- e
- }
-
- def makeFileEntry(file: File, name: String) =
- {
-// log.debug("\tAdding " + file + " as " + name + " ...")
- val e = createEntry(name)
- e setTime file.lastModified
- e
- }
- def addFileEntry(file: File, name: String)
- {
- output putNextEntry makeFileEntry(file, name)
- transfer(file, output)
- output.closeEntry()
- }
-
- //Calculate directories and add them to the generated Zip
- allDirectoryPaths(files) foreach addDirectoryEntry
-
- //Add all files to the generated Zip
- files foreach { case (file, name) => addFileEntry(file, name) }
- }
-
- // map a path a/b/c to List("a", "b")
- private def relativeComponents(path: String): List[String] =
- path.split("/").toList.dropRight(1)
-
- // map components List("a", "b", "c") to List("a/b/c/", "a/b/", "a/", "")
- private def directories(path: List[String]): List[String] =
- path.foldLeft(List(""))( (e,l) => (e.head + l + "/") :: e )
-
- // map a path a/b/c to List("a/b/", "a/")
- private def directoryPaths(path: String): List[String] =
- directories(relativeComponents(path)).filter(_.length > 1)
-
- // produce a sorted list of all the subdirectories of all provided files
- private def allDirectoryPaths(files: Iterable[(File,String)]) =
- TreeSet[String]() ++ (files flatMap { case (file, name) => directoryPaths(name) })
-
- private def normalizeDirName(name: String) =
- {
- val norm1 = normalizeName(name)
- if(norm1.endsWith("/")) norm1 else (norm1 + "/")
- }
- private def normalizeName(name: String) =
- {
- val sep = File.separatorChar
- if(sep == '/') name else name.replace(sep, '/')
- }
-
- private def withZipOutput(file: File, manifest: Option[Manifest])(f: ZipOutputStream => Unit)
- {
- fileOutputStream(false)(file) { fileOut =>
- val (zipOut, ext) =
- manifest match
- {
- case Some(mf) =>
- {
- import Attributes.Name.MANIFEST_VERSION
- val main = mf.getMainAttributes
- if(!main.containsKey(MANIFEST_VERSION))
- main.put(MANIFEST_VERSION, "1.0")
- (new JarOutputStream(fileOut, mf), "jar")
- }
- case None => (new ZipOutputStream(fileOut), "zip")
- }
- try { f(zipOut) }
- catch { case e: Exception => "Error writing " + ext + ": " + e.toString }
- finally { zipOut.close }
- }
- }
- def relativize(base: File, file: File): Option[String] =
- {
- val pathString = file.getAbsolutePath
- baseFileString(base) flatMap
- {
- baseString =>
- {
- if(pathString.startsWith(baseString))
- Some(pathString.substring(baseString.length))
- else
- None
- }
- }
- }
- private def baseFileString(baseFile: File): Option[String] =
- {
- if(baseFile.isDirectory)
- {
- val cp = baseFile.getAbsolutePath
- assert(cp.length > 0)
- val normalized = if(cp.charAt(cp.length - 1) == File.separatorChar) cp else cp + File.separatorChar
- Some(normalized)
- }
- else
- None
- }
- def copy(sources: Traversable[(File,File)], overwrite: Boolean = false, preserveLastModified: Boolean = false): Set[File] =
- sources.map( tupled(copyImpl(overwrite, preserveLastModified)) ).toSet
- private def copyImpl(overwrite: Boolean, preserveLastModified: Boolean)(from: File, to: File): File =
- {
- if(overwrite || !to.exists || from.lastModified > to.lastModified)
- {
- if(from.isDirectory)
- createDirectory(to)
- else
- {
- createDirectory(to.getParentFile)
- copyFile(from, to, preserveLastModified)
- }
- }
- to
- }
- def copyDirectory(source: File, target: File, overwrite: Boolean = false, preserveLastModified: Boolean = false): Unit =
- copy( (Path.fromFile(source) ***) x Path.rebase(source, target), overwrite, preserveLastModified)
-
- def copyFile(sourceFile: File, targetFile: File, preserveLastModified: Boolean = false)
- {
- require(sourceFile.exists, "Source file '" + sourceFile.getAbsolutePath + "' does not exist.")
- require(!sourceFile.isDirectory, "Source file '" + sourceFile.getAbsolutePath + "' is a directory.")
- fileInputChannel(sourceFile) { in =>
- fileOutputChannel(targetFile) { out =>
- val copied = out.transferFrom(in, 0, in.size)
- if(copied != in.size)
- error("Could not copy '" + sourceFile + "' to '" + targetFile + "' (" + copied + "/" + in.size + " bytes copied)")
- }
- }
- if(preserveLastModified)
- copyLastModified(sourceFile, targetFile)
- }
- def copyLastModified(sourceFile: File, targetFile: File) = targetFile.setLastModified( sourceFile.lastModified )
- def defaultCharset = utf8
-
- def write(file: File, content: String, charset: Charset = defaultCharset, append: Boolean = false): Unit =
- writer(file, content, charset, append) { _.write(content) }
-
- def writer[T](file: File, content: String, charset: Charset, append: Boolean = false)(f: BufferedWriter => T): T =
- {
- if(charset.newEncoder.canEncode(content))
- fileWriter(charset, append)(file) { f }
- else
- error("String cannot be encoded by charset " + charset.name)
- }
-
- def reader[T](file: File, charset: Charset = defaultCharset)(f: BufferedReader => T): T =
- fileReader(charset)(file) { f }
-
- def read(file: File, charset: Charset = defaultCharset): String =
- {
- val out = new ByteArrayOutputStream(file.length.toInt)
- transfer(file, out)
- out.toString(charset.name)
- }
- /** doesn't close the InputStream */
- def readStream(in: InputStream, charset: Charset = defaultCharset): String =
- {
- val out = new ByteArrayOutputStream
- transfer(in, out)
- out.toString(charset.name)
- }
- def readBytes(file: File): Array[Byte] = fileInputStream(file)(readBytes)
- /** doesn't close the InputStream */
- def readBytes(in: InputStream): Array[Byte] =
- {
- val out = new ByteArrayOutputStream
- transfer(in, out)
- out.toByteArray
- }
-
- def append(file: File, content: String, charset: Charset = defaultCharset): Unit =
- write(file, content, charset, true)
- def append(file: File, bytes: Array[Byte]): Unit =
- writeBytes(file, bytes, true)
-
- def write(file: File, bytes: Array[Byte]): Unit =
- writeBytes(file, bytes, false)
- private def writeBytes(file: File, bytes: Array[Byte], append: Boolean): Unit =
- fileOutputStream(append)(file) { _.write(bytes) }
-
-
- // Not optimized for large files
- def readLines(file: File, charset: Charset = defaultCharset): List[String] =
- fileReader(charset)(file)(readLines)
-
- // Not optimized for large files
- def readLines(in: BufferedReader): List[String] =
- foldLines[List[String]](in, Nil)( (accum, line) => line :: accum ).reverse
-
- def foreachLine(in: BufferedReader)(f: String => Unit): Unit =
- foldLines(in, ())( (_, line) => f(line) )
-
- def foldLines[T](in: BufferedReader, init: T)(f: (T, String) => T): T =
- {
- def readLine(accum: T): T =
- {
- val line = in.readLine()
- if(line eq null) accum else readLine(f(accum, line))
- }
- readLine(init)
- }
-
- def writeLines(file: File, lines: Seq[String], charset: Charset = defaultCharset, append: Boolean = false): Unit =
- writer(file, lines.headOption.getOrElse(""), charset, append) { w =>
- lines.foreach { line => w.write(line); w.newLine() }
- }
-
- def write(properties: Properties, label: String, to: File) =
- fileOutputStream()(to) { output => properties.store(output, label) }
- def load(properties: Properties, from: File): Unit =
- if(from.exists)
- fileInputStream(from){ input => properties.load(input) }
-
- /** A pattern used to split a String by path separator characters.*/
- private val PathSeparatorPattern = java.util.regex.Pattern.compile(File.pathSeparator)
-
- /** Splits a String around path separator characters. */
- def pathSplit(s: String) = PathSeparatorPattern.split(s)
-
- /** Move the provided files to a temporary location.
- * If 'f' returns normally, delete the files.
- * If 'f' throws an Exception, return the files to their original location.*/
- def stash[T](files: Set[File])(f: => T): T =
- withTemporaryDirectory { dir =>
- val stashed = stashLocations(dir, files.toArray)
- move(stashed)
-
- try { f } catch { case e: Exception =>
- try { move(stashed.map(_.swap)); throw e }
- catch { case _: Exception => throw e }
- }
- }
-
- private def stashLocations(dir: File, files: Array[File]) =
- for( (file, index) <- files.zipWithIndex) yield
- (file, new File(dir, index.toHexString))
-
- def move(files: Traversable[(File, File)]): Unit =
- files.foreach(Function.tupled(move))
-
- def move(a: File, b: File): Unit =
- {
- if(b.exists)
- delete(b)
- if(!a.renameTo(b))
- {
- copyFile(a, b, true)
- delete(a)
- }
- }
-
- def gzipFileOut[T](file: File)(f: OutputStream => T): T =
- Using.fileOutputStream()(file) { fout =>
- Using.gzipOutputStream(fout) { outg =>
- Using.bufferedOutputStream(outg)(f) }}
-
- def gzipFileIn[T](file: File)(f: InputStream => T): T =
- Using.fileInputStream(file) { fin =>
- Using.gzipInputStream(fin) { ing =>
- Using.bufferedInputStream(ing)(f) }}
+ /** The maximum number of times a unique temporary filename is attempted to be created.*/
+ private val MaximumTries = 10
+ /** The producer of randomness for unique name generation.*/
+ private lazy val random = new java.util.Random
+ val temporaryDirectory = new File(System.getProperty("java.io.tmpdir"))
+ /** The size of the byte or char buffer used in various methods.*/
+ private val BufferSize = 8192
+ val Newline = System.getProperty("line.separator")
+
+ val utf8 = Charset.forName("UTF-8")
+
+ def classLocation(cl: Class[_]): URL =
+ {
+ val codeSource = cl.getProtectionDomain.getCodeSource
+ if(codeSource == null) error("No class location for " + cl)
+ else codeSource.getLocation
+ }
+ def classLocationFile(cl: Class[_]): File = toFile(classLocation(cl))
+ def classLocation[T](implicit mf: SManifest[T]): URL = classLocation(mf.erasure)
+ def classLocationFile[T](implicit mf: SManifest[T]): File = classLocationFile(mf.erasure)
+
+ def toFile(url: URL) =
+ try { new File(url.toURI) }
+ catch { case _: URISyntaxException => new File(url.getPath) }
+
+ /** Converts the given URL to a File. If the URL is for an entry in a jar, the File for the jar is returned. */
+ def asFile(url: URL): File =
+ {
+ url.getProtocol match
+ {
+ case "file" => toFile(url)
+ case "jar" =>
+ val path = url.getPath
+ val end = path.indexOf('!')
+ new File(new URI(if(end == -1) path else path.substring(0, end)))
+ case _ => error("Invalid protocol " + url.getProtocol)
+ }
+ }
+ def assertDirectory(file: File) { assert(file.isDirectory, (if(file.exists) "Not a directory: " else "Directory not found: ") + file) }
+ def assertDirectories(file: File*) { file.foreach(assertDirectory) }
+
+ // "base.extension" -> (base, extension)
+ def split(name: String): (String, String) =
+ {
+ val lastDot = name.lastIndexOf('.')
+ if(lastDot >= 0)
+ (name.substring(0, lastDot), name.substring(lastDot+1))
+ else
+ (name, "")
+ }
+
+ def touch(files: Traversable[File]): Unit = files.foreach(touch)
+ /** Creates a file at the given location.*/
+ def touch(file: File)
+ {
+ createDirectory(file.getParentFile)
+ val created = translate("Could not create file " + file) { file.createNewFile() }
+ if(created || file.isDirectory)
+ ()
+ else if(!file.setLastModified(System.currentTimeMillis))
+ error("Could not update last modified time for file " + file)
+ }
+ def createDirectories(dirs: Traversable[File]): Unit =
+ dirs.foreach(createDirectory)
+ def createDirectory(dir: File): Unit =
+ {
+ def failBase = "Could not create directory " + dir
+ if(dir.isDirectory || dir.mkdirs())
+ ()
+ else if(dir.exists)
+ error(failBase + ": file exists and is not a directory.")
+ else
+ error(failBase)
+ }
+
+ /** Gzips the file 'in' and writes it to 'out'. 'in' cannot be the same file as 'out'. */
+ def gzip(in: File, out: File)
+ {
+ require(in != out, "Input file cannot be the same as the output file.")
+ Using.fileInputStream(in) { inputStream =>
+ Using.fileOutputStream()(out) { outputStream =>
+ gzip(inputStream, outputStream)
+ }
+ }
+ }
+ /** Gzips the InputStream 'in' and writes it to 'output'. Neither stream is closed.*/
+ def gzip(input: InputStream, output: OutputStream): Unit =
+ gzipOutputStream(output) { gzStream => transfer(input, gzStream) }
+
+ /** Gunzips the file 'in' and writes it to 'out'. 'in' cannot be the same file as 'out'. */
+ def gunzip(in: File, out: File)
+ {
+ require(in != out, "Input file cannot be the same as the output file.")
+ Using.fileInputStream(in) { inputStream =>
+ Using.fileOutputStream()(out) { outputStream =>
+ gunzip(inputStream, outputStream)
+ }
+ }
+ }
+ /** Gunzips the InputStream 'input' and writes it to 'output'. Neither stream is closed.*/
+ def gunzip(input: InputStream, output: OutputStream): Unit =
+ gzipInputStream(input) { gzStream => transfer(gzStream, output) }
+
+ def unzip(from: File, toDirectory: File, filter: NameFilter = AllPassFilter): Set[File] = fileInputStream(from)(in => unzipStream(in, toDirectory, filter))
+ def unzipURL(from: URL, toDirectory: File, filter: NameFilter = AllPassFilter): Set[File] = urlInputStream(from)(in => unzipStream(in, toDirectory, filter))
+ def unzipStream(from: InputStream, toDirectory: File, filter: NameFilter = AllPassFilter): Set[File] =
+ {
+ createDirectory(toDirectory)
+ zipInputStream(from) { zipInput => extract(zipInput, toDirectory, filter) }
+ }
+ private def extract(from: ZipInputStream, toDirectory: File, filter: NameFilter) =
+ {
+ val set = new HashSet[File]
+ def next()
+ {
+ val entry = from.getNextEntry
+ if(entry == null)
+ ()
+ else
+ {
+ val name = entry.getName
+ if(filter.accept(name))
+ {
+ val target = new File(toDirectory, name)
+ //log.debug("Extracting zip entry '" + name + "' to '" + target + "'")
+ if(entry.isDirectory)
+ createDirectory(target)
+ else
+ {
+ set += target
+ translate("Error extracting zip entry '" + name + "' to '" + target + "': ") {
+ fileOutputStream(false)(target) { out => transfer(from, out) }
+ }
+ }
+ //target.setLastModified(entry.getTime)
+ }
+ else
+ {
+ //log.debug("Ignoring zip entry '" + name + "'")
+ }
+ from.closeEntry()
+ next()
+ }
+ }
+ next()
+ Set() ++ set
+ }
+
+ /** Retrieves the content of the given URL and writes it to the given File. */
+ def download(url: URL, to: File) =
+ Using.urlInputStream(url) { inputStream =>
+ transfer(inputStream, to)
+ }
+
+ def transfer(in: File, out: File): Unit =
+ fileInputStream(in){ in => transfer(in, out) }
+
+ def transfer(in: File, out: OutputStream): Unit =
+ fileInputStream(in){ in => transfer(in, out) }
+
+ /** Copies all bytes from the given input stream to the given File.*/
+ def transfer(in: InputStream, to: File): Unit =
+ Using.fileOutputStream()(to) { outputStream =>
+ transfer(in, outputStream)
+ }
+
+ /** Copies all bytes from the given input stream to the given output stream.
+ * Neither stream is closed.*/
+ def transfer(in: InputStream, out: OutputStream): Unit = transferImpl(in, out, false)
+ /** Copies all bytes from the given input stream to the given output stream. The
+ * input stream is closed after the method completes.*/
+ def transferAndClose(in: InputStream, out: OutputStream): Unit = transferImpl(in, out, true)
+ private def transferImpl(in: InputStream, out: OutputStream, close: Boolean)
+ {
+ try
+ {
+ val buffer = new Array[Byte](BufferSize)
+ def read()
+ {
+ val byteCount = in.read(buffer)
+ if(byteCount >= 0)
+ {
+ out.write(buffer, 0, byteCount)
+ read()
+ }
+ }
+ read()
+ }
+ finally { if(close) in.close }
+ }
+
+ /** Creates a temporary directory and provides its location to the given function. The directory
+ * is deleted after the function returns.*/
+ def withTemporaryDirectory[T](action: File => T): T =
+ {
+ val dir = createTemporaryDirectory
+ try { action(dir) }
+ finally { delete(dir) }
+ }
+ def createTemporaryDirectory: File =
+ {
+ def create(tries: Int): File =
+ {
+ if(tries > MaximumTries)
+ error("Could not create temporary directory.")
+ else
+ {
+ val randomName = "sbt_" + java.lang.Integer.toHexString(random.nextInt)
+ val f = new File(temporaryDirectory, randomName)
+
+ try { createDirectory(f); f }
+ catch { case e: Exception => create(tries + 1) }
+ }
+ }
+ create(0)
+ }
+ def withTemporaryFile[T](prefix: String, postfix: String)(action: File => T): T =
+ {
+ val file = File.createTempFile(prefix, postfix)
+ try { action(file) }
+ finally { file.delete() }
+ }
+
+ private[sbt] def jars(dir: File): Iterable[File] = listFiles(dir, GlobFilter("*.jar"))
+
+ def deleteIfEmpty(dirs: collection.Set[File]): Unit =
+ {
+ val isEmpty = new HashMap[File, Boolean]
+ def visit(f: File): Boolean = isEmpty.getOrElseUpdate(f, dirs(f) && f.isDirectory && (f.listFiles forall visit) )
+
+ dirs foreach visit
+ for( (f, true) <- isEmpty) f.delete
+ }
+
+ def delete(files: Iterable[File]): Unit = files.foreach(delete)
+ def delete(file: File)
+ {
+ translate("Error deleting file " + file + ": ")
+ {
+ if(file.isDirectory)
+ {
+ delete(listFiles(file))
+ file.delete
+ }
+ else if(file.exists)
+ file.delete
+ }
+ }
+ def listFiles(filter: java.io.FileFilter)(dir: File): Array[File] = wrapNull(dir.listFiles(filter))
+ def listFiles(dir: File, filter: java.io.FileFilter): Array[File] = wrapNull(dir.listFiles(filter))
+ def listFiles(dir: File): Array[File] = wrapNull(dir.listFiles())
+ private[sbt] def wrapNull(a: Array[File]) =
+ {
+ if(a == null)
+ new Array[File](0)
+ else
+ a
+ }
+
+
+ /** Creates a jar file.
+ * @param sources The files to include in the jar file paired with the entry name in the jar.
+ * @param outputJar The file to write the jar to.
+ * @param manifest The manifest for the jar.*/
+ def jar(sources: Traversable[(File,String)], outputJar: File, manifest: Manifest): Unit =
+ archive(sources.toSeq, outputJar, Some(manifest))
+ /** Creates a zip file.
+ * @param sources The files to include in the zip file paired with the entry name in the zip.
+ * @param outputZip The file to write the zip to.*/
+ def zip(sources: Traversable[(File,String)], outputZip: File): Unit =
+ archive(sources.toSeq, outputZip, None)
+
+ private def archive(sources: Seq[(File,String)], outputFile: File, manifest: Option[Manifest])
+ {
+ if(outputFile.isDirectory)
+ error("Specified output file " + outputFile + " is a directory.")
+ else
+ {
+ val outputDir = outputFile.getParentFile
+ createDirectory(outputDir)
+ withZipOutput(outputFile, manifest)
+ { output =>
+ val createEntry: (String => ZipEntry) = if(manifest.isDefined) new JarEntry(_) else new ZipEntry(_)
+ writeZip(sources, output)(createEntry)
+ }
+ }
+ }
+ private def writeZip(sources: Seq[(File,String)], output: ZipOutputStream)(createEntry: String => ZipEntry)
+ {
+ import Path.{lazyPathFinder => pf}
+ val files = sources.collect { case (file,name) if file.isFile => (file, normalizeName(name)) }
+ val now = System.currentTimeMillis
+ // The CRC32 for an empty value, needed to store directories in zip files
+ val emptyCRC = new CRC32().getValue()
+
+ def addDirectoryEntry(name: String)
+ {
+ output putNextEntry makeDirectoryEntry(name)
+ output.closeEntry()
+ }
+
+ def makeDirectoryEntry(name: String) =
+ {
+// log.debug("\tAdding directory " + relativePath + " ...")
+ val e = createEntry(name)
+ e setTime now
+ e setSize 0
+ e setMethod ZipEntry.STORED
+ e setCrc emptyCRC
+ e
+ }
+
+ def makeFileEntry(file: File, name: String) =
+ {
+// log.debug("\tAdding " + file + " as " + name + " ...")
+ val e = createEntry(name)
+ e setTime file.lastModified
+ e
+ }
+ def addFileEntry(file: File, name: String)
+ {
+ output putNextEntry makeFileEntry(file, name)
+ transfer(file, output)
+ output.closeEntry()
+ }
+
+ //Calculate directories and add them to the generated Zip
+ allDirectoryPaths(files) foreach addDirectoryEntry
+
+ //Add all files to the generated Zip
+ files foreach { case (file, name) => addFileEntry(file, name) }
+ }
+
+ // map a path a/b/c to List("a", "b")
+ private def relativeComponents(path: String): List[String] =
+ path.split("/").toList.dropRight(1)
+
+ // map components List("a", "b", "c") to List("a/b/c/", "a/b/", "a/", "")
+ private def directories(path: List[String]): List[String] =
+ path.foldLeft(List(""))( (e,l) => (e.head + l + "/") :: e )
+
+ // map a path a/b/c to List("a/b/", "a/")
+ private def directoryPaths(path: String): List[String] =
+ directories(relativeComponents(path)).filter(_.length > 1)
+
+ // produce a sorted list of all the subdirectories of all provided files
+ private def allDirectoryPaths(files: Iterable[(File,String)]) =
+ TreeSet[String]() ++ (files flatMap { case (file, name) => directoryPaths(name) })
+
+ private def normalizeDirName(name: String) =
+ {
+ val norm1 = normalizeName(name)
+ if(norm1.endsWith("/")) norm1 else (norm1 + "/")
+ }
+ private def normalizeName(name: String) =
+ {
+ val sep = File.separatorChar
+ if(sep == '/') name else name.replace(sep, '/')
+ }
+
+ private def withZipOutput(file: File, manifest: Option[Manifest])(f: ZipOutputStream => Unit)
+ {
+ fileOutputStream(false)(file) { fileOut =>
+ val (zipOut, ext) =
+ manifest match
+ {
+ case Some(mf) =>
+ {
+ import Attributes.Name.MANIFEST_VERSION
+ val main = mf.getMainAttributes
+ if(!main.containsKey(MANIFEST_VERSION))
+ main.put(MANIFEST_VERSION, "1.0")
+ (new JarOutputStream(fileOut, mf), "jar")
+ }
+ case None => (new ZipOutputStream(fileOut), "zip")
+ }
+ try { f(zipOut) }
+ catch { case e: Exception => "Error writing " + ext + ": " + e.toString }
+ finally { zipOut.close }
+ }
+ }
+ def relativize(base: File, file: File): Option[String] =
+ {
+ val pathString = file.getAbsolutePath
+ baseFileString(base) flatMap
+ {
+ baseString =>
+ {
+ if(pathString.startsWith(baseString))
+ Some(pathString.substring(baseString.length))
+ else
+ None
+ }
+ }
+ }
+ private def baseFileString(baseFile: File): Option[String] =
+ {
+ if(baseFile.isDirectory)
+ {
+ val cp = baseFile.getAbsolutePath
+ assert(cp.length > 0)
+ val normalized = if(cp.charAt(cp.length - 1) == File.separatorChar) cp else cp + File.separatorChar
+ Some(normalized)
+ }
+ else
+ None
+ }
+ def copy(sources: Traversable[(File,File)], overwrite: Boolean = false, preserveLastModified: Boolean = false): Set[File] =
+ sources.map( tupled(copyImpl(overwrite, preserveLastModified)) ).toSet
+ private def copyImpl(overwrite: Boolean, preserveLastModified: Boolean)(from: File, to: File): File =
+ {
+ if(overwrite || !to.exists || from.lastModified > to.lastModified)
+ {
+ if(from.isDirectory)
+ createDirectory(to)
+ else
+ {
+ createDirectory(to.getParentFile)
+ copyFile(from, to, preserveLastModified)
+ }
+ }
+ to
+ }
+ def copyDirectory(source: File, target: File, overwrite: Boolean = false, preserveLastModified: Boolean = false): Unit =
+ copy( (Path.fromFile(source) ***) x Path.rebase(source, target), overwrite, preserveLastModified)
+
+ def copyFile(sourceFile: File, targetFile: File, preserveLastModified: Boolean = false)
+ {
+ require(sourceFile.exists, "Source file '" + sourceFile.getAbsolutePath + "' does not exist.")
+ require(!sourceFile.isDirectory, "Source file '" + sourceFile.getAbsolutePath + "' is a directory.")
+ fileInputChannel(sourceFile) { in =>
+ fileOutputChannel(targetFile) { out =>
+ val copied = out.transferFrom(in, 0, in.size)
+ if(copied != in.size)
+ error("Could not copy '" + sourceFile + "' to '" + targetFile + "' (" + copied + "/" + in.size + " bytes copied)")
+ }
+ }
+ if(preserveLastModified)
+ copyLastModified(sourceFile, targetFile)
+ }
+ def copyLastModified(sourceFile: File, targetFile: File) = targetFile.setLastModified( sourceFile.lastModified )
+ def defaultCharset = utf8
+
+ def write(file: File, content: String, charset: Charset = defaultCharset, append: Boolean = false): Unit =
+ writer(file, content, charset, append) { _.write(content) }
+
+ def writer[T](file: File, content: String, charset: Charset, append: Boolean = false)(f: BufferedWriter => T): T =
+ {
+ if(charset.newEncoder.canEncode(content))
+ fileWriter(charset, append)(file) { f }
+ else
+ error("String cannot be encoded by charset " + charset.name)
+ }
+
+ def reader[T](file: File, charset: Charset = defaultCharset)(f: BufferedReader => T): T =
+ fileReader(charset)(file) { f }
+
+ def read(file: File, charset: Charset = defaultCharset): String =
+ {
+ val out = new ByteArrayOutputStream(file.length.toInt)
+ transfer(file, out)
+ out.toString(charset.name)
+ }
+ /** doesn't close the InputStream */
+ def readStream(in: InputStream, charset: Charset = defaultCharset): String =
+ {
+ val out = new ByteArrayOutputStream
+ transfer(in, out)
+ out.toString(charset.name)
+ }
+ def readBytes(file: File): Array[Byte] = fileInputStream(file)(readBytes)
+ /** doesn't close the InputStream */
+ def readBytes(in: InputStream): Array[Byte] =
+ {
+ val out = new ByteArrayOutputStream
+ transfer(in, out)
+ out.toByteArray
+ }
+
+ def append(file: File, content: String, charset: Charset = defaultCharset): Unit =
+ write(file, content, charset, true)
+ def append(file: File, bytes: Array[Byte]): Unit =
+ writeBytes(file, bytes, true)
+
+ def write(file: File, bytes: Array[Byte]): Unit =
+ writeBytes(file, bytes, false)
+ private def writeBytes(file: File, bytes: Array[Byte], append: Boolean): Unit =
+ fileOutputStream(append)(file) { _.write(bytes) }
+
+
+ // Not optimized for large files
+ def readLines(file: File, charset: Charset = defaultCharset): List[String] =
+ fileReader(charset)(file)(readLines)
+
+ // Not optimized for large files
+ def readLines(in: BufferedReader): List[String] =
+ foldLines[List[String]](in, Nil)( (accum, line) => line :: accum ).reverse
+
+ def foreachLine(in: BufferedReader)(f: String => Unit): Unit =
+ foldLines(in, ())( (_, line) => f(line) )
+
+ def foldLines[T](in: BufferedReader, init: T)(f: (T, String) => T): T =
+ {
+ def readLine(accum: T): T =
+ {
+ val line = in.readLine()
+ if(line eq null) accum else readLine(f(accum, line))
+ }
+ readLine(init)
+ }
+
+ def writeLines(file: File, lines: Seq[String], charset: Charset = defaultCharset, append: Boolean = false): Unit =
+ writer(file, lines.headOption.getOrElse(""), charset, append) { w =>
+ lines.foreach { line => w.write(line); w.newLine() }
+ }
+
+ def write(properties: Properties, label: String, to: File) =
+ fileOutputStream()(to) { output => properties.store(output, label) }
+ def load(properties: Properties, from: File): Unit =
+ if(from.exists)
+ fileInputStream(from){ input => properties.load(input) }
+
+ /** A pattern used to split a String by path separator characters.*/
+ private val PathSeparatorPattern = java.util.regex.Pattern.compile(File.pathSeparator)
+
+ /** Splits a String around path separator characters. */
+ def pathSplit(s: String) = PathSeparatorPattern.split(s)
+
+ /** Move the provided files to a temporary location.
+ * If 'f' returns normally, delete the files.
+ * If 'f' throws an Exception, return the files to their original location.*/
+ def stash[T](files: Set[File])(f: => T): T =
+ withTemporaryDirectory { dir =>
+ val stashed = stashLocations(dir, files.toArray)
+ move(stashed)
+
+ try { f } catch { case e: Exception =>
+ try { move(stashed.map(_.swap)); throw e }
+ catch { case _: Exception => throw e }
+ }
+ }
+
+ private def stashLocations(dir: File, files: Array[File]) =
+ for( (file, index) <- files.zipWithIndex) yield
+ (file, new File(dir, index.toHexString))
+
+ def move(files: Traversable[(File, File)]): Unit =
+ files.foreach(Function.tupled(move))
+
+ def move(a: File, b: File): Unit =
+ {
+ if(b.exists)
+ delete(b)
+ if(!a.renameTo(b))
+ {
+ copyFile(a, b, true)
+ delete(a)
+ }
+ }
+
+ def gzipFileOut[T](file: File)(f: OutputStream => T): T =
+ Using.fileOutputStream()(file) { fout =>
+ Using.gzipOutputStream(fout) { outg =>
+ Using.bufferedOutputStream(outg)(f) }}
+
+ def gzipFileIn[T](file: File)(f: InputStream => T): T =
+ Using.fileInputStream(file) { fin =>
+ Using.gzipInputStream(fin) { ing =>
+ Using.bufferedInputStream(ing)(f) }}
}
[8/9] CLEREZZA-435: repaced tabs with spaces in scala files
Posted by re...@apache.org.
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/bundledevtool/src/main/scala/sbt/io/IPC.scala
----------------------------------------------------------------------
diff --git a/bundledevtool/src/main/scala/sbt/io/IPC.scala b/bundledevtool/src/main/scala/sbt/io/IPC.scala
index 01f3092..ddd09f7 100644
--- a/bundledevtool/src/main/scala/sbt/io/IPC.scala
+++ b/bundledevtool/src/main/scala/sbt/io/IPC.scala
@@ -29,65 +29,65 @@ import java.net.{InetAddress, ServerSocket, Socket}
object IPC
{
- private val portMin = 1025
- private val portMax = 65536
- private val loopback = InetAddress.getByName(null) // loopback
-
- def client[T](port: Int)(f: IPC => T): T =
- ipc(new Socket(loopback, port))(f)
-
- def pullServer[T](f: Server => T): T =
- {
- val server = makeServer
- try { f(new Server(server)) }
- finally { server.close() }
- }
- def makeServer: ServerSocket =
- {
- val random = new java.util.Random
- def nextPort = random.nextInt(portMax - portMin + 1) + portMin
- def createServer(attempts: Int): ServerSocket =
- if(attempts > 0)
- try { new ServerSocket(nextPort, 1, loopback) }
- catch { case _: Exception => createServer(attempts - 1) }
- else
- error("Could not connect to socket: maximum attempts exceeded")
- createServer(10)
- }
- def server[T](f: IPC => Option[T]): T = serverImpl(makeServer, f)
- def server[T](port: Int)(f: IPC => Option[T]): T =
- serverImpl(new ServerSocket(port, 1, loopback), f)
- private def serverImpl[T](server: ServerSocket, f: IPC => Option[T]): T =
- {
- def listen(): T =
- {
- ipc(server.accept())(f) match
- {
- case Some(done) => done
- case None => listen()
- }
- }
-
- try { listen() }
- finally { server.close() }
- }
- private def ipc[T](s: Socket)(f: IPC => T): T =
- try { f(new IPC(s)) }
- finally { s.close() }
-
- final class Server private[IPC](s: ServerSocket) extends NotNull
- {
- def port = s.getLocalPort
- def close() = s.close()
- def connection[T](f: IPC => T): T = IPC.ipc(s.accept())(f)
- }
+ private val portMin = 1025
+ private val portMax = 65536
+ private val loopback = InetAddress.getByName(null) // loopback
+
+ def client[T](port: Int)(f: IPC => T): T =
+ ipc(new Socket(loopback, port))(f)
+
+ def pullServer[T](f: Server => T): T =
+ {
+ val server = makeServer
+ try { f(new Server(server)) }
+ finally { server.close() }
+ }
+ def makeServer: ServerSocket =
+ {
+ val random = new java.util.Random
+ def nextPort = random.nextInt(portMax - portMin + 1) + portMin
+ def createServer(attempts: Int): ServerSocket =
+ if(attempts > 0)
+ try { new ServerSocket(nextPort, 1, loopback) }
+ catch { case _: Exception => createServer(attempts - 1) }
+ else
+ error("Could not connect to socket: maximum attempts exceeded")
+ createServer(10)
+ }
+ def server[T](f: IPC => Option[T]): T = serverImpl(makeServer, f)
+ def server[T](port: Int)(f: IPC => Option[T]): T =
+ serverImpl(new ServerSocket(port, 1, loopback), f)
+ private def serverImpl[T](server: ServerSocket, f: IPC => Option[T]): T =
+ {
+ def listen(): T =
+ {
+ ipc(server.accept())(f) match
+ {
+ case Some(done) => done
+ case None => listen()
+ }
+ }
+
+ try { listen() }
+ finally { server.close() }
+ }
+ private def ipc[T](s: Socket)(f: IPC => T): T =
+ try { f(new IPC(s)) }
+ finally { s.close() }
+
+ final class Server private[IPC](s: ServerSocket) extends NotNull
+ {
+ def port = s.getLocalPort
+ def close() = s.close()
+ def connection[T](f: IPC => T): T = IPC.ipc(s.accept())(f)
+ }
}
final class IPC private(s: Socket) extends NotNull
{
- def port = s.getLocalPort
- private val in = new BufferedReader(new InputStreamReader(s.getInputStream))
- private val out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream))
-
- def send(s: String) = { out.write(s); out.newLine(); out.flush() }
- def receive: String = in.readLine()
+ def port = s.getLocalPort
+ private val in = new BufferedReader(new InputStreamReader(s.getInputStream))
+ private val out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream))
+
+ def send(s: String) = { out.write(s); out.newLine(); out.flush() }
+ def receive: String = in.readLine()
}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/bundledevtool/src/main/scala/sbt/io/NameFilter.scala
----------------------------------------------------------------------
diff --git a/bundledevtool/src/main/scala/sbt/io/NameFilter.scala b/bundledevtool/src/main/scala/sbt/io/NameFilter.scala
index 38ac454..4bf5c68 100644
--- a/bundledevtool/src/main/scala/sbt/io/NameFilter.scala
+++ b/bundledevtool/src/main/scala/sbt/io/NameFilter.scala
@@ -29,65 +29,65 @@ import java.util.regex.Pattern
trait FileFilter extends java.io.FileFilter with NotNull
{
- def || (filter: FileFilter): FileFilter = new SimpleFileFilter( file => accept(file) || filter.accept(file) )
- def && (filter: FileFilter): FileFilter = new SimpleFileFilter( file => accept(file) && filter.accept(file) )
- def -- (filter: FileFilter): FileFilter = new SimpleFileFilter( file => accept(file) && !filter.accept(file) )
- def unary_- : FileFilter = new SimpleFileFilter( file => !accept(file) )
+ def || (filter: FileFilter): FileFilter = new SimpleFileFilter( file => accept(file) || filter.accept(file) )
+ def && (filter: FileFilter): FileFilter = new SimpleFileFilter( file => accept(file) && filter.accept(file) )
+ def -- (filter: FileFilter): FileFilter = new SimpleFileFilter( file => accept(file) && !filter.accept(file) )
+ def unary_- : FileFilter = new SimpleFileFilter( file => !accept(file) )
}
trait NameFilter extends FileFilter with NotNull
{
- def accept(name: String): Boolean
- final def accept(file: File): Boolean = accept(file.getName)
- def | (filter: NameFilter): NameFilter = new SimpleFilter( name => accept(name) || filter.accept(name) )
- def & (filter: NameFilter): NameFilter = new SimpleFilter( name => accept(name) && filter.accept(name) )
- def - (filter: NameFilter): NameFilter = new SimpleFilter( name => accept(name) && !filter.accept(name) )
- override def unary_- : NameFilter = new SimpleFilter( name => !accept(name) )
+ def accept(name: String): Boolean
+ final def accept(file: File): Boolean = accept(file.getName)
+ def | (filter: NameFilter): NameFilter = new SimpleFilter( name => accept(name) || filter.accept(name) )
+ def & (filter: NameFilter): NameFilter = new SimpleFilter( name => accept(name) && filter.accept(name) )
+ def - (filter: NameFilter): NameFilter = new SimpleFilter( name => accept(name) && !filter.accept(name) )
+ override def unary_- : NameFilter = new SimpleFilter( name => !accept(name) )
}
object HiddenFileFilter extends FileFilter {
- def accept(file: File) = file.isHidden && file.getName != "."
+ def accept(file: File) = file.isHidden && file.getName != "."
}
object ExistsFileFilter extends FileFilter {
- def accept(file: File) = file.exists
+ def accept(file: File) = file.exists
}
object DirectoryFilter extends FileFilter {
- def accept(file: File) = file.isDirectory
+ def accept(file: File) = file.isDirectory
}
class SimpleFileFilter(val acceptFunction: File => Boolean) extends FileFilter
{
- def accept(file: File) = acceptFunction(file)
+ def accept(file: File) = acceptFunction(file)
}
class ExactFilter(val matchName: String) extends NameFilter
{
- def accept(name: String) = matchName == name
+ def accept(name: String) = matchName == name
}
class SimpleFilter(val acceptFunction: String => Boolean) extends NameFilter
{
- def accept(name: String) = acceptFunction(name)
+ def accept(name: String) = acceptFunction(name)
}
class PatternFilter(val pattern: Pattern) extends NameFilter
{
- def accept(name: String) = pattern.matcher(name).matches
+ def accept(name: String) = pattern.matcher(name).matches
}
object AllPassFilter extends NameFilter
{
- def accept(name: String) = true
+ def accept(name: String) = true
}
object NothingFilter extends NameFilter
{
- def accept(name: String) = false
+ def accept(name: String) = false
}
object GlobFilter
{
- implicit def apply(expression: String): NameFilter =
- {
- require(!expression.exists(java.lang.Character.isISOControl), "Control characters not allowed in filter expression.")
- if(expression == "*")
- AllPassFilter
- else if(expression.indexOf('*') < 0) // includes case where expression is empty
- new ExactFilter(expression)
- else
- new PatternFilter(Pattern.compile(expression.split("\\*", -1).map(quote).mkString(".*")))
- }
- private def quote(s: String) = if(s.isEmpty) "" else Pattern.quote(s.replaceAll("\n", """\n"""))
+ implicit def apply(expression: String): NameFilter =
+ {
+ require(!expression.exists(java.lang.Character.isISOControl), "Control characters not allowed in filter expression.")
+ if(expression == "*")
+ AllPassFilter
+ else if(expression.indexOf('*') < 0) // includes case where expression is empty
+ new ExactFilter(expression)
+ else
+ new PatternFilter(Pattern.compile(expression.split("\\*", -1).map(quote).mkString(".*")))
+ }
+ private def quote(s: String) = if(s.isEmpty) "" else Pattern.quote(s.replaceAll("\n", """\n"""))
}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/bundledevtool/src/main/scala/sbt/io/Pack.scala
----------------------------------------------------------------------
diff --git a/bundledevtool/src/main/scala/sbt/io/Pack.scala b/bundledevtool/src/main/scala/sbt/io/Pack.scala
index 562d443..c7dc287 100644
--- a/bundledevtool/src/main/scala/sbt/io/Pack.scala
+++ b/bundledevtool/src/main/scala/sbt/io/Pack.scala
@@ -30,29 +30,29 @@ import IO._
object Pack
{
- def pack(jarPath: File, out: File): Unit = pack(jarPath, out, defaultPackerOptions)
- def pack(jarPath: File, out: File, options: Iterable[(String, String)])
- {
- val packer = Pack200.newPacker
- import collection.JavaConversions._
- packer.properties ++= options
-
- Using.jarFile(false)(jarPath) { f =>
- Using.fileOutputStream()(out) { stream =>
- packer.pack(f, stream)
- }
- }
- }
- def unpack(packedPath: File, toJarPath: File)
- {
- val unpacker = Pack200.newUnpacker
- Using.fileOutputStream()(toJarPath) { fileStream =>
- Using.jarOutputStream(fileStream) { jarOut =>
- unpacker.unpack(packedPath, jarOut)
- }
- }
- }
- def defaultPackerOptions = scala.collection.immutable.Map()
+ def pack(jarPath: File, out: File): Unit = pack(jarPath, out, defaultPackerOptions)
+ def pack(jarPath: File, out: File, options: Iterable[(String, String)])
+ {
+ val packer = Pack200.newPacker
+ import collection.JavaConversions._
+ packer.properties ++= options
+
+ Using.jarFile(false)(jarPath) { f =>
+ Using.fileOutputStream()(out) { stream =>
+ packer.pack(f, stream)
+ }
+ }
+ }
+ def unpack(packedPath: File, toJarPath: File)
+ {
+ val unpacker = Pack200.newUnpacker
+ Using.fileOutputStream()(toJarPath) { fileStream =>
+ Using.jarOutputStream(fileStream) { jarOut =>
+ unpacker.unpack(packedPath, jarOut)
+ }
+ }
+ }
+ def defaultPackerOptions = scala.collection.immutable.Map()
}
import java.net.URL
@@ -60,41 +60,41 @@ import java.net.URL
* on scalaz and it is difficult to determine whether a jar is both signed and valid. */
object SignJar
{
- final class SignOption private[SignJar](val toList: List[String], val signOnly: Boolean)
- {
- override def toString = toList.mkString(" ")
- }
- def keyStore(url: URL) = new SignOption("-keystore" :: url.toExternalForm :: Nil, true)
- def signedJar(p: Path) = new SignOption("-signedjar" :: p.asFile.getAbsolutePath :: Nil, true)
- def verbose = new SignOption("-verbose" :: Nil, false)
- def sigFile(name: String) = new SignOption("-sigfile" :: name :: Nil, true)
- def storeType(t: String) = new SignOption("-storetype" :: t :: Nil, false)
- def provider(p: String) = new SignOption("-provider" :: p :: Nil, false)
- def providerName(p: String) = new SignOption("-providerName" :: p :: Nil, false)
- def storePassword(p: String) = new SignOption("-storepass" :: p :: Nil, true)
- def keyPassword(p: String) = new SignOption("-keypass" :: p :: Nil, true)
-
- private def VerifyOption = "-verify"
-
- /** Uses jarsigner to sign the given jar. */
- def sign(jarPath: File, alias: String, options: Seq[SignOption])(fork: (String, List[String]) => Int)
- {
- require(!alias.trim.isEmpty, "Alias cannot be empty")
- val arguments = options.toList.flatMap(_.toList) ::: jarPath.getAbsolutePath :: alias :: Nil
- execute("signing", arguments)(fork)
- }
- /** Uses jarsigner to verify the given jar.*/
- def verify(jarPath: File, options: Seq[SignOption])(fork: (String, List[String]) => Int)
- {
- val arguments = options.filter(!_.signOnly).toList.flatMap(_.toList) ::: VerifyOption :: jarPath.getAbsolutePath :: Nil
- execute("verifying", arguments)(fork)
- }
- private def execute(action: String, arguments: List[String])(fork: (String, List[String]) => Int)
- {
- val exitCode = fork(CommandName, arguments)
- if(exitCode != 0)
- error("Error " + action + " jar (exit code was " + exitCode + ".)")
- }
-
- private val CommandName = "jarsigner"
+ final class SignOption private[SignJar](val toList: List[String], val signOnly: Boolean)
+ {
+ override def toString = toList.mkString(" ")
+ }
+ def keyStore(url: URL) = new SignOption("-keystore" :: url.toExternalForm :: Nil, true)
+ def signedJar(p: Path) = new SignOption("-signedjar" :: p.asFile.getAbsolutePath :: Nil, true)
+ def verbose = new SignOption("-verbose" :: Nil, false)
+ def sigFile(name: String) = new SignOption("-sigfile" :: name :: Nil, true)
+ def storeType(t: String) = new SignOption("-storetype" :: t :: Nil, false)
+ def provider(p: String) = new SignOption("-provider" :: p :: Nil, false)
+ def providerName(p: String) = new SignOption("-providerName" :: p :: Nil, false)
+ def storePassword(p: String) = new SignOption("-storepass" :: p :: Nil, true)
+ def keyPassword(p: String) = new SignOption("-keypass" :: p :: Nil, true)
+
+ private def VerifyOption = "-verify"
+
+ /** Uses jarsigner to sign the given jar. */
+ def sign(jarPath: File, alias: String, options: Seq[SignOption])(fork: (String, List[String]) => Int)
+ {
+ require(!alias.trim.isEmpty, "Alias cannot be empty")
+ val arguments = options.toList.flatMap(_.toList) ::: jarPath.getAbsolutePath :: alias :: Nil
+ execute("signing", arguments)(fork)
+ }
+ /** Uses jarsigner to verify the given jar.*/
+ def verify(jarPath: File, options: Seq[SignOption])(fork: (String, List[String]) => Int)
+ {
+ val arguments = options.filter(!_.signOnly).toList.flatMap(_.toList) ::: VerifyOption :: jarPath.getAbsolutePath :: Nil
+ execute("verifying", arguments)(fork)
+ }
+ private def execute(action: String, arguments: List[String])(fork: (String, List[String]) => Int)
+ {
+ val exitCode = fork(CommandName, arguments)
+ if(exitCode != 0)
+ error("Error " + action + " jar (exit code was " + exitCode + ".)")
+ }
+
+ private val CommandName = "jarsigner"
}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/bundledevtool/src/main/scala/sbt/io/Path.scala
----------------------------------------------------------------------
diff --git a/bundledevtool/src/main/scala/sbt/io/Path.scala b/bundledevtool/src/main/scala/sbt/io/Path.scala
index ea9d6f9..44c8ae8 100644
--- a/bundledevtool/src/main/scala/sbt/io/Path.scala
+++ b/bundledevtool/src/main/scala/sbt/io/Path.scala
@@ -34,260 +34,260 @@ import scala.collection.{generic, immutable, mutable, TraversableLike}
* @see sbt.PathFinder*/
sealed abstract class Path extends PathFinder
{
- /** Creates a base directory for this path. This is used by copy and zip functions
- * to determine the relative path that should be used in the destination. For example,
- * if the following path is specified to be copied to directory 'd',
- *
- * <code>((a / b) ###) / x / y</code>
- *
- * the copied path would be
- *
- * <code>d / x / y</code>
- *
- * The <code>relativePath</code> method is used to return the relative path to the base directory. */
- override def ### : Path = new BaseDirectory(this)
- private[sbt] def addTo(pathSet: mutable.Set[Path])
- {
- if(asFile.exists)
- pathSet += this
- }
- override def / (component: String): Path = if(component == ".") this else new RelativePath(this, component)
- /** True if and only if the file represented by this path exists.*/
- def exists = asFile.exists
- /** True if and only if the file represented by this path is a directory.*/
- def isDirectory = asFile.isDirectory
- /** The last modified time of the file represented by this path.*/
- def lastModified = asFile.lastModified
- /* True if and only if file that this path represents exists and the file represented by the path 'p'
- * does not exist or was modified before the file for this path.*/
- def newerThan(p: Path): Boolean = exists && (!p.exists || lastModified > p.lastModified)
- /* True if and only if file that this path represents does not exist or the file represented by the path 'p'
- * exists and was modified after the file for this path.*/
- def olderThan(p: Path): Boolean = p newerThan this
- /** The file represented by this path.*/
- def asFile: File
- /** The file represented by this path converted to a <code>URL</code>.*/
- def asURL = asFile.toURI.toURL
- /** The string representation of this path relative to the base directory. The project directory is the
- * default base directory if one is not specified explicitly using the <code>###</code> operator.*/
- lazy val relativePath: String = relativePathString(sep.toString)
- def relativePathString(separator: String): String
- final def projectRelativePath: String = projectRelativePathString(sep.toString)
- def projectRelativePathString(separator: String): String
- def absolutePath: String = asFile.getAbsolutePath
- private[sbt] def prependTo(s: String): String
-
- /** The last component of this path.*/
- def name = asFile.getName
- /** The extension part of the name of this path. This is the part of the name after the last period, or the empty string if there is no period.*/
- def ext = baseAndExt._2
- /** The base of the name of this path. This is the part of the name before the last period, or the full name if there is no period.*/
- def base = baseAndExt._1
- def baseAndExt: (String, String) =
- {
- val nme = name
- val dot = nme.lastIndexOf('.')
- if(dot < 0) (nme, "") else (nme.substring(0, dot), nme.substring(dot+1))
- }
-
- /** Equality of Paths is defined in terms of the underlying <code>File</code>.*/
- override final def equals(other: Any) =
- other match
- {
- case op: Path => asFile == op.asFile
- case _ => false
- }
- /** The hash code of a Path is that of the underlying <code>File</code>.*/
- override final def hashCode = asFile.hashCode
+ /** Creates a base directory for this path. This is used by copy and zip functions
+ * to determine the relative path that should be used in the destination. For example,
+ * if the following path is specified to be copied to directory 'd',
+ *
+ * <code>((a / b) ###) / x / y</code>
+ *
+ * the copied path would be
+ *
+ * <code>d / x / y</code>
+ *
+ * The <code>relativePath</code> method is used to return the relative path to the base directory. */
+ override def ### : Path = new BaseDirectory(this)
+ private[sbt] def addTo(pathSet: mutable.Set[Path])
+ {
+ if(asFile.exists)
+ pathSet += this
+ }
+ override def / (component: String): Path = if(component == ".") this else new RelativePath(this, component)
+ /** True if and only if the file represented by this path exists.*/
+ def exists = asFile.exists
+ /** True if and only if the file represented by this path is a directory.*/
+ def isDirectory = asFile.isDirectory
+ /** The last modified time of the file represented by this path.*/
+ def lastModified = asFile.lastModified
+ /* True if and only if file that this path represents exists and the file represented by the path 'p'
+ * does not exist or was modified before the file for this path.*/
+ def newerThan(p: Path): Boolean = exists && (!p.exists || lastModified > p.lastModified)
+ /* True if and only if file that this path represents does not exist or the file represented by the path 'p'
+ * exists and was modified after the file for this path.*/
+ def olderThan(p: Path): Boolean = p newerThan this
+ /** The file represented by this path.*/
+ def asFile: File
+ /** The file represented by this path converted to a <code>URL</code>.*/
+ def asURL = asFile.toURI.toURL
+ /** The string representation of this path relative to the base directory. The project directory is the
+ * default base directory if one is not specified explicitly using the <code>###</code> operator.*/
+ lazy val relativePath: String = relativePathString(sep.toString)
+ def relativePathString(separator: String): String
+ final def projectRelativePath: String = projectRelativePathString(sep.toString)
+ def projectRelativePathString(separator: String): String
+ def absolutePath: String = asFile.getAbsolutePath
+ private[sbt] def prependTo(s: String): String
+
+ /** The last component of this path.*/
+ def name = asFile.getName
+ /** The extension part of the name of this path. This is the part of the name after the last period, or the empty string if there is no period.*/
+ def ext = baseAndExt._2
+ /** The base of the name of this path. This is the part of the name before the last period, or the full name if there is no period.*/
+ def base = baseAndExt._1
+ def baseAndExt: (String, String) =
+ {
+ val nme = name
+ val dot = nme.lastIndexOf('.')
+ if(dot < 0) (nme, "") else (nme.substring(0, dot), nme.substring(dot+1))
+ }
+
+ /** Equality of Paths is defined in terms of the underlying <code>File</code>.*/
+ override final def equals(other: Any) =
+ other match
+ {
+ case op: Path => asFile == op.asFile
+ case _ => false
+ }
+ /** The hash code of a Path is that of the underlying <code>File</code>.*/
+ override final def hashCode = asFile.hashCode
}
private final class BaseDirectory(private[sbt] val path: Path) extends Path
{
- override def ### : Path = this
- override def toString = path.toString
- def asFile = path.asFile
- def relativePathString(separator: String) = ""
- def projectRelativePathString(separator: String) = path.projectRelativePathString(separator)
- private[sbt] def prependTo(s: String) = "." + sep + s
+ override def ### : Path = this
+ override def toString = path.toString
+ def asFile = path.asFile
+ def relativePathString(separator: String) = ""
+ def projectRelativePathString(separator: String) = path.projectRelativePathString(separator)
+ private[sbt] def prependTo(s: String) = "." + sep + s
}
private[sbt] final class FilePath(file: File) extends Path
{
- lazy val asFile = absolute(file)
- override def toString = absolutePath
- def relativePathString(separator: String) = asFile.getName
- def projectRelativePathString(separator: String) = relativePathString(separator)
- private[sbt] def prependTo(s: String) = absolutePath + sep + s
+ lazy val asFile = absolute(file)
+ override def toString = absolutePath
+ def relativePathString(separator: String) = asFile.getName
+ def projectRelativePathString(separator: String) = relativePathString(separator)
+ private[sbt] def prependTo(s: String) = absolutePath + sep + s
}
// toRoot is the path between this and the root project path and is used for toString
private[sbt] final class ProjectDirectory(file: File, toRoot: Option[Path]) extends Path
{
- def this(file: File) = this(file, None)
- lazy val asFile = absolute(file)
- override def toString = foldToRoot(_.toString, ".")
- def relativePathString(separator: String) = ""
- def projectRelativePathString(separator: String) = ""
- private[sbt] def prependTo(s: String) = foldToRoot(_.prependTo(s), "." + sep + s)
- private[sbt] def foldToRoot[T](f: Path => T, orElse: T) = toRoot.map(f).getOrElse(orElse)
+ def this(file: File) = this(file, None)
+ lazy val asFile = absolute(file)
+ override def toString = foldToRoot(_.toString, ".")
+ def relativePathString(separator: String) = ""
+ def projectRelativePathString(separator: String) = ""
+ private[sbt] def prependTo(s: String) = foldToRoot(_.prependTo(s), "." + sep + s)
+ private[sbt] def foldToRoot[T](f: Path => T, orElse: T) = toRoot.map(f).getOrElse(orElse)
}
private[sbt] final class RelativePath(val parentPath: Path, val component: String) extends Path
{
- checkComponent(component)
- override def toString = parentPath prependTo component
- lazy val asFile = new File(parentPath.asFile, component)
- private[sbt] def prependTo(s: String) = parentPath prependTo (component + sep + s)
- def relativePathString(separator: String) = relative(parentPath.relativePathString(separator), separator)
- def projectRelativePathString(separator: String) = relative(parentPath.projectRelativePathString(separator), separator)
- private def relative(parentRelative: String, separator: String) =
- {
- if(parentRelative.isEmpty)
- component
- else
- parentRelative + separator + component
- }
+ checkComponent(component)
+ override def toString = parentPath prependTo component
+ lazy val asFile = new File(parentPath.asFile, component)
+ private[sbt] def prependTo(s: String) = parentPath prependTo (component + sep + s)
+ def relativePathString(separator: String) = relative(parentPath.relativePathString(separator), separator)
+ def projectRelativePathString(separator: String) = relative(parentPath.projectRelativePathString(separator), separator)
+ private def relative(parentRelative: String, separator: String) =
+ {
+ if(parentRelative.isEmpty)
+ component
+ else
+ parentRelative + separator + component
+ }
}
- import java.io.File
- import File.pathSeparator
+ import java.io.File
+ import File.pathSeparator
trait PathExtra extends Alternatives with Mapper
{
- implicit def fileToPath(file: File): Path = Path.fromFile(file)
- implicit def pathToFile(path: Path): File = path.asFile
- implicit def pathsToFiles[CC[X] <: TraversableLike[X,CC[X]]](cc: CC[Path])(implicit cb: generic.CanBuildFrom[CC[Path], File, CC[File]]): CC[File] =
- cc.map(_.asFile)
- implicit def filesToPaths[CC[X] <: TraversableLike[X,CC[X]]](cc: CC[File])(implicit cb: generic.CanBuildFrom[CC[File], Path, CC[Path]]): CC[Path] =
- cc.map(fileToPath)
- implicit def filesToFinder(cc: Traversable[File]): PathFinder = finder(cc)
- implicit def pathsToFinder(cc: Traversable[Path]): PathFinder = lazyPathFinder(cc)
+ implicit def fileToPath(file: File): Path = Path.fromFile(file)
+ implicit def pathToFile(path: Path): File = path.asFile
+ implicit def pathsToFiles[CC[X] <: TraversableLike[X,CC[X]]](cc: CC[Path])(implicit cb: generic.CanBuildFrom[CC[Path], File, CC[File]]): CC[File] =
+ cc.map(_.asFile)
+ implicit def filesToPaths[CC[X] <: TraversableLike[X,CC[X]]](cc: CC[File])(implicit cb: generic.CanBuildFrom[CC[File], Path, CC[Path]]): CC[Path] =
+ cc.map(fileToPath)
+ implicit def filesToFinder(cc: Traversable[File]): PathFinder = finder(cc)
+ implicit def pathsToFinder(cc: Traversable[Path]): PathFinder = lazyPathFinder(cc)
}
object Path extends PathExtra
{
- def fileProperty(name: String) = Path.fromFile(System.getProperty(name))
- def userHome = fileProperty("user.home")
-
- def absolute(file: File) = new File(file.toURI.normalize).getAbsoluteFile
- /** Constructs a String representation of <code>Path</code>s. The absolute path String of each <code>Path</code> is
- * separated by the platform's path separator.*/
- def makeString(paths: Iterable[Path]): String = makeString(paths, pathSeparator)
- /** Constructs a String representation of <code>Path</code>s. The absolute path String of each <code>Path</code> is
- * separated by the given separator String.*/
- def makeString(paths: Iterable[Path], sep: String): String = paths.map(_.absolutePath).mkString(sep)
+ def fileProperty(name: String) = Path.fromFile(System.getProperty(name))
+ def userHome = fileProperty("user.home")
+
+ def absolute(file: File) = new File(file.toURI.normalize).getAbsoluteFile
+ /** Constructs a String representation of <code>Path</code>s. The absolute path String of each <code>Path</code> is
+ * separated by the platform's path separator.*/
+ def makeString(paths: Iterable[Path]): String = makeString(paths, pathSeparator)
+ /** Constructs a String representation of <code>Path</code>s. The absolute path String of each <code>Path</code> is
+ * separated by the given separator String.*/
+ def makeString(paths: Iterable[Path], sep: String): String = paths.map(_.absolutePath).mkString(sep)
- def makeString(paths: Seq[File]): String = makeString(paths, pathSeparator)
- def makeString(paths: Seq[File], sep: String): String = paths.map(_.getAbsolutePath).mkString(sep)
-
- /** Constructs a String representation of <code>Path</code>s. The relative path String of each <code>Path</code> is
- * separated by the platform's path separator.*/
- def makeRelativeString(paths: Iterable[Path]): String = paths.map(_.relativePathString(sep.toString)).mkString(pathSeparator)
-
- def splitString(projectPath: Path, value: String): Iterable[Path] =
- {
- for(pathString <- pathSplit(value) if pathString.length > 0) yield
- Path.fromString(projectPath, pathString)
- }
-
- /** A <code>PathFinder</code> that always produces the empty set of <code>Path</code>s.*/
- def emptyPathFinder =
- new PathFinder
- {
- private[sbt] def addTo(pathSet: mutable.Set[Path]) {}
- }
- /** A <code>PathFinder</code> that selects the paths provided by the <code>paths</code> argument, which is
- * reevaluated on each call to the <code>PathFinder</code>'s <code>get</code> method. */
- def lazyPathFinder(paths: => Traversable[Path]): PathFinder =
- new PathFinder
- {
- private[sbt] def addTo(pathSet: mutable.Set[Path]) = pathSet ++= paths
- }
- def finder(files: => Traversable[File]): PathFinder = lazyPathFinder { fromFiles(files) }
-
- /** The separator character of the platform.*/
- val sep = java.io.File.separatorChar
-
- /** Checks the string to verify that it is a legal path component. The string must be non-empty,
- * not a slash, and not '.' or '..'.*/
- def checkComponent(c: String): String =
- {
- require(c.length > 0, "Path component must not be empty")
- require(c.indexOf('/') == -1, "Path component '" + c + "' must not have forward slashes in it")
- require(c.indexOf('\\') == -1, "Path component '" + c + "' must not have backslashes in it")
- require(c != "..", "Path component cannot be '..'")
- require(c != ".", "Path component cannot be '.'")
- c
- }
- /** Converts a path string relative to the given base path to a <code>Path</code>. */
- def fromString(basePath: Path, value: String): Path =
- {
- if(value.isEmpty)
- basePath
- else
- {
- val f = new File(value)
- if(f.isAbsolute)
- fromFile(f)
- else
- {
- val components = value.split("""[/\\]""")
- (basePath /: components)( (path, component) => path / component )
- }
- }
- }
- def baseAncestor(path: Path): Option[Path] =
- path match
- {
- case pd: ProjectDirectory => None
- case fp: FilePath => None
- case rp: RelativePath => baseAncestor(rp.parentPath)
- case b: BaseDirectory => Some(b.path)
- }
-
- def relativize(basePath: Path, path: Path): Option[Path] = relativize(basePath, path.asFile)
- def relativize(basePath: Path, file: File): Option[Path] =
- basePathString(basePath) flatMap { baseString => relativize(basePath, baseString, file) }
- def relativize(basePath: Path, basePathString: String, file: File): Option[Path] =
- {
- val pathString = file.getAbsolutePath
- if(pathString.startsWith(basePathString))
- Some(fromString(basePath, pathString.substring(basePathString.length)))
- else
- None
- }
- def relativizeFile(baseFile: File, file: File): Option[File] = relativize(baseFile, file).map { path => new File(path) }
- private[sbt] def relativize(baseFile: File, file: File): Option[String] =
- {
- val pathString = file.getAbsolutePath
- baseFileString(baseFile) flatMap
- {
- baseString =>
- {
- if(pathString.startsWith(baseString))
- Some(pathString.substring(baseString.length))
- else
- None
- }
- }
- }
- private[sbt] def basePathString(basePath: Path): Option[String] = baseFileString(basePath.asFile)
- private def baseFileString(baseFile: File): Option[String] =
- {
- if(baseFile.isDirectory)
- {
- val cp = baseFile.getAbsolutePath
- assert(cp.length > 0)
- if(cp.charAt(cp.length - 1) == File.separatorChar)
- Some(cp)
- else
- Some(cp + File.separatorChar)
- }
- else
- None
- }
- def fromFile(file: String): Path = fromFile(new File(file))
- def fromFile(file: File): Path = new FilePath(file)
- import collection.generic.{CanBuildFrom, FilterMonadic}
- def fromFiles[Repr, That](files: FilterMonadic[File, Repr])(implicit bf: CanBuildFrom[Repr, Path, That]): That = files.map(fromFile)
+ def makeString(paths: Seq[File]): String = makeString(paths, pathSeparator)
+ def makeString(paths: Seq[File], sep: String): String = paths.map(_.getAbsolutePath).mkString(sep)
+
+ /** Constructs a String representation of <code>Path</code>s. The relative path String of each <code>Path</code> is
+ * separated by the platform's path separator.*/
+ def makeRelativeString(paths: Iterable[Path]): String = paths.map(_.relativePathString(sep.toString)).mkString(pathSeparator)
+
+ def splitString(projectPath: Path, value: String): Iterable[Path] =
+ {
+ for(pathString <- pathSplit(value) if pathString.length > 0) yield
+ Path.fromString(projectPath, pathString)
+ }
+
+ /** A <code>PathFinder</code> that always produces the empty set of <code>Path</code>s.*/
+ def emptyPathFinder =
+ new PathFinder
+ {
+ private[sbt] def addTo(pathSet: mutable.Set[Path]) {}
+ }
+ /** A <code>PathFinder</code> that selects the paths provided by the <code>paths</code> argument, which is
+ * reevaluated on each call to the <code>PathFinder</code>'s <code>get</code> method. */
+ def lazyPathFinder(paths: => Traversable[Path]): PathFinder =
+ new PathFinder
+ {
+ private[sbt] def addTo(pathSet: mutable.Set[Path]) = pathSet ++= paths
+ }
+ def finder(files: => Traversable[File]): PathFinder = lazyPathFinder { fromFiles(files) }
+
+ /** The separator character of the platform.*/
+ val sep = java.io.File.separatorChar
+
+ /** Checks the string to verify that it is a legal path component. The string must be non-empty,
+ * not a slash, and not '.' or '..'.*/
+ def checkComponent(c: String): String =
+ {
+ require(c.length > 0, "Path component must not be empty")
+ require(c.indexOf('/') == -1, "Path component '" + c + "' must not have forward slashes in it")
+ require(c.indexOf('\\') == -1, "Path component '" + c + "' must not have backslashes in it")
+ require(c != "..", "Path component cannot be '..'")
+ require(c != ".", "Path component cannot be '.'")
+ c
+ }
+ /** Converts a path string relative to the given base path to a <code>Path</code>. */
+ def fromString(basePath: Path, value: String): Path =
+ {
+ if(value.isEmpty)
+ basePath
+ else
+ {
+ val f = new File(value)
+ if(f.isAbsolute)
+ fromFile(f)
+ else
+ {
+ val components = value.split("""[/\\]""")
+ (basePath /: components)( (path, component) => path / component )
+ }
+ }
+ }
+ def baseAncestor(path: Path): Option[Path] =
+ path match
+ {
+ case pd: ProjectDirectory => None
+ case fp: FilePath => None
+ case rp: RelativePath => baseAncestor(rp.parentPath)
+ case b: BaseDirectory => Some(b.path)
+ }
+
+ def relativize(basePath: Path, path: Path): Option[Path] = relativize(basePath, path.asFile)
+ def relativize(basePath: Path, file: File): Option[Path] =
+ basePathString(basePath) flatMap { baseString => relativize(basePath, baseString, file) }
+ def relativize(basePath: Path, basePathString: String, file: File): Option[Path] =
+ {
+ val pathString = file.getAbsolutePath
+ if(pathString.startsWith(basePathString))
+ Some(fromString(basePath, pathString.substring(basePathString.length)))
+ else
+ None
+ }
+ def relativizeFile(baseFile: File, file: File): Option[File] = relativize(baseFile, file).map { path => new File(path) }
+ private[sbt] def relativize(baseFile: File, file: File): Option[String] =
+ {
+ val pathString = file.getAbsolutePath
+ baseFileString(baseFile) flatMap
+ {
+ baseString =>
+ {
+ if(pathString.startsWith(baseString))
+ Some(pathString.substring(baseString.length))
+ else
+ None
+ }
+ }
+ }
+ private[sbt] def basePathString(basePath: Path): Option[String] = baseFileString(basePath.asFile)
+ private def baseFileString(baseFile: File): Option[String] =
+ {
+ if(baseFile.isDirectory)
+ {
+ val cp = baseFile.getAbsolutePath
+ assert(cp.length > 0)
+ if(cp.charAt(cp.length - 1) == File.separatorChar)
+ Some(cp)
+ else
+ Some(cp + File.separatorChar)
+ }
+ else
+ None
+ }
+ def fromFile(file: String): Path = fromFile(new File(file))
+ def fromFile(file: File): Path = new FilePath(file)
+ import collection.generic.{CanBuildFrom, FilterMonadic}
+ def fromFiles[Repr, That](files: FilterMonadic[File, Repr])(implicit bf: CanBuildFrom[Repr, Path, That]): That = files.map(fromFile)
- def getFiles(files: Traversable[Path]): immutable.Set[File] = files.map(_.asFile).toSet
- def getURLs(files: Traversable[Path]): Array[URL] = files.map(_.asURL).toArray
+ def getFiles(files: Traversable[Path]): immutable.Set[File] = files.map(_.asFile).toSet
+ def getURLs(files: Traversable[Path]): Array[URL] = files.map(_.asURL).toArray
- def toURLs(files: Seq[File]): Array[URL] = files.map(_.toURI.toURL).toArray
+ def toURLs(files: Seq[File]): Array[URL] = files.map(_.toURI.toURL).toArray
}
/** A path finder constructs a set of paths. The set is evaluated by a call to the <code>get</code>
@@ -295,147 +295,147 @@ object Path extends PathExtra
* has changed.*/
sealed abstract class PathFinder extends NotNull
{
- /** The union of the paths found by this <code>PathFinder</code> with the paths found by 'paths'.*/
- def +++(paths: PathFinder): PathFinder = new Paths(this, paths)
- /** Excludes all paths from <code>excludePaths</code> from the paths selected by this <code>PathFinder</code>.*/
- def ---(excludePaths: PathFinder): PathFinder = new ExcludePaths(this, excludePaths)
- /** Constructs a new finder that selects all paths with a name that matches <code>filter</code> and are
- * descendents of paths selected by this finder.*/
- def **(filter: FileFilter): PathFinder = new DescendentOrSelfPathFinder(this, filter)
- def *** : PathFinder = **(AllPassFilter)
- /** Constructs a new finder that selects all paths with a name that matches <code>filter</code> and are
- * immediate children of paths selected by this finder.*/
- def *(filter: FileFilter): PathFinder = new ChildPathFinder(this, filter)
- /** Constructs a new finder that selects all paths with name <code>literal</code> that are immediate children
- * of paths selected by this finder.*/
- def / (literal: String): PathFinder = new ChildPathFinder(this, new ExactFilter(literal))
- /** Constructs a new finder that selects all paths with name <code>literal</code> that are immediate children
- * of paths selected by this finder.*/
- final def \ (literal: String): PathFinder = this / literal
+ /** The union of the paths found by this <code>PathFinder</code> with the paths found by 'paths'.*/
+ def +++(paths: PathFinder): PathFinder = new Paths(this, paths)
+ /** Excludes all paths from <code>excludePaths</code> from the paths selected by this <code>PathFinder</code>.*/
+ def ---(excludePaths: PathFinder): PathFinder = new ExcludePaths(this, excludePaths)
+ /** Constructs a new finder that selects all paths with a name that matches <code>filter</code> and are
+ * descendents of paths selected by this finder.*/
+ def **(filter: FileFilter): PathFinder = new DescendentOrSelfPathFinder(this, filter)
+ def *** : PathFinder = **(AllPassFilter)
+ /** Constructs a new finder that selects all paths with a name that matches <code>filter</code> and are
+ * immediate children of paths selected by this finder.*/
+ def *(filter: FileFilter): PathFinder = new ChildPathFinder(this, filter)
+ /** Constructs a new finder that selects all paths with name <code>literal</code> that are immediate children
+ * of paths selected by this finder.*/
+ def / (literal: String): PathFinder = new ChildPathFinder(this, new ExactFilter(literal))
+ /** Constructs a new finder that selects all paths with name <code>literal</code> that are immediate children
+ * of paths selected by this finder.*/
+ final def \ (literal: String): PathFinder = this / literal
- /** Makes the paths selected by this finder into base directories.
- * @see Path.###
- */
- def ### : PathFinder = new BasePathFinder(this)
+ /** Makes the paths selected by this finder into base directories.
+ * @see Path.###
+ */
+ def ### : PathFinder = new BasePathFinder(this)
- def x_![T](mapper: File => Option[T]): Traversable[(File,T)] = x(mapper, false)
- /** Applies `mapper` to each path selected by this PathFinder and returns the path paired with the non-empty result.
- * If the result is empty (None) and `errorIfNone` is true, an exception is thrown.
- * If `errorIfNone` is false, the path is dropped from the returned Traversable.*/
- def x[T](mapper: File => Option[T], errorIfNone: Boolean = true): Traversable[(File,T)] =
- {
- val apply = if(errorIfNone) mapper | fail else mapper
- for(file <- getFiles; mapped <- apply(file)) yield (file, mapped)
- }
- /** Pairs each path selected by this PathFinder with its relativePath.*/
- def xx: Traversable[(File, String)] = get.map(path => (path.asFile, path.relativePath))
+ def x_![T](mapper: File => Option[T]): Traversable[(File,T)] = x(mapper, false)
+ /** Applies `mapper` to each path selected by this PathFinder and returns the path paired with the non-empty result.
+ * If the result is empty (None) and `errorIfNone` is true, an exception is thrown.
+ * If `errorIfNone` is false, the path is dropped from the returned Traversable.*/
+ def x[T](mapper: File => Option[T], errorIfNone: Boolean = true): Traversable[(File,T)] =
+ {
+ val apply = if(errorIfNone) mapper | fail else mapper
+ for(file <- getFiles; mapped <- apply(file)) yield (file, mapped)
+ }
+ /** Pairs each path selected by this PathFinder with its relativePath.*/
+ def xx: Traversable[(File, String)] = get.map(path => (path.asFile, path.relativePath))
- /** Selects all descendent paths with a name that matches <code>include</code> and do not have an intermediate
- * path with a name that matches <code>intermediateExclude</code>. Typical usage is:
- *
- * <code>descendentsExcept("*.jar", ".svn")</code>*/
- def descendentsExcept(include: FileFilter, intermediateExclude: FileFilter): PathFinder =
- (this ** include) --- (this ** intermediateExclude ** include)
-
- /** Evaluates this finder. The set returned by this method will reflect the underlying filesystem at the
- * time of calling. If the filesystem changes, two calls to this method might be different.*/
- final def get: immutable.Set[Path] =
- {
- val pathSet = new mutable.HashSet[Path]
- addTo(pathSet)
- pathSet.toSet
- }
- /** Only keeps paths for which `f` returns true. It is non-strict, so it is not evaluated until the returned finder is evaluated.*/
- final def filter(f: Path => Boolean): PathFinder = Path.lazyPathFinder(get.filter(f))
- /* Non-strict flatMap: no evaluation occurs until the returned finder is evaluated.*/
- final def flatMap(f: Path => PathFinder): PathFinder = Path.lazyPathFinder(get.flatMap(p => f(p).get))
- /** Evaluates this finder and converts the results to an `Array` of `URL`s..*/
- final def getURLs: Array[URL] = Path.getURLs(get)
- /** Evaluates this finder and converts the results to a `Set` of `File`s.*/
- final def getFiles: immutable.Set[File] = Path.getFiles(get)
- /** Evaluates this finder and converts the results to a `Set` of absolute path strings.*/
- final def getPaths: immutable.Set[String] = strictMap(_.absolutePath)
- /** Evaluates this finder and converts the results to a `Set` of relative path strings.*/
- final def getRelativePaths: immutable.Set[String] = strictMap(_.relativePath)
- final def strictMap[T](f: Path => T): immutable.Set[T] = get.map(f).toSet
- private[sbt] def addTo(pathSet: mutable.Set[Path])
+ /** Selects all descendent paths with a name that matches <code>include</code> and do not have an intermediate
+ * path with a name that matches <code>intermediateExclude</code>. Typical usage is:
+ *
+ * <code>descendentsExcept("*.jar", ".svn")</code>*/
+ def descendentsExcept(include: FileFilter, intermediateExclude: FileFilter): PathFinder =
+ (this ** include) --- (this ** intermediateExclude ** include)
+
+ /** Evaluates this finder. The set returned by this method will reflect the underlying filesystem at the
+ * time of calling. If the filesystem changes, two calls to this method might be different.*/
+ final def get: immutable.Set[Path] =
+ {
+ val pathSet = new mutable.HashSet[Path]
+ addTo(pathSet)
+ pathSet.toSet
+ }
+ /** Only keeps paths for which `f` returns true. It is non-strict, so it is not evaluated until the returned finder is evaluated.*/
+ final def filter(f: Path => Boolean): PathFinder = Path.lazyPathFinder(get.filter(f))
+ /* Non-strict flatMap: no evaluation occurs until the returned finder is evaluated.*/
+ final def flatMap(f: Path => PathFinder): PathFinder = Path.lazyPathFinder(get.flatMap(p => f(p).get))
+ /** Evaluates this finder and converts the results to an `Array` of `URL`s..*/
+ final def getURLs: Array[URL] = Path.getURLs(get)
+ /** Evaluates this finder and converts the results to a `Set` of `File`s.*/
+ final def getFiles: immutable.Set[File] = Path.getFiles(get)
+ /** Evaluates this finder and converts the results to a `Set` of absolute path strings.*/
+ final def getPaths: immutable.Set[String] = strictMap(_.absolutePath)
+ /** Evaluates this finder and converts the results to a `Set` of relative path strings.*/
+ final def getRelativePaths: immutable.Set[String] = strictMap(_.relativePath)
+ final def strictMap[T](f: Path => T): immutable.Set[T] = get.map(f).toSet
+ private[sbt] def addTo(pathSet: mutable.Set[Path])
- /** Create a PathFinder from this one where each path has a unique name.
- * A single path is arbitrarily selected from the set of paths with the same name.*/
- def distinct: PathFinder = Path.lazyPathFinder((Map() ++ get.map(p => (p.asFile.getName, p))) .values.toList )
+ /** Create a PathFinder from this one where each path has a unique name.
+ * A single path is arbitrarily selected from the set of paths with the same name.*/
+ def distinct: PathFinder = Path.lazyPathFinder((Map() ++ get.map(p => (p.asFile.getName, p))) .values.toList )
- /** Constructs a string by evaluating this finder, converting the resulting Paths to absolute path strings, and joining them with the platform path separator.*/
- final def absString = Path.makeString(get)
- /** Constructs a string by evaluating this finder, converting the resulting Paths to relative path strings, and joining them with the platform path separator.*/
- final def relativeString = Path.makeRelativeString(get)
- /** Constructs a debugging string for this finder by evaluating it and separating paths by newlines.*/
- override def toString = get.mkString("\n ", "\n ","")
+ /** Constructs a string by evaluating this finder, converting the resulting Paths to absolute path strings, and joining them with the platform path separator.*/
+ final def absString = Path.makeString(get)
+ /** Constructs a string by evaluating this finder, converting the resulting Paths to relative path strings, and joining them with the platform path separator.*/
+ final def relativeString = Path.makeRelativeString(get)
+ /** Constructs a debugging string for this finder by evaluating it and separating paths by newlines.*/
+ override def toString = get.mkString("\n ", "\n ","")
}
private class BasePathFinder(base: PathFinder) extends PathFinder
{
- private[sbt] def addTo(pathSet: mutable.Set[Path])
- {
- for(path <- base.get)
- pathSet += (path ###)
- }
+ private[sbt] def addTo(pathSet: mutable.Set[Path])
+ {
+ for(path <- base.get)
+ pathSet += (path ###)
+ }
}
private abstract class FilterPath extends PathFinder with FileFilter
{
- def parent: PathFinder
- def filter: FileFilter
- final def accept(file: File) = filter.accept(file)
-
- protected def handlePath(path: Path, pathSet: mutable.Set[Path])
- {
- for(matchedFile <- wrapNull(path.asFile.listFiles(this)))
- pathSet += path / matchedFile.getName
- }
+ def parent: PathFinder
+ def filter: FileFilter
+ final def accept(file: File) = filter.accept(file)
+
+ protected def handlePath(path: Path, pathSet: mutable.Set[Path])
+ {
+ for(matchedFile <- wrapNull(path.asFile.listFiles(this)))
+ pathSet += path / matchedFile.getName
+ }
}
private class DescendentOrSelfPathFinder(val parent: PathFinder, val filter: FileFilter) extends FilterPath
{
- private[sbt] def addTo(pathSet: mutable.Set[Path])
- {
- for(path <- parent.get)
- {
- if(accept(path.asFile))
- pathSet += path
- handlePathDescendent(path, pathSet)
- }
- }
- private def handlePathDescendent(path: Path, pathSet: mutable.Set[Path])
- {
- handlePath(path, pathSet)
- for(childDirectory <- wrapNull(path.asFile.listFiles(DirectoryFilter)))
- handlePathDescendent(path / childDirectory.getName, pathSet)
- }
+ private[sbt] def addTo(pathSet: mutable.Set[Path])
+ {
+ for(path <- parent.get)
+ {
+ if(accept(path.asFile))
+ pathSet += path
+ handlePathDescendent(path, pathSet)
+ }
+ }
+ private def handlePathDescendent(path: Path, pathSet: mutable.Set[Path])
+ {
+ handlePath(path, pathSet)
+ for(childDirectory <- wrapNull(path.asFile.listFiles(DirectoryFilter)))
+ handlePathDescendent(path / childDirectory.getName, pathSet)
+ }
}
private class ChildPathFinder(val parent: PathFinder, val filter: FileFilter) extends FilterPath
{
- private[sbt] def addTo(pathSet: mutable.Set[Path])
- {
- for(path <- parent.get)
- handlePath(path, pathSet)
- }
+ private[sbt] def addTo(pathSet: mutable.Set[Path])
+ {
+ for(path <- parent.get)
+ handlePath(path, pathSet)
+ }
}
private class Paths(a: PathFinder, b: PathFinder) extends PathFinder
{
- private[sbt] def addTo(pathSet: mutable.Set[Path])
- {
- a.addTo(pathSet)
- b.addTo(pathSet)
- }
+ private[sbt] def addTo(pathSet: mutable.Set[Path])
+ {
+ a.addTo(pathSet)
+ b.addTo(pathSet)
+ }
}
private class ExcludePaths(include: PathFinder, exclude: PathFinder) extends PathFinder
{
- private[sbt] def addTo(pathSet: mutable.Set[Path])
- {
- val includeSet = new mutable.HashSet[Path]
- include.addTo(includeSet)
-
- val excludeSet = new mutable.HashSet[Path]
- exclude.addTo(excludeSet)
-
- includeSet --= excludeSet
- pathSet ++= includeSet
- }
+ private[sbt] def addTo(pathSet: mutable.Set[Path])
+ {
+ val includeSet = new mutable.HashSet[Path]
+ include.addTo(includeSet)
+
+ val excludeSet = new mutable.HashSet[Path]
+ exclude.addTo(excludeSet)
+
+ includeSet --= excludeSet
+ pathSet ++= includeSet
+ }
}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/bundledevtool/src/main/scala/sbt/io/PathMapper.scala
----------------------------------------------------------------------
diff --git a/bundledevtool/src/main/scala/sbt/io/PathMapper.scala b/bundledevtool/src/main/scala/sbt/io/PathMapper.scala
index c48b3fb..3a48360 100644
--- a/bundledevtool/src/main/scala/sbt/io/PathMapper.scala
+++ b/bundledevtool/src/main/scala/sbt/io/PathMapper.scala
@@ -24,58 +24,58 @@
*/
package sbt
- import java.io.File
+ import java.io.File
trait Mapper
{
- type PathMap = File => Option[String]
- type FileMap = File => Option[File]
+ type PathMap = File => Option[String]
+ type FileMap = File => Option[File]
- val basic: PathMap = f => Some(f.getPath)
- def relativeTo(base: File): PathMap = IO.relativize(base, _)
- def rebase(oldBase: File, newBase0: String): PathMap =
- {
- val newBase = normalizeBase(newBase0)
- (file: File) =>
- if(file == oldBase)
- Some( if(newBase.isEmpty) "." else newBase )
- else
- IO.relativize(oldBase, file).map(newBase + _)
- }
- def fail: Any => Nothing = f => error("No mapping for " + f)
- val flat: PathMap = f => Some(f.getName)
- def flatRebase(newBase0: String): PathMap =
- {
- val newBase = normalizeBase(newBase0)
- f => Some(newBase + f.getName)
- }
- def some[A,B](f: A => B): A => Some[B] = x => Some(f(x))
+ val basic: PathMap = f => Some(f.getPath)
+ def relativeTo(base: File): PathMap = IO.relativize(base, _)
+ def rebase(oldBase: File, newBase0: String): PathMap =
+ {
+ val newBase = normalizeBase(newBase0)
+ (file: File) =>
+ if(file == oldBase)
+ Some( if(newBase.isEmpty) "." else newBase )
+ else
+ IO.relativize(oldBase, file).map(newBase + _)
+ }
+ def fail: Any => Nothing = f => error("No mapping for " + f)
+ val flat: PathMap = f => Some(f.getName)
+ def flatRebase(newBase0: String): PathMap =
+ {
+ val newBase = normalizeBase(newBase0)
+ f => Some(newBase + f.getName)
+ }
+ def some[A,B](f: A => B): A => Some[B] = x => Some(f(x))
- def normalizeBase(base: String) = if(!base.isEmpty && !base.endsWith("/")) base + "/" else base
+ def normalizeBase(base: String) = if(!base.isEmpty && !base.endsWith("/")) base + "/" else base
- def abs: FileMap = f => Some(f.getAbsoluteFile)
- def resolve(newDirectory: File): FileMap = file => Some(new File(newDirectory, file.getPath))
- def rebase(oldBase: File, newBase: File): FileMap =
- file =>
- if(file == oldBase)
- Some(newBase)
- else
- IO.relativize(oldBase, file) map { r => new File(newBase, r) }
+ def abs: FileMap = f => Some(f.getAbsoluteFile)
+ def resolve(newDirectory: File): FileMap = file => Some(new File(newDirectory, file.getPath))
+ def rebase(oldBase: File, newBase: File): FileMap =
+ file =>
+ if(file == oldBase)
+ Some(newBase)
+ else
+ IO.relativize(oldBase, file) map { r => new File(newBase, r) }
- def flat(newDirectory: File): FileMap = file => Some(new File(newDirectory, file.getName))
+ def flat(newDirectory: File): FileMap = file => Some(new File(newDirectory, file.getName))
}
trait Alternative[A,B] { def | (g: A => Option[B]): A => Option[B] }
trait Alternatives
{
- implicit def alternative[A,B](f:A => Option[B]): Alternative[A,B] =
- new Alternative[A,B] { def | (g: A => Option[B]) =
- (a: A) => f(a) orElse g(a)
- }
- final def alternatives[A,B](alts: Seq[A => Option[B]]): A => Option[B] =
- alts match
- {
- case Seq(f, fs @ _*) => f | alternatives(fs)
- case Seq() => a => None
- }
+ implicit def alternative[A,B](f:A => Option[B]): Alternative[A,B] =
+ new Alternative[A,B] { def | (g: A => Option[B]) =
+ (a: A) => f(a) orElse g(a)
+ }
+ final def alternatives[A,B](alts: Seq[A => Option[B]]): A => Option[B] =
+ alts match
+ {
+ case Seq(f, fs @ _*) => f | alternatives(fs)
+ case Seq() => a => None
+ }
}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/bundledevtool/src/main/scala/sbt/io/Resources.scala
----------------------------------------------------------------------
diff --git a/bundledevtool/src/main/scala/sbt/io/Resources.scala b/bundledevtool/src/main/scala/sbt/io/Resources.scala
index cdb560a..d8fb52f 100644
--- a/bundledevtool/src/main/scala/sbt/io/Resources.scala
+++ b/bundledevtool/src/main/scala/sbt/io/Resources.scala
@@ -30,59 +30,59 @@ import Resources.error
object Resources
{
- def apply(basePath: String) =
- {
- require(basePath.startsWith("/"))
- val resource = getClass.getResource(basePath)
- if(resource == null)
- error("Resource base directory '" + basePath + "' not on classpath.")
- else
- {
- val file = toFile(resource)
- if(file.exists)
- new Resources(file)
- else
- error("Resource base directory '" + basePath + "' does not exist.")
- }
- }
- def error(msg: String) = throw new ResourcesException(msg)
- private val LoadErrorPrefix = "Error loading initial project: "
+ def apply(basePath: String) =
+ {
+ require(basePath.startsWith("/"))
+ val resource = getClass.getResource(basePath)
+ if(resource == null)
+ error("Resource base directory '" + basePath + "' not on classpath.")
+ else
+ {
+ val file = toFile(resource)
+ if(file.exists)
+ new Resources(file)
+ else
+ error("Resource base directory '" + basePath + "' does not exist.")
+ }
+ }
+ def error(msg: String) = throw new ResourcesException(msg)
+ private val LoadErrorPrefix = "Error loading initial project: "
}
class ResourcesException(msg: String) extends Exception(msg)
class Resources(val baseDirectory: File)
{
- import Resources._
- // The returned directory is not actually read-only, but it should be treated that way
- def readOnlyResourceDirectory(group: String, name: String): File =
- {
- val groupDirectory = new File(baseDirectory, group)
- if(groupDirectory.isDirectory)
- {
- val resourceDirectory = new File(groupDirectory, name)
- if(resourceDirectory.isDirectory)
- resourceDirectory
- else
- error("Resource directory '" + name + "' in group '" + group + "' not found.")
- }
- else
- error("Group '" + group + "' not found.")
- }
- def readWriteResourceDirectory[T](group: String, name: String)(withDirectory: File => T): T =
- {
- val file = readOnlyResourceDirectory(group, name)
- readWriteResourceDirectory(file)(withDirectory)
- }
+ import Resources._
+ // The returned directory is not actually read-only, but it should be treated that way
+ def readOnlyResourceDirectory(group: String, name: String): File =
+ {
+ val groupDirectory = new File(baseDirectory, group)
+ if(groupDirectory.isDirectory)
+ {
+ val resourceDirectory = new File(groupDirectory, name)
+ if(resourceDirectory.isDirectory)
+ resourceDirectory
+ else
+ error("Resource directory '" + name + "' in group '" + group + "' not found.")
+ }
+ else
+ error("Group '" + group + "' not found.")
+ }
+ def readWriteResourceDirectory[T](group: String, name: String)(withDirectory: File => T): T =
+ {
+ val file = readOnlyResourceDirectory(group, name)
+ readWriteResourceDirectory(file)(withDirectory)
+ }
- def readWriteResourceDirectory[T](readOnly: File)(withDirectory: File => T): T =
- {
- require(readOnly.isDirectory)
- def readWrite(readOnly: File)(temporary: File): T =
- {
- val readWriteDirectory = new File(temporary, readOnly.getName)
- copyDirectory(readOnly, readWriteDirectory)
- withDirectory(readWriteDirectory)
- }
- withTemporaryDirectory(readWrite(readOnly))
- }
+ def readWriteResourceDirectory[T](readOnly: File)(withDirectory: File => T): T =
+ {
+ require(readOnly.isDirectory)
+ def readWrite(readOnly: File)(temporary: File): T =
+ {
+ val readWriteDirectory = new File(temporary, readOnly.getName)
+ copyDirectory(readOnly, readWriteDirectory)
+ withDirectory(readWriteDirectory)
+ }
+ withTemporaryDirectory(readWrite(readOnly))
+ }
}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/bundledevtool/src/main/scala/sbt/io/SourceModificationWatch.scala
----------------------------------------------------------------------
diff --git a/bundledevtool/src/main/scala/sbt/io/SourceModificationWatch.scala b/bundledevtool/src/main/scala/sbt/io/SourceModificationWatch.scala
index 9795905..bd22211 100644
--- a/bundledevtool/src/main/scala/sbt/io/SourceModificationWatch.scala
+++ b/bundledevtool/src/main/scala/sbt/io/SourceModificationWatch.scala
@@ -24,46 +24,46 @@
*/
package sbt
- import annotation.tailrec
+ import annotation.tailrec
object SourceModificationWatch
{
- @tailrec def watch(sourcesFinder: PathFinder, pollDelaySec: Int, state: WatchState)(terminationCondition: => Boolean): (Boolean, WatchState) =
- {
- import state._
+ @tailrec def watch(sourcesFinder: PathFinder, pollDelaySec: Int, state: WatchState)(terminationCondition: => Boolean): (Boolean, WatchState) =
+ {
+ import state._
- def sourceFiles: Iterable[java.io.File] = sourcesFinder.getFiles
- val (lastModifiedTime, fileCount) =
- ( (0L, 0) /: sourceFiles) {(acc, file) => /*println("processing "+file);*/ (math.max(acc._1, file.lastModified), acc._2 + 1)}
+ def sourceFiles: Iterable[java.io.File] = sourcesFinder.getFiles
+ val (lastModifiedTime, fileCount) =
+ ( (0L, 0) /: sourceFiles) {(acc, file) => /*println("processing "+file);*/ (math.max(acc._1, file.lastModified), acc._2 + 1)}
- //println("lastModifiedTime:"+new java.util.Date(lastModifiedTime))
- //println("lastModifiedTime - lastCallbackCallTime"+(lastModifiedTime - lastCallbackCallTime))
- val sourcesModified =
- lastModifiedTime > lastCallbackCallTime ||
- previousFileCount != fileCount
+ //println("lastModifiedTime:"+new java.util.Date(lastModifiedTime))
+ //println("lastModifiedTime - lastCallbackCallTime"+(lastModifiedTime - lastCallbackCallTime))
+ val sourcesModified =
+ lastModifiedTime > lastCallbackCallTime ||
+ previousFileCount != fileCount
- val (triggered, newCallbackCallTime) =
- if (sourcesModified) {
- (false, System.currentTimeMillis)
- }
- else
- (awaitingQuietPeriod, lastCallbackCallTime)
+ val (triggered, newCallbackCallTime) =
+ if (sourcesModified) {
+ (false, System.currentTimeMillis)
+ }
+ else
+ (awaitingQuietPeriod, lastCallbackCallTime)
- val newState = new WatchState(newCallbackCallTime, fileCount, sourcesModified, if(triggered) count + 1 else count)
- if(triggered)
- (true, newState)
- else
- {
- Thread.sleep(pollDelaySec * 1000)
- if(terminationCondition)
- (false, newState)
- else
- watch(sourcesFinder, pollDelaySec, newState)(terminationCondition)
- }
- }
+ val newState = new WatchState(newCallbackCallTime, fileCount, sourcesModified, if(triggered) count + 1 else count)
+ if(triggered)
+ (true, newState)
+ else
+ {
+ Thread.sleep(pollDelaySec * 1000)
+ if(terminationCondition)
+ (false, newState)
+ else
+ watch(sourcesFinder, pollDelaySec, newState)(terminationCondition)
+ }
+ }
}
final class WatchState(val lastCallbackCallTime: Long, val previousFileCount: Int, val awaitingQuietPeriod:Boolean, val count: Int)
object WatchState
{
- def empty = new WatchState(0L, 0, false, 0)
+ def empty = new WatchState(0L, 0, false, 0)
}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/bundledevtool/src/main/scala/sbt/io/Using.scala
----------------------------------------------------------------------
diff --git a/bundledevtool/src/main/scala/sbt/io/Using.scala b/bundledevtool/src/main/scala/sbt/io/Using.scala
index c87f955..0b1698c 100644
--- a/bundledevtool/src/main/scala/sbt/io/Using.scala
+++ b/bundledevtool/src/main/scala/sbt/io/Using.scala
@@ -39,81 +39,81 @@ import Using._
abstract class Using[Source, T]
{
- protected def open(src: Source): T
- def apply[R](src: Source)(f: T => R): R =
- {
- val resource = open(src)
- try { f(resource) }
- finally { close(resource) }
- }
- protected def close(out: T): Unit
+ protected def open(src: Source): T
+ def apply[R](src: Source)(f: T => R): R =
+ {
+ val resource = open(src)
+ try { f(resource) }
+ finally { close(resource) }
+ }
+ protected def close(out: T): Unit
}
import scala.reflect.{Manifest => SManifest}
abstract class WrapUsing[Source, T](implicit srcMf: SManifest[Source], targetMf: SManifest[T]) extends Using[Source, T]
{
- protected def label[S](m: SManifest[S]) = m.erasure.getSimpleName
- protected def openImpl(source: Source): T
- protected final def open(source: Source): T =
- translate("Error wrapping " + label(srcMf) + " in " + label(targetMf) + ": ") { openImpl(source) }
+ protected def label[S](m: SManifest[S]) = m.erasure.getSimpleName
+ protected def openImpl(source: Source): T
+ protected final def open(source: Source): T =
+ translate("Error wrapping " + label(srcMf) + " in " + label(targetMf) + ": ") { openImpl(source) }
}
trait OpenFile[T] extends Using[File, T]
{
- protected def openImpl(file: File): T
- protected final def open(file: File): T =
- {
- val parent = file.getParentFile
- if(parent != null)
- IO.createDirectory(parent)
- openImpl(file)
- }
+ protected def openImpl(file: File): T
+ protected final def open(file: File): T =
+ {
+ val parent = file.getParentFile
+ if(parent != null)
+ IO.createDirectory(parent)
+ openImpl(file)
+ }
}
object Using
{
- def wrap[Source, T<: Closeable](openF: Source => T)(implicit srcMf: SManifest[Source], targetMf: SManifest[T]): Using[Source,T] =
- wrap(openF, closeCloseable)
- def wrap[Source, T](openF: Source => T, closeF: T => Unit)(implicit srcMf: SManifest[Source], targetMf: SManifest[T]): Using[Source,T] =
- new WrapUsing[Source, T]
- {
- def openImpl(source: Source) = openF(source)
- def close(t: T) = closeF(t)
- }
+ def wrap[Source, T<: Closeable](openF: Source => T)(implicit srcMf: SManifest[Source], targetMf: SManifest[T]): Using[Source,T] =
+ wrap(openF, closeCloseable)
+ def wrap[Source, T](openF: Source => T, closeF: T => Unit)(implicit srcMf: SManifest[Source], targetMf: SManifest[T]): Using[Source,T] =
+ new WrapUsing[Source, T]
+ {
+ def openImpl(source: Source) = openF(source)
+ def close(t: T) = closeF(t)
+ }
- def resource[Source, T <: Closeable](openF: Source => T): Using[Source,T] =
- resource(openF, closeCloseable)
- def resource[Source, T](openF: Source => T, closeF: T => Unit): Using[Source,T] =
- new Using[Source,T]
- {
- def open(s: Source) = openF(s)
- def close(s: T) = closeF(s)
- }
- def file[T <: Closeable](openF: File => T): OpenFile[T] = file(openF, closeCloseable)
- def file[T](openF: File => T, closeF: T => Unit): OpenFile[T] =
- new OpenFile[T]
- {
- def openImpl(file: File) = openF(file)
- def close(t: T) = closeF(t)
- }
- private def closeCloseable[T <: Closeable]: T => Unit = _.close()
+ def resource[Source, T <: Closeable](openF: Source => T): Using[Source,T] =
+ resource(openF, closeCloseable)
+ def resource[Source, T](openF: Source => T, closeF: T => Unit): Using[Source,T] =
+ new Using[Source,T]
+ {
+ def open(s: Source) = openF(s)
+ def close(s: T) = closeF(s)
+ }
+ def file[T <: Closeable](openF: File => T): OpenFile[T] = file(openF, closeCloseable)
+ def file[T](openF: File => T, closeF: T => Unit): OpenFile[T] =
+ new OpenFile[T]
+ {
+ def openImpl(file: File) = openF(file)
+ def close(t: T) = closeF(t)
+ }
+ private def closeCloseable[T <: Closeable]: T => Unit = _.close()
- def bufferedOutputStream = wrap( (out: OutputStream) => new BufferedOutputStream(out) )
- def bufferedInputStream = wrap( (in: InputStream) => new BufferedInputStream(in) )
- def fileOutputStream(append: Boolean = false) = file(f => new BufferedOutputStream(new FileOutputStream(f, append)))
- def fileInputStream = file(f => new BufferedInputStream(new FileInputStream(f)))
- def urlInputStream = resource( (u: URL) => translate("Error opening " + u + ": ")(u.openStream))
- def fileOutputChannel = file(f => new FileOutputStream(f).getChannel)
- def fileInputChannel = file(f => new FileInputStream(f).getChannel)
- def fileWriter(charset: Charset = IO.utf8, append: Boolean = false) =
- file(f => new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f, append), charset)) )
- def fileReader(charset: Charset) = file(f => new BufferedReader(new InputStreamReader(new FileInputStream(f), charset)) )
- def jarFile(verify: Boolean) = file(f => new JarFile(f, verify), (_: JarFile).close())
- def zipFile = file(f => new ZipFile(f), (_: ZipFile).close())
- def streamReader = wrap{ (_: (InputStream, Charset)) match { case (in, charset) => new InputStreamReader(in, charset) } }
- def gzipInputStream = wrap( (in: InputStream) => new GZIPInputStream(in, 8192) )
- def zipInputStream = wrap( (in: InputStream) => new ZipInputStream(in))
- def zipOutputStream = wrap( (out: OutputStream) => new ZipOutputStream(out))
- def gzipOutputStream = wrap((out: OutputStream) => new GZIPOutputStream(out, 8192), (_: GZIPOutputStream).finish())
- def jarOutputStream = wrap( (out: OutputStream) => new JarOutputStream(out))
- def jarInputStream = wrap( (in: InputStream) => new JarInputStream(in))
- def zipEntry(zip: ZipFile) = resource( (entry: ZipEntry) =>
- translate("Error opening " + entry.getName + " in " + zip + ": ") { zip.getInputStream(entry) } )
+ def bufferedOutputStream = wrap( (out: OutputStream) => new BufferedOutputStream(out) )
+ def bufferedInputStream = wrap( (in: InputStream) => new BufferedInputStream(in) )
+ def fileOutputStream(append: Boolean = false) = file(f => new BufferedOutputStream(new FileOutputStream(f, append)))
+ def fileInputStream = file(f => new BufferedInputStream(new FileInputStream(f)))
+ def urlInputStream = resource( (u: URL) => translate("Error opening " + u + ": ")(u.openStream))
+ def fileOutputChannel = file(f => new FileOutputStream(f).getChannel)
+ def fileInputChannel = file(f => new FileInputStream(f).getChannel)
+ def fileWriter(charset: Charset = IO.utf8, append: Boolean = false) =
+ file(f => new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f, append), charset)) )
+ def fileReader(charset: Charset) = file(f => new BufferedReader(new InputStreamReader(new FileInputStream(f), charset)) )
+ def jarFile(verify: Boolean) = file(f => new JarFile(f, verify), (_: JarFile).close())
+ def zipFile = file(f => new ZipFile(f), (_: ZipFile).close())
+ def streamReader = wrap{ (_: (InputStream, Charset)) match { case (in, charset) => new InputStreamReader(in, charset) } }
+ def gzipInputStream = wrap( (in: InputStream) => new GZIPInputStream(in, 8192) )
+ def zipInputStream = wrap( (in: InputStream) => new ZipInputStream(in))
+ def zipOutputStream = wrap( (out: OutputStream) => new ZipOutputStream(out))
+ def gzipOutputStream = wrap((out: OutputStream) => new GZIPOutputStream(out, 8192), (_: GZIPOutputStream).finish())
+ def jarOutputStream = wrap( (out: OutputStream) => new JarOutputStream(out))
+ def jarInputStream = wrap( (in: InputStream) => new JarInputStream(in))
+ def zipEntry(zip: ZipFile) = resource( (entry: ZipEntry) =>
+ translate("Error opening " + entry.getName + " in " + zip + ": ") { zip.getInputStream(entry) } )
}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/jaxrs.stanbol.fragments/src/main/scala/org/apache/clerezza/jaxrs/stanbol/webfragements/WebFragmentRunner.scala
----------------------------------------------------------------------
diff --git a/jaxrs.stanbol.fragments/src/main/scala/org/apache/clerezza/jaxrs/stanbol/webfragements/WebFragmentRunner.scala b/jaxrs.stanbol.fragments/src/main/scala/org/apache/clerezza/jaxrs/stanbol/webfragements/WebFragmentRunner.scala
index b40d430..ab23e75 100644
--- a/jaxrs.stanbol.fragments/src/main/scala/org/apache/clerezza/jaxrs/stanbol/webfragements/WebFragmentRunner.scala
+++ b/jaxrs.stanbol.fragments/src/main/scala/org/apache/clerezza/jaxrs/stanbol/webfragements/WebFragmentRunner.scala
@@ -229,13 +229,13 @@ class WebFragmentRunner extends javax.servlet.Filter with GlobalMenuItemsProvide
}
override def doFilter(request: ServletRequest, response: ServletResponse,
- chain: FilterChain){
- chain.doFilter(request, response);
- }
+ chain: FilterChain){
+ chain.doFilter(request, response);
+ }
- override def destroy() {
+ override def destroy() {
winkRequestProcessor.unbindComponent(contextResolverImpl)
- }
+ }
def getMenuItems() : java.util.Set[GlobalMenuItem] = {
@@ -249,10 +249,10 @@ class WebFragmentRunner extends javax.servlet.Filter with GlobalMenuItemsProvide
def wrapped = servletContext;
new ServletContext() {
def getServletContextName() :String = { wrapped.getServletContextName()}
- def removeAttribute(name: String) :Unit = { wrapped.removeAttribute(name)}
- def setAttribute(name: String, value: Any) :Unit = { wrapped.setAttribute(name, value)}
- def getAttributeNames() :java.util.Enumeration[_] = { wrapped.getAttributeNames()}
- def getAttribute(name: String) :Object = {
+ def removeAttribute(name: String) :Unit = { wrapped.removeAttribute(name)}
+ def setAttribute(name: String, value: Any) :Unit = { wrapped.setAttribute(name, value)}
+ def getAttributeNames() :java.util.Enumeration[_] = { wrapped.getAttributeNames()}
+ def getAttribute(name: String) :Object = {
val result = wrapped.getAttribute(name)
if (result != null) {
result
@@ -263,29 +263,29 @@ class WebFragmentRunner extends javax.servlet.Filter with GlobalMenuItemsProvide
} else null
}
}
- def getInitParameterNames() :java.util.Enumeration[_] = { wrapped.getInitParameterNames()}
- def getInitParameter(name: String) :String = { wrapped.getInitParameter(name)}
- def getServerInfo() :String = { wrapped.getServerInfo()}
- def getRealPath(name: String) :String = { wrapped.getRealPath(name)}
- def log(message: String, exception: Throwable) :Unit = { wrapped.log(message,exception)}
- def log(exception: Exception, message: String) :Unit = { wrapped.log(exception, message)}
- def log(message: String) :Unit = { wrapped.log(message)}
- @Deprecated
- def getServletNames() :java.util.Enumeration[_] = { wrapped.getServletNames()}
- @Deprecated
- def getServlets() :java.util.Enumeration[_] = { wrapped.getServlets()}
- @Deprecated
- def getServlet(name: String) :javax.servlet.Servlet = { wrapped.getServlet(name)}
- def getNamedDispatcher(name: String) :javax.servlet.RequestDispatcher = { wrapped.getNamedDispatcher(name)}
- def getRequestDispatcher(path: String) :javax.servlet.RequestDispatcher = { wrapped.getRequestDispatcher(path)}
- def getResourceAsStream(path: String) :java.io.InputStream = { wrapped.getResourceAsStream(path)}
- def getResource(path: String) :java.net.URL = { wrapped.getResource(path)}
- def getResourcePaths(path: String) :java.util.Set[_] = { wrapped.getResourcePaths(path)}
- def getMimeType(file: String) :String = { wrapped.getMimeType(file)}
- def getMinorVersion() :Int = { wrapped.getMajorVersion()}
- def getMajorVersion() :Int = { wrapped.getMajorVersion()}
- def getContext(uripath: String) :javax.servlet.ServletContext = { wrapped.getContext(uripath)}
- def getContextPath() :String = { wrapped.getContextPath()}
+ def getInitParameterNames() :java.util.Enumeration[_] = { wrapped.getInitParameterNames()}
+ def getInitParameter(name: String) :String = { wrapped.getInitParameter(name)}
+ def getServerInfo() :String = { wrapped.getServerInfo()}
+ def getRealPath(name: String) :String = { wrapped.getRealPath(name)}
+ def log(message: String, exception: Throwable) :Unit = { wrapped.log(message,exception)}
+ def log(exception: Exception, message: String) :Unit = { wrapped.log(exception, message)}
+ def log(message: String) :Unit = { wrapped.log(message)}
+ @Deprecated
+ def getServletNames() :java.util.Enumeration[_] = { wrapped.getServletNames()}
+ @Deprecated
+ def getServlets() :java.util.Enumeration[_] = { wrapped.getServlets()}
+ @Deprecated
+ def getServlet(name: String) :javax.servlet.Servlet = { wrapped.getServlet(name)}
+ def getNamedDispatcher(name: String) :javax.servlet.RequestDispatcher = { wrapped.getNamedDispatcher(name)}
+ def getRequestDispatcher(path: String) :javax.servlet.RequestDispatcher = { wrapped.getRequestDispatcher(path)}
+ def getResourceAsStream(path: String) :java.io.InputStream = { wrapped.getResourceAsStream(path)}
+ def getResource(path: String) :java.net.URL = { wrapped.getResource(path)}
+ def getResourcePaths(path: String) :java.util.Set[_] = { wrapped.getResourcePaths(path)}
+ def getMimeType(file: String) :String = { wrapped.getMimeType(file)}
+ def getMinorVersion() :Int = { wrapped.getMajorVersion()}
+ def getMajorVersion() :Int = { wrapped.getMajorVersion()}
+ def getContext(uripath: String) :javax.servlet.ServletContext = { wrapped.getContext(uripath)}
+ def getContextPath() :String = { wrapped.getContextPath()}
}
}
}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/osgi.services/src/main/scala/org/apache/clerezza/osgi/services/ActivationHelper.scala
----------------------------------------------------------------------
diff --git a/osgi.services/src/main/scala/org/apache/clerezza/osgi/services/ActivationHelper.scala b/osgi.services/src/main/scala/org/apache/clerezza/osgi/services/ActivationHelper.scala
index 3bb8fad..0239818 100644
--- a/osgi.services/src/main/scala/org/apache/clerezza/osgi/services/ActivationHelper.scala
+++ b/osgi.services/src/main/scala/org/apache/clerezza/osgi/services/ActivationHelper.scala
@@ -30,84 +30,84 @@ import org.osgi.framework.{ServiceRegistration, BundleContext, BundleActivator}
*/
trait ActivationHelper extends BundleActivator {
- /**
- * this is intended to be used exclusively in the argument to the register-methods
- */
- protected var context: BundleContext= null
+ /**
+ * this is intended to be used exclusively in the argument to the register-methods
+ */
+ protected var context: BundleContext= null
- /**
- * Registers a JAX-RS Root Resource
- */
- protected def registerRootResource(rootResource: =>Object) {
- registerService(rootResource, classOf[Object], "javax.ws.rs" -> true)
- }
+ /**
+ * Registers a JAX-RS Root Resource
+ */
+ protected def registerRootResource(rootResource: =>Object) {
+ registerService(rootResource, classOf[Object], "javax.ws.rs" -> true)
+ }
- /**
- * Register a Renderlet
- * Note: renderlet must implement org.apache.clerezza.platform.typerendering.TypeRenderlet, argument not decalred on
- * this type to avoid dependency
- */
- protected def registerRenderlet(renderlet: =>Object) {
- registerServiceStringInterfaces(renderlet, Seq("org.apache.clerezza.platform.typerendering.TypeRenderlet"), Map[String, Any]())
- }
+ /**
+ * Register a Renderlet
+ * Note: renderlet must implement org.apache.clerezza.platform.typerendering.TypeRenderlet, argument not decalred on
+ * this type to avoid dependency
+ */
+ protected def registerRenderlet(renderlet: =>Object) {
+ registerServiceStringInterfaces(renderlet, Seq("org.apache.clerezza.platform.typerendering.TypeRenderlet"), Map[String, Any]())
+ }
- /**
- * Register a TypeHandler
- */
- protected def registerTypeHandler(typeHandler: => Object) {
- registerService(typeHandler, classOf[Object], "org.apache.clerezza.platform.typehandler" -> true)
- }
+ /**
+ * Register a TypeHandler
+ */
+ protected def registerTypeHandler(typeHandler: => Object) {
+ registerService(typeHandler, classOf[Object], "org.apache.clerezza.platform.typehandler" -> true)
+ }
- /**
- * Register a service exposing a specified interface with an arbitrary number of
- * arguments
- */
- protected def registerService(instance: => AnyRef, interface:Class[_],
- arguments: (String, Any)*) {
- registerService(instance, Seq(interface), Map(arguments:_*))
- }
+ /**
+ * Register a service exposing a specified interface with an arbitrary number of
+ * arguments
+ */
+ protected def registerService(instance: => AnyRef, interface:Class[_],
+ arguments: (String, Any)*) {
+ registerService(instance, Seq(interface), Map(arguments:_*))
+ }
- /**
- * Registers a service for a Seq of interfaces and a map of arguments
- */
- protected def registerService(instance: => AnyRef, interfaces: Seq[Class[_]],
- arguments: Map[String, Any]) {
- registerServiceStringInterfaces(instance, for (i <- interfaces) yield i.getName, arguments)
- }
- /**
- * Registers a service for a Seq of interfaces and a map of arguments
- */
- private def registerServiceStringInterfaces(instance: => AnyRef, interfaces: Seq[String],
- arguments: Map[String, Any]) {
- managedServices ::= ((() => instance, interfaces, arguments))
- }
+ /**
+ * Registers a service for a Seq of interfaces and a map of arguments
+ */
+ protected def registerService(instance: => AnyRef, interfaces: Seq[Class[_]],
+ arguments: Map[String, Any]) {
+ registerServiceStringInterfaces(instance, for (i <- interfaces) yield i.getName, arguments)
+ }
+ /**
+ * Registers a service for a Seq of interfaces and a map of arguments
+ */
+ private def registerServiceStringInterfaces(instance: => AnyRef, interfaces: Seq[String],
+ arguments: Map[String, Any]) {
+ managedServices ::= ((() => instance, interfaces, arguments))
+ }
- /**
- * invoked by the OSGi environment when the bundle is started, this method registers
- * the services for which the register-methods hqave been called (during object construction)
- */
- def start(context: BundleContext) {
- this.context = context
- registeredServices = Nil
- for (entry <- managedServices) {
- val args = asJavaDictionary(mutable.Map(entry._3.toSeq:_*))
- registeredServices ::= context.registerService(
- entry._2.toArray, entry._1(), args)
- }
- this.context = null
- }
+ /**
+ * invoked by the OSGi environment when the bundle is started, this method registers
+ * the services for which the register-methods hqave been called (during object construction)
+ */
+ def start(context: BundleContext) {
+ this.context = context
+ registeredServices = Nil
+ for (entry <- managedServices) {
+ val args = asJavaDictionary(mutable.Map(entry._3.toSeq:_*))
+ registeredServices ::= context.registerService(
+ entry._2.toArray, entry._1(), args)
+ }
+ this.context = null
+ }
- /**
- * called when the bundle is stopped, this method unregisters the provided service
- */
- def stop(context: BundleContext) {
- for(sr <- registeredServices) {
- sr.unregister();
- }
- registeredServices = null
- }
+ /**
+ * called when the bundle is stopped, this method unregisters the provided service
+ */
+ def stop(context: BundleContext) {
+ for(sr <- registeredServices) {
+ sr.unregister();
+ }
+ registeredServices = null
+ }
- private var managedServices: List[(() => Any, Seq[String], Map[String, Any])] = Nil
+ private var managedServices: List[(() => Any, Seq[String], Map[String, Any])] = Nil
- private var registeredServices: List[ServiceRegistration[_]] = null
+ private var registeredServices: List[ServiceRegistration[_]] = null
}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/osgi.services/src/main/scala/org/apache/clerezza/osgi/services/ServicesDsl.scala
----------------------------------------------------------------------
diff --git a/osgi.services/src/main/scala/org/apache/clerezza/osgi/services/ServicesDsl.scala b/osgi.services/src/main/scala/org/apache/clerezza/osgi/services/ServicesDsl.scala
index 15f952c..6d0f245 100644
--- a/osgi.services/src/main/scala/org/apache/clerezza/osgi/services/ServicesDsl.scala
+++ b/osgi.services/src/main/scala/org/apache/clerezza/osgi/services/ServicesDsl.scala
@@ -23,75 +23,75 @@ import scala.collection.JavaConversions._
class ServicesDsl(bundleContext: BundleContext) {
- /**
- * returns an instance of a service exposing T
- */
- def $[T](implicit m: Manifest[T]): T = {
- getService(m.erasure.asInstanceOf[Class[T]])
- }
+ /**
+ * returns an instance of a service exposing T
+ */
+ def $[T](implicit m: Manifest[T]): T = {
+ getService(m.erasure.asInstanceOf[Class[T]])
+ }
- private def getService[T](clazz : Class[T]) : T= {
- val serviceReference = bundleContext.getServiceReference(clazz.getName)
- if (serviceReference != null) {
- bundleContext.getService(serviceReference).asInstanceOf[T]
- } else null.asInstanceOf[T]
- }
+ private def getService[T](clazz : Class[T]) : T= {
+ val serviceReference = bundleContext.getServiceReference(clazz.getName)
+ if (serviceReference != null) {
+ bundleContext.getService(serviceReference).asInstanceOf[T]
+ } else null.asInstanceOf[T]
+ }
- /**
- * executes action as soon as a service exposing T is available, if such
- * a service is already available the action is executed immedtely and the
- * method blocks until the action finished executing, otherwise the method
- * returns and action will be executed when a respective becomes available.
- */
- def doWith[T](action: T => Unit)(implicit m: Manifest[T]) {
- val clazz = m.erasure.asInstanceOf[Class[T]]
- val service = getService(clazz)
- if (service != null) {
- action(service)
- } else {
- lazy val serviceListener: ServiceListener = new ServiceListener {
- def serviceChanged(e: ServiceEvent) = {
- if (e.getType == ServiceEvent.REGISTERED) {
- bundleContext.removeServiceListener(serviceListener)
- action(bundleContext.getService(e.getServiceReference).asInstanceOf[T])
- }
- }
- }
- bundleContext.addServiceListener(serviceListener,
- "("+Constants.OBJECTCLASS+"="+clazz.getName+")")
- }
- }
+ /**
+ * executes action as soon as a service exposing T is available, if such
+ * a service is already available the action is executed immedtely and the
+ * method blocks until the action finished executing, otherwise the method
+ * returns and action will be executed when a respective becomes available.
+ */
+ def doWith[T](action: T => Unit)(implicit m: Manifest[T]) {
+ val clazz = m.erasure.asInstanceOf[Class[T]]
+ val service = getService(clazz)
+ if (service != null) {
+ action(service)
+ } else {
+ lazy val serviceListener: ServiceListener = new ServiceListener {
+ def serviceChanged(e: ServiceEvent) = {
+ if (e.getType == ServiceEvent.REGISTERED) {
+ bundleContext.removeServiceListener(serviceListener)
+ action(bundleContext.getService(e.getServiceReference).asInstanceOf[T])
+ }
+ }
+ }
+ bundleContext.addServiceListener(serviceListener,
+ "("+Constants.OBJECTCLASS+"="+clazz.getName+")")
+ }
+ }
- def doWith[T,U](action: (T,U) => Unit)(implicit mt: Manifest[T], mu: Manifest[U]) {
- doWith[T] {
- t: T => {
- val clazz = mu.erasure.asInstanceOf[Class[U]]
- val service = getService(clazz)
- if (service != null) {
- action(t, service)
- } else {
- doWith[U,T] {
- (iu: U, it: T) => action(it,iu)
- }
- }
- }
- }
- }
+ def doWith[T,U](action: (T,U) => Unit)(implicit mt: Manifest[T], mu: Manifest[U]) {
+ doWith[T] {
+ t: T => {
+ val clazz = mu.erasure.asInstanceOf[Class[U]]
+ val service = getService(clazz)
+ if (service != null) {
+ action(t, service)
+ } else {
+ doWith[U,T] {
+ (iu: U, it: T) => action(it,iu)
+ }
+ }
+ }
+ }
+ }
- def doWith[T,U,V](action: (T,U,V) => Unit)(implicit mt: Manifest[T],
- mu: Manifest[U], mv: Manifest[V]) {
- doWith[T,U] {
- (t: T, u: U) => {
- val clazz = mv.erasure.asInstanceOf[Class[V]]
- val service: V = getService(clazz)
- if (service != null) {
- action(t, u, service)
- } else {
- doWith[U,V,T] {
- (iu: U, iv: V, it: T) => action(it,iu,iv)
- }
- }
- }
- }
- }
+ def doWith[T,U,V](action: (T,U,V) => Unit)(implicit mt: Manifest[T],
+ mu: Manifest[U], mv: Manifest[V]) {
+ doWith[T,U] {
+ (t: T, u: U) => {
+ val clazz = mv.erasure.asInstanceOf[Class[V]]
+ val service: V = getService(clazz)
+ if (service != null) {
+ action(t, u, service)
+ } else {
+ doWith[U,V,T] {
+ (iu: U, iv: V, it: T) => action(it,iu,iv)
+ }
+ }
+ }
+ }
+ }
}
[4/9] CLEREZZA-435: repaced tabs with spaces in scala files
Posted by re...@apache.org.
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/platform.shellcustomizer/src/main/scala/org/apache/clerezza/platform/shellcustomizer/PlatformDsl.scala
----------------------------------------------------------------------
diff --git a/platform.shellcustomizer/src/main/scala/org/apache/clerezza/platform/shellcustomizer/PlatformDsl.scala b/platform.shellcustomizer/src/main/scala/org/apache/clerezza/platform/shellcustomizer/PlatformDsl.scala
index 2964392..84f66cf 100644
--- a/platform.shellcustomizer/src/main/scala/org/apache/clerezza/platform/shellcustomizer/PlatformDsl.scala
+++ b/platform.shellcustomizer/src/main/scala/org/apache/clerezza/platform/shellcustomizer/PlatformDsl.scala
@@ -35,17 +35,17 @@ import clerezza.rdf.core.serializedform.Parser
*/
class PlatformDsl(outputStream: OutputStream, bundleContext: BundleContext) {
- private lazy val out = new PrintWriter(new OutputStreamWriter(outputStream, "utf-8"), true)
- private val serviceDsl = new ServicesDsl(bundleContext)
- import serviceDsl._
+ private lazy val out = new PrintWriter(new OutputStreamWriter(outputStream, "utf-8"), true)
+ private val serviceDsl = new ServicesDsl(bundleContext)
+ import serviceDsl._
- lazy val contentGraph = $[ContentGraphProvider].getContentGraph
- def parser = $[Parser]
+ lazy val contentGraph = $[ContentGraphProvider].getContentGraph
+ def parser = $[Parser]
- def uname {
- out println ("Clerezza on "+System.getProperty("java.vm.name"))
- }
+ def uname {
+ out println ("Clerezza on "+System.getProperty("java.vm.name"))
+ }
- //here we could add a command to set the debug output to the console for some packages
+ //here we could add a command to set the debug output to the console for some packages
}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/platform.style.default/src/main/scala/Activator.scala
----------------------------------------------------------------------
diff --git a/platform.style.default/src/main/scala/Activator.scala b/platform.style.default/src/main/scala/Activator.scala
index 1c22cac..a6a687b 100644
--- a/platform.style.default/src/main/scala/Activator.scala
+++ b/platform.style.default/src/main/scala/Activator.scala
@@ -38,9 +38,9 @@ import java.io.{FileOutputStream, FileInputStream, File}
*/
class Activator extends ActivationHelper {
- registerRenderlet(new GlobalMenuRenderlet)
- registerRenderlet(new HeadedPageRenderlet)
- registerRenderlet(new CollectionHeader)
- registerRenderlet(new RdfListRenderlet)
-
+ registerRenderlet(new GlobalMenuRenderlet)
+ registerRenderlet(new HeadedPageRenderlet)
+ registerRenderlet(new CollectionHeader)
+ registerRenderlet(new RdfListRenderlet)
+
}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/platform.style.default/src/main/scala/CollectionHeader.scala
----------------------------------------------------------------------
diff --git a/platform.style.default/src/main/scala/CollectionHeader.scala b/platform.style.default/src/main/scala/CollectionHeader.scala
index 4e7dd61..97fd00c 100644
--- a/platform.style.default/src/main/scala/CollectionHeader.scala
+++ b/platform.style.default/src/main/scala/CollectionHeader.scala
@@ -30,9 +30,9 @@ import org.apache.clerezza.rdf.scala.utils.Preamble._
*/
class CollectionHeader extends HeadedPageRenderlet {
- override val getRdfType = HIERARCHY.Collection
+ override val getRdfType = HIERARCHY.Collection
- override def defaultTitle(res: RichGraphNode) = (res*) + " (Collection)"
+ override def defaultTitle(res: RichGraphNode) = (res*) + " (Collection)"
}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/platform.style.default/src/main/scala/GlobalMenuRenderlet.scala
----------------------------------------------------------------------
diff --git a/platform.style.default/src/main/scala/GlobalMenuRenderlet.scala b/platform.style.default/src/main/scala/GlobalMenuRenderlet.scala
index 408a338..9db29a0 100644
--- a/platform.style.default/src/main/scala/GlobalMenuRenderlet.scala
+++ b/platform.style.default/src/main/scala/GlobalMenuRenderlet.scala
@@ -37,57 +37,57 @@ import org.apache.clerezza.rdf.ontologies.DC
*/
class GlobalMenuRenderlet extends SRenderlet {
- val getRdfType = RDFS.Resource
+ val getRdfType = RDFS.Resource
- override def getModePattern = "menu"
+ override def getModePattern = "menu"
- override def renderedPage(arguments: XmlResult.Arguments) = {
- new XmlResult(arguments) {
- def menuLink(href: String, label: String) =
- if ((res*).endsWith(href) || (res*).endsWith(href+"index")) {
- <a href={href} class="active">{label}</a>
- } else {
- <a href={href}>{label}</a>
- }
- override def content = {
- def menu(s: Any) = new UriRef("http://clerezza.org/2009/11/global-menu#"+s)
+ override def renderedPage(arguments: XmlResult.Arguments) = {
+ new XmlResult(arguments) {
+ def menuLink(href: String, label: String) =
+ if ((res*).endsWith(href) || (res*).endsWith(href+"index")) {
+ <a href={href} class="active">{label}</a>
+ } else {
+ <a href={href}>{label}</a>
+ }
+ override def content = {
+ def menu(s: Any) = new UriRef("http://clerezza.org/2009/11/global-menu#"+s)
def rdfs(s: Any) = new UriRef("http://www.w3.org/2000/01/rdf-schema#"+s)
def platform(s: Any) = new UriRef("http://clerezza.org/2009/08/platform#"+s)
def dct(s: Any) = new UriRef("http://purl.org/dc/terms/"+s)
<div class="column nav">
- <ul>
-
+ <ul>
+
- {for (menuItem <- res/menu("globalMenu")!!) yield
- <li class="top-nav-entry"><div class="title">
- {
- if ((menuItem/menu("path")).length > 0) {
- <a href={menuItem/menu("path")*}>{(menuItem/rdfs("label")*)}</a>
- } else {
- <a href="#" onclick="return false">{(menuItem/rdfs("label")*)}</a>
- }
- }
- </div>
- {
- ifx ((menuItem/menu("children")).length > 0) {
- <div>
- <ul class="nav-entries">
- {
- for (childMenuItem <- menuItem/menu("children")!!) yield {
- <li><a href={childMenuItem/menu("path")*}>{childMenuItem/rdfs("label")*}</a><span>{childMenuItem/dct("description")*}</span></li>
- }
- }
- </ul>
- </div>
- }
- }
- </li>
- }
- </ul>
+ {for (menuItem <- res/menu("globalMenu")!!) yield
+ <li class="top-nav-entry"><div class="title">
+ {
+ if ((menuItem/menu("path")).length > 0) {
+ <a href={menuItem/menu("path")*}>{(menuItem/rdfs("label")*)}</a>
+ } else {
+ <a href="#" onclick="return false">{(menuItem/rdfs("label")*)}</a>
+ }
+ }
+ </div>
+ {
+ ifx ((menuItem/menu("children")).length > 0) {
+ <div>
+ <ul class="nav-entries">
+ {
+ for (childMenuItem <- menuItem/menu("children")!!) yield {
+ <li><a href={childMenuItem/menu("path")*}>{childMenuItem/rdfs("label")*}</a><span>{childMenuItem/dct("description")*}</span></li>
+ }
+ }
+ </ul>
+ </div>
+ }
+ }
+ </li>
+ }
+ </ul>
</div>
- }
- }
- }
+ }
+ }
+ }
}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/platform.style.default/src/main/scala/HeadedPageRenderlet.scala
----------------------------------------------------------------------
diff --git a/platform.style.default/src/main/scala/HeadedPageRenderlet.scala b/platform.style.default/src/main/scala/HeadedPageRenderlet.scala
index 63dead1..f5c0106 100644
--- a/platform.style.default/src/main/scala/HeadedPageRenderlet.scala
+++ b/platform.style.default/src/main/scala/HeadedPageRenderlet.scala
@@ -39,22 +39,22 @@ import org.apache.clerezza.rdf.ontologies.DC
*/
class HeadedPageRenderlet extends SRenderlet {
- val getRdfType = PLATFORM.HeadedPage
+ val getRdfType = PLATFORM.HeadedPage
- override def getModePattern = "(?!.*naked).*"
+ override def getModePattern = "(?!.*naked).*"
- protected def defaultTitle(res: RichGraphNode) = "An incomplete titled content "+(res/DISCOBITS.contains*)
+ protected def defaultTitle(res: RichGraphNode) = "An incomplete titled content "+(res/DISCOBITS.contains*)
- override def renderedPage(arguments: XmlResult.Arguments) = {
- new XmlResult(arguments) {
- def menuLink(href: String, label: String) =
- if ((res*).endsWith(href) || (res*).endsWith(href+"index")) {
- <a href={href} class="active">{label}</a>
- } else {
- <a href={href}>{label}</a>
- }
- override def content = {
- resultDocModifier.addStyleSheet("/style/style.css");
+ override def renderedPage(arguments: XmlResult.Arguments) = {
+ new XmlResult(arguments) {
+ def menuLink(href: String, label: String) =
+ if ((res*).endsWith(href) || (res*).endsWith(href+"index")) {
+ <a href={href} class="active">{label}</a>
+ } else {
+ <a href={href}>{label}</a>
+ }
+ override def content = {
+ resultDocModifier.addStyleSheet("/style/style.css");
resultDocModifier.addScriptReference("/jquery/jquery-1.3.2.min.js");
/*resultDocModifier.addScriptReference("/jquery/jquery.menu.js");
resultDocModifier.addScriptReference("/jquery/jquery.panel.js");
@@ -62,99 +62,99 @@ resultDocModifier.addScriptReference("/style/scripts/panel.js");*/
resultDocModifier.addScriptReference("/scripts/modification-status.js");
resultDocModifier.addScriptReference("/scripts/status-message.js");
<html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- {(res/DISCOBITS.contains).find(e => ((e/DISCOBITS.pos*) == "0")) match {
- case Some(e) => <title>{render(e/DISCOBITS.holds, "naked")}</title>
- case None => <title>{defaultTitle(res)}</title>
- }
- }
- </head>
- <body>
- <div class="zz-header">
- <div class="bar"></div>
- <div class="logo">
- <a href="http://clerezza.apache.org/" style=""><img src="/images/logo.png" alt="logo" /></a>
- </div>
- <div class="module-info">
- <span id="tx-module">
- <div id="tx-page-actions">
- <ol id="tx-page-actions-ol">
- </ol>
- </div>
- </span>
- <div id="tx-module-tabs">
- <ol id="tx-module-tabs-ol">
- </ol>
-
- </div>
- </div>
-
- <div class="zz-control">
- <div class="login">
- {
- def platform(s: Any) = new UriRef("http://clerezza.org/2009/08/platform#"+s)
- val userName = context/platform("user")/platform("userName")*
- val displayName = if ((context/platform("user")/FOAF.name).length == 0) {
- userName
- } else {
- context/platform("user")/FOAF.name*
- }
- if((userName).equals("anonymous")) {
- <span>
- <a href= {"/login?referer="+URLEncoder.encode(uriInfo.getAbsolutePath.toString, "utf-8")}
- id="tx-login-button">login</a>
- </span>
- } else {
- <span><a href={"/user/" + userName + "/control-panel"}>{displayName}</a>|<a href="/logout">logout</a></span>
- }
- }
- </div>
- <div class="actions" id="tx-contextual-buttons">
- <ol id="tx-contextual-buttons-ol">
- </ol>
- </div>
- <div id="tx-module-options">
- <ol id="tx-module-options-ol">
- </ol>
- </div>
-
-
- <div class="tx-panel" id="tx-panel">
- <div id="tx-panel-title"><h3></h3></div>
- <div class="tx-panel-window">
- <div class="tx-panel-tab-buttons" id="tx-panel-tab-buttons">
- <ol id="tx-panel-tab-buttons-ol">
- </ol>
- </div>
- <div class="tx-panel-tabs" id="tx-panel-tabs"></div>
- </div>
- </div>
-
- </div>
- </div>
- {render(context,"menu")}
- <div class="zz-content">
- {
- if (mode == null) {
- render(res, "naked")
- } else {
- render(res, mode + "-naked")
- }
- }
- </div>
- <div class="footer">
- <div class="logos"><img src="/images/feather.png" /><img src="/images/sw-vert-w3c.png" /><img src="/images/footer-logo.png" /></div>
+ <head>
+ {(res/DISCOBITS.contains).find(e => ((e/DISCOBITS.pos*) == "0")) match {
+ case Some(e) => <title>{render(e/DISCOBITS.holds, "naked")}</title>
+ case None => <title>{defaultTitle(res)}</title>
+ }
+ }
+ </head>
+ <body>
+ <div class="zz-header">
+ <div class="bar"></div>
+ <div class="logo">
+ <a href="http://clerezza.apache.org/" style=""><img src="/images/logo.png" alt="logo" /></a>
+ </div>
+ <div class="module-info">
+ <span id="tx-module">
+ <div id="tx-page-actions">
+ <ol id="tx-page-actions-ol">
+ </ol>
+ </div>
+ </span>
+ <div id="tx-module-tabs">
+ <ol id="tx-module-tabs-ol">
+ </ol>
+
+ </div>
+ </div>
+
+ <div class="zz-control">
+ <div class="login">
+ {
+ def platform(s: Any) = new UriRef("http://clerezza.org/2009/08/platform#"+s)
+ val userName = context/platform("user")/platform("userName")*
+ val displayName = if ((context/platform("user")/FOAF.name).length == 0) {
+ userName
+ } else {
+ context/platform("user")/FOAF.name*
+ }
+ if((userName).equals("anonymous")) {
+ <span>
+ <a href= {"/login?referer="+URLEncoder.encode(uriInfo.getAbsolutePath.toString, "utf-8")}
+ id="tx-login-button">login</a>
+ </span>
+ } else {
+ <span><a href={"/user/" + userName + "/control-panel"}>{displayName}</a>|<a href="/logout">logout</a></span>
+ }
+ }
+ </div>
+ <div class="actions" id="tx-contextual-buttons">
+ <ol id="tx-contextual-buttons-ol">
+ </ol>
+ </div>
+ <div id="tx-module-options">
+ <ol id="tx-module-options-ol">
+ </ol>
+ </div>
+
+
+ <div class="tx-panel" id="tx-panel">
+ <div id="tx-panel-title"><h3></h3></div>
+ <div class="tx-panel-window">
+ <div class="tx-panel-tab-buttons" id="tx-panel-tab-buttons">
+ <ol id="tx-panel-tab-buttons-ol">
+ </ol>
+ </div>
+ <div class="tx-panel-tabs" id="tx-panel-tabs"></div>
+ </div>
+ </div>
+
+ </div>
+ </div>
+ {render(context,"menu")}
+ <div class="zz-content">
+ {
+ if (mode == null) {
+ render(res, "naked")
+ } else {
+ render(res, mode + "-naked")
+ }
+ }
+ </div>
+ <div class="footer">
+ <div class="logos"><img src="/images/feather.png" /><img src="/images/sw-vert-w3c.png" /><img src="/images/footer-logo.png" /></div>
- <div class="divider"></div>
- <div class="dark">
- <div class="copyright">Apache Clerezza, Clerezza, Apache, the Apache feather logo, and the Apache Clerezza project logo are trademarks of The Apache Software Foundation. <br></br>© 2011 The Apache Software Foundation.</div>
- </div>
- </div>
- </body>
+ <div class="divider"></div>
+ <div class="dark">
+ <div class="copyright">Apache Clerezza, Clerezza, Apache, the Apache feather logo, and the Apache Clerezza project logo are trademarks of The Apache Software Foundation. <br></br>© 2011 The Apache Software Foundation.</div>
+ </div>
+ </div>
+ </body>
</html>
-
- }
- }
- }
+
+ }
+ }
+ }
}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/platform.style.default/src/main/scala/RdfListRenderlet.scala
----------------------------------------------------------------------
diff --git a/platform.style.default/src/main/scala/RdfListRenderlet.scala b/platform.style.default/src/main/scala/RdfListRenderlet.scala
index b9cbd32..2425d24 100644
--- a/platform.style.default/src/main/scala/RdfListRenderlet.scala
+++ b/platform.style.default/src/main/scala/RdfListRenderlet.scala
@@ -33,21 +33,21 @@ import org.apache.clerezza.platform.typerendering.scala._
*/
class RdfListRenderlet extends SRenderlet {
- val getRdfType = RDF.List
+ val getRdfType = RDF.List
-
- override def renderedPage(arguments: XmlResult.Arguments) = {
- new XmlResult(arguments) {
- override def content = {
- <div id="tx-content" class="list">
- {for (entry <- res!!) yield
- <div class="entry">
- {render(entry, mode)}
- </div>
- }
- </div>
- }
- }
- }
+
+ override def renderedPage(arguments: XmlResult.Arguments) = {
+ new XmlResult(arguments) {
+ override def content = {
+ <div id="tx-content" class="list">
+ {for (entry <- res!!) yield
+ <div class="entry">
+ {render(entry, mode)}
+ </div>
+ }
+ </div>
+ }
+ }
+ }
}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/platform.typerendering.gui/src/main/scala/Activator.scala
----------------------------------------------------------------------
diff --git a/platform.typerendering.gui/src/main/scala/Activator.scala b/platform.typerendering.gui/src/main/scala/Activator.scala
index d5731da..5e88a85 100644
--- a/platform.typerendering.gui/src/main/scala/Activator.scala
+++ b/platform.typerendering.gui/src/main/scala/Activator.scala
@@ -41,86 +41,86 @@ import java.security.{AccessControlException, AccessController}
*/
class Activator extends BundleActivator {
- private var renderletsOverview: ServiceRegistration[Object] = null
- private var renderletRegistration: ServiceRegistration[TypeRenderlet] = null
+ private var renderletsOverview: ServiceRegistration[Object] = null
+ private var renderletRegistration: ServiceRegistration[TypeRenderlet] = null
private var menuProviderRegistration: ServiceRegistration[GlobalMenuItemsProvider] = null
- private var bundleContext: BundleContext = null
+ private var bundleContext: BundleContext = null
- final val path = "admin/renderlets/overview"
- @Path(path)
- object RenderletsOverview {
- @GET def get() = {
- val resultMGraph = new SimpleMGraph();
- val preamble = new Preamble(resultMGraph)
- import preamble._
- val resultNode = new GraphNode(new BNode(), resultMGraph);
- resultNode.addProperty(RDF.`type` , Ontology.RenderletOverviewPage);
- resultNode.addProperty(RDF.`type` , PLATFORM.HeadedPage);
- resultNode.addProperty(RDF.`type` , RDF.List);
- val renderletList = resultNode.asList;
- for (sr <- bundleContext.getServiceReferences(classOf[TypeRenderlet].getName, null)) {
- val renderlet = bundleContext.getService(sr).asInstanceOf[TypeRenderlet]
- val rendRes = new BNode()
- rendRes.addProperty(RDF.`type`, Ontology.Renderlet);
- rendRes.addPropertyValue(Ontology.mediaType,
- renderlet.getMediaType.toString)
- if (renderlet.getModePattern != null) rendRes.addPropertyValue(Ontology.modePattern,
- renderlet.getModePattern)
- rendRes.addProperty(Ontology.rdfType,
- renderlet.getRdfType)
- rendRes.addPropertyValue(Ontology.stringRepresentation,
- renderlet.toString)
- rendRes.addPropertyValue(Ontology.providingBundle,
- sr.getBundle.getLocation)
- renderletList.add(rendRes)
- }
- resultNode;
- }
- }
+ final val path = "admin/renderlets/overview"
+ @Path(path)
+ object RenderletsOverview {
+ @GET def get() = {
+ val resultMGraph = new SimpleMGraph();
+ val preamble = new Preamble(resultMGraph)
+ import preamble._
+ val resultNode = new GraphNode(new BNode(), resultMGraph);
+ resultNode.addProperty(RDF.`type` , Ontology.RenderletOverviewPage);
+ resultNode.addProperty(RDF.`type` , PLATFORM.HeadedPage);
+ resultNode.addProperty(RDF.`type` , RDF.List);
+ val renderletList = resultNode.asList;
+ for (sr <- bundleContext.getServiceReferences(classOf[TypeRenderlet].getName, null)) {
+ val renderlet = bundleContext.getService(sr).asInstanceOf[TypeRenderlet]
+ val rendRes = new BNode()
+ rendRes.addProperty(RDF.`type`, Ontology.Renderlet);
+ rendRes.addPropertyValue(Ontology.mediaType,
+ renderlet.getMediaType.toString)
+ if (renderlet.getModePattern != null) rendRes.addPropertyValue(Ontology.modePattern,
+ renderlet.getModePattern)
+ rendRes.addProperty(Ontology.rdfType,
+ renderlet.getRdfType)
+ rendRes.addPropertyValue(Ontology.stringRepresentation,
+ renderlet.toString)
+ rendRes.addPropertyValue(Ontology.providingBundle,
+ sr.getBundle.getLocation)
+ renderletList.add(rendRes)
+ }
+ resultNode;
+ }
+ }
- object MenuProvider extends GlobalMenuItemsProvider {
- override def getMenuItems: java.util.Set[GlobalMenuItem] = {
- import collection.JavaConversions._
- val result = new HashSet[GlobalMenuItem]();
- try {
- //TODO should have a more general way to say that a user has some administrative priviledges
- AccessController.checkPermission(new TcPermission("urn:x-localinstance:/content.graph", "readwrite"))
- }
- catch {
- case e: AccessControlException => {
- return result
- }
- }
- result.add(new GlobalMenuItem("/"+path,"renderlet-overview", "Renderlet Overview", -999, "Administration"))
- result
- }
- }
+ object MenuProvider extends GlobalMenuItemsProvider {
+ override def getMenuItems: java.util.Set[GlobalMenuItem] = {
+ import collection.JavaConversions._
+ val result = new HashSet[GlobalMenuItem]();
+ try {
+ //TODO should have a more general way to say that a user has some administrative priviledges
+ AccessController.checkPermission(new TcPermission("urn:x-localinstance:/content.graph", "readwrite"))
+ }
+ catch {
+ case e: AccessControlException => {
+ return result
+ }
+ }
+ result.add(new GlobalMenuItem("/"+path,"renderlet-overview", "Renderlet Overview", -999, "Administration"))
+ result
+ }
+ }
- /**
- * called when the bundle is started, this method initializes the provided service
- */
- def start(context: BundleContext) {
- this.bundleContext = context
- val args = scala.collection.mutable.Map("javax.ws.rs" -> true)
- renderletsOverview = context.registerService(classOf[Object],
- RenderletsOverview, args)
- val renderlet = new RenderletDescriptionRenderlet
- val serviceReference = context.getServiceReference(classOf[RenderletManager].getName)
- renderletRegistration = context.registerService(classOf[TypeRenderlet],
- renderlet, null)
- menuProviderRegistration = context.registerService(classOf[GlobalMenuItemsProvider],
- MenuProvider, null)
- }
+ /**
+ * called when the bundle is started, this method initializes the provided service
+ */
+ def start(context: BundleContext) {
+ this.bundleContext = context
+ val args = scala.collection.mutable.Map("javax.ws.rs" -> true)
+ renderletsOverview = context.registerService(classOf[Object],
+ RenderletsOverview, args)
+ val renderlet = new RenderletDescriptionRenderlet
+ val serviceReference = context.getServiceReference(classOf[RenderletManager].getName)
+ renderletRegistration = context.registerService(classOf[TypeRenderlet],
+ renderlet, null)
+ menuProviderRegistration = context.registerService(classOf[GlobalMenuItemsProvider],
+ MenuProvider, null)
+ }
- /**
- * called when the bundle is stopped, this method unregisters the provided service
- */
- def stop(context: BundleContext) {
- renderletsOverview.unregister()
- renderletRegistration.unregister()
- menuProviderRegistration.unregister()
- this.bundleContext = null
- }
+ /**
+ * called when the bundle is stopped, this method unregisters the provided service
+ */
+ def stop(context: BundleContext) {
+ renderletsOverview.unregister()
+ renderletRegistration.unregister()
+ menuProviderRegistration.unregister()
+ this.bundleContext = null
+ }
}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/platform.typerendering.gui/src/main/scala/Ontology.scala
----------------------------------------------------------------------
diff --git a/platform.typerendering.gui/src/main/scala/Ontology.scala b/platform.typerendering.gui/src/main/scala/Ontology.scala
index 7f34948..209d4c4 100644
--- a/platform.typerendering.gui/src/main/scala/Ontology.scala
+++ b/platform.typerendering.gui/src/main/scala/Ontology.scala
@@ -25,15 +25,15 @@ import org.apache.clerezza.rdf.core.UriRef
object Ontology {
- private def p(s: String) = new UriRef("http://clerezza.org/2011/25/renderletgui#"+s)
+ private def p(s: String) = new UriRef("http://clerezza.org/2011/25/renderletgui#"+s)
- val RenderletOverviewPage = p("RenderletOverviewPage")
- val Renderlet = p("Renderlet")
- val renderlet = p("renderlet")
- val modePattern = p("modePattern")
- val mediaType = p("mediaType")
- val rdfType = p("renderedType")
- val providingBundle = p("providingBundle")
- val stringRepresentation = p("stringRepresentation")
+ val RenderletOverviewPage = p("RenderletOverviewPage")
+ val Renderlet = p("Renderlet")
+ val renderlet = p("renderlet")
+ val modePattern = p("modePattern")
+ val mediaType = p("mediaType")
+ val rdfType = p("renderedType")
+ val providingBundle = p("providingBundle")
+ val stringRepresentation = p("stringRepresentation")
}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/platform.typerendering.gui/src/main/scala/RenderletDescriptionRenderlet.scala
----------------------------------------------------------------------
diff --git a/platform.typerendering.gui/src/main/scala/RenderletDescriptionRenderlet.scala b/platform.typerendering.gui/src/main/scala/RenderletDescriptionRenderlet.scala
index 088c787..afd20dc 100644
--- a/platform.typerendering.gui/src/main/scala/RenderletDescriptionRenderlet.scala
+++ b/platform.typerendering.gui/src/main/scala/RenderletDescriptionRenderlet.scala
@@ -37,24 +37,24 @@ import org.apache.clerezza.rdf.ontologies.DC
*/
class RenderletDescriptionRenderlet extends SRenderlet {
- val getRdfType = Ontology.Renderlet
+ val getRdfType = Ontology.Renderlet
- override def getModePattern = "naked"
+ override def getModePattern = "naked"
- override def renderedPage(arguments: XmlResult.Arguments) = {
- new XmlResult(arguments) {
- override def content = {
- resultDocModifier.setTitle("Renderlet Overview")
- resultDocModifier.addStyleSheet("/styles/renderlets/style.css")
- <div class="renderlet">
- <div>Renderlet: <span class="value">{res/Ontology.stringRepresentation*}</span></div>
- <div>For type: <span class="value">{res/Ontology.rdfType*}</span></div>
- <div>Producing: <span class="value">{res/Ontology.mediaType*}</span></div>
- {if ((res/Ontology.modePattern).size > 0) <div>Mode pattern: <span class="value">{res/Ontology.modePattern*}</span></div>}
- <div>Provided by: <span class="value">{res/Ontology.providingBundle*}</span></div>
- </div>
- }
- }
- }
+ override def renderedPage(arguments: XmlResult.Arguments) = {
+ new XmlResult(arguments) {
+ override def content = {
+ resultDocModifier.setTitle("Renderlet Overview")
+ resultDocModifier.addStyleSheet("/styles/renderlets/style.css")
+ <div class="renderlet">
+ <div>Renderlet: <span class="value">{res/Ontology.stringRepresentation*}</span></div>
+ <div>For type: <span class="value">{res/Ontology.rdfType*}</span></div>
+ <div>Producing: <span class="value">{res/Ontology.mediaType*}</span></div>
+ {if ((res/Ontology.modePattern).size > 0) <div>Mode pattern: <span class="value">{res/Ontology.modePattern*}</span></div>}
+ <div>Provided by: <span class="value">{res/Ontology.providingBundle*}</span></div>
+ </div>
+ }
+ }
+ }
}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/platform.typerendering.scala/src/main/scala/org/apache/clerezza/platform/typerendering/scala/AbstractRenderlet.scala
----------------------------------------------------------------------
diff --git a/platform.typerendering.scala/src/main/scala/org/apache/clerezza/platform/typerendering/scala/AbstractRenderlet.scala b/platform.typerendering.scala/src/main/scala/org/apache/clerezza/platform/typerendering/scala/AbstractRenderlet.scala
index a9da3d9..84a4221 100644
--- a/platform.typerendering.scala/src/main/scala/org/apache/clerezza/platform/typerendering/scala/AbstractRenderlet.scala
+++ b/platform.typerendering.scala/src/main/scala/org/apache/clerezza/platform/typerendering/scala/AbstractRenderlet.scala
@@ -46,46 +46,46 @@ import org.apache.clerezza.rdf.scala.utils.Preamble._
*
* class BookFormRenderlet extends AbstractRenderlet {
*
- * override def renderedPage(arguments: RenderedPage.Arguments): RenderedPage = {
- * new RenderedPage(arguments) {
+ * override def renderedPage(arguments: RenderedPage.Arguments): RenderedPage = {
+ * new RenderedPage(arguments) {
*
- * override def content = <div xmlns="http://www.w3.org/1999/xhtml">
- * ....
- * </div>
- * }
- * }
+ * override def content = <div xmlns="http://www.w3.org/1999/xhtml">
+ * ....
+ * </div>
+ * }
+ * }
* }
*/
abstract class AbstractRenderlet extends Renderlet {
- def renderedPage(renderingArguments: RenderedPage.Arguments): RenderedPage
+ def renderedPage(renderingArguments: RenderedPage.Arguments): RenderedPage
- def ifx[T](con: => Boolean)(f: => T) : T = {
- if (con) f else null.asInstanceOf[T]
- }
+ def ifx[T](con: => Boolean)(f: => T) : T = {
+ if (con) f else null.asInstanceOf[T]
+ }
- val resultDocModifier = org.apache.clerezza.platform.typerendering.ResultDocModifier.getInstance();
+ val resultDocModifier = org.apache.clerezza.platform.typerendering.ResultDocModifier.getInstance();
- @throws(classOf[IOException])
- override def render(res: GraphNode, context: GraphNode,
- sharedRenderingValues: java.util.Map[String, Object],
- renderer: CallbackRenderer ,
- renderingSpecification: URI,
- mode: String,
- mediaType: MediaType,
- requestProperties: RequestProperties,
- os: OutputStream) = {
- if (os == null) {
- throw new IllegalArgumentException("Exception!")
- }
- val renderingSpecificationOption = if (renderingSpecification != null) {Some(renderingSpecification)} else {None}
- val modeOption = if (mode != null) {Some(mode)} else {None}
- renderedPage(
- RenderedPage.Arguments(res, context, sharedRenderingValues, renderer,
- renderingSpecificationOption, modeOption,
- mediaType, requestProperties, os));
+ @throws(classOf[IOException])
+ override def render(res: GraphNode, context: GraphNode,
+ sharedRenderingValues: java.util.Map[String, Object],
+ renderer: CallbackRenderer ,
+ renderingSpecification: URI,
+ mode: String,
+ mediaType: MediaType,
+ requestProperties: RequestProperties,
+ os: OutputStream) = {
+ if (os == null) {
+ throw new IllegalArgumentException("Exception!")
+ }
+ val renderingSpecificationOption = if (renderingSpecification != null) {Some(renderingSpecification)} else {None}
+ val modeOption = if (mode != null) {Some(mode)} else {None}
+ renderedPage(
+ RenderedPage.Arguments(res, context, sharedRenderingValues, renderer,
+ renderingSpecificationOption, modeOption,
+ mediaType, requestProperties, os));
- }
+ }
}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/platform.typerendering.scala/src/main/scala/org/apache/clerezza/platform/typerendering/scala/PageRenderlet.scala
----------------------------------------------------------------------
diff --git a/platform.typerendering.scala/src/main/scala/org/apache/clerezza/platform/typerendering/scala/PageRenderlet.scala b/platform.typerendering.scala/src/main/scala/org/apache/clerezza/platform/typerendering/scala/PageRenderlet.scala
index f9a4cf3..df8335f 100644
--- a/platform.typerendering.scala/src/main/scala/org/apache/clerezza/platform/typerendering/scala/PageRenderlet.scala
+++ b/platform.typerendering.scala/src/main/scala/org/apache/clerezza/platform/typerendering/scala/PageRenderlet.scala
@@ -39,26 +39,26 @@ import org.apache.clerezza.rdf.scala.utils.Preamble._
*/
abstract class PageRenderlet extends AbstractRenderlet {
- def renderedPage(renderingArguments: RenderedPage.Arguments): RenderedPage
- def rdfType: UriRef
- def mode = "naked"
+ def renderedPage(renderingArguments: RenderedPage.Arguments): RenderedPage
+ def rdfType: UriRef
+ def mode = "naked"
- var renderletManager: RenderletManager = null;
+ var renderletManager: RenderletManager = null;
- def activate(context: ComponentContext) = {
- renderletManager.registerRenderlet(this.getClass.getName,
- null,
- rdfType, mode,
- MediaType.APPLICATION_XHTML_XML_TYPE, true);
- }
+ def activate(context: ComponentContext) = {
+ renderletManager.registerRenderlet(this.getClass.getName,
+ null,
+ rdfType, mode,
+ MediaType.APPLICATION_XHTML_XML_TYPE, true);
+ }
- def bindRenderletManager(m: RenderletManager) = {
- renderletManager = m
- }
+ def bindRenderletManager(m: RenderletManager) = {
+ renderletManager = m
+ }
- def unbindRenderletManager(m: RenderletManager) = {
- renderletManager = null
- }
+ def unbindRenderletManager(m: RenderletManager) = {
+ renderletManager = null
+ }
}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/platform.typerendering.scala/src/main/scala/org/apache/clerezza/platform/typerendering/scala/RenderedPage.scala
----------------------------------------------------------------------
diff --git a/platform.typerendering.scala/src/main/scala/org/apache/clerezza/platform/typerendering/scala/RenderedPage.scala b/platform.typerendering.scala/src/main/scala/org/apache/clerezza/platform/typerendering/scala/RenderedPage.scala
index b353a76..76d835e 100644
--- a/platform.typerendering.scala/src/main/scala/org/apache/clerezza/platform/typerendering/scala/RenderedPage.scala
+++ b/platform.typerendering.scala/src/main/scala/org/apache/clerezza/platform/typerendering/scala/RenderedPage.scala
@@ -43,134 +43,134 @@ import org.apache.clerezza.rdf.scala.utils.RichGraphNode
@deprecated("user XmlResult with SRenderlet", "2012")
abstract class RenderedPage(arguments: RenderedPage.Arguments) {
- val RenderedPage.Arguments(
- res: GraphNode,
- context: GraphNode,
- sharedRenderingValues: java.util.Map[String, Object],
- renderer: CallbackRenderer,
- renderingSpecificationOption: Option[URI],
- modeOption: Option[String],
- mediaType: MediaType,
- requestProperties: RequestProperties,
- os: OutputStream) = arguments;
- val mode = modeOption match {
- case Some(x) => x
- case None => null
- }
-
- val uriInfo = requestProperties.getUriInfo
- val requestHeaders = requestProperties.getRequestHeaders
- val responseHeaders = requestProperties.getResponseHeaders
-
- def render(resource: GraphNode): Seq[Node] = {
- modeOption match {
- case Some(m) => render(resource, m)
- case None => render(resource, "naked")
- }
- }
-
- def render(resource: GraphNode, mode: String) = {
- def parseNodeSeq(string: String) = {
- _root_.scala.xml.XML.loadString("<elem>" + string + "</elem>").child
- }
- val baos = new java.io.ByteArrayOutputStream
- renderer.render(resource, context, mode, baos)
- parseNodeSeq(new String(baos.toByteArray))
- }
-
- /**
- * renders the specified resource without using the base-graph from resource
- * rendered by the caller but getting a new context using the GraphNodeProvider
- */
- def render(resource: UriRef): Seq[Node] = {
- modeOption match {
- case Some(m) => render(resource, m)
- case None => render(resource, "naked")
- }
- }
-
- /**
- * renders the specified resource without using the base-graph from resource
- * rendered by the caller but getting a new context using the GraphNodeProvider
- */
- def render(resource: UriRef, mode: String) = {
- def parseNodeSeq(string: String) = {
- _root_.scala.xml.XML.loadString("<elem>" + string + "</elem>").child
- }
- val baos = new java.io.ByteArrayOutputStream
- renderer.render(resource, context, mode, baos)
- parseNodeSeq(new String(baos.toByteArray))
- }
-
- /**
- * This is an object that allows one to use some nice shortcuts in scala based subclasses
- * - $variable will get the value of the sharedRenderingValues hash
- * - $variable = value allows one to update the sharedRenderingValues hash
- * - $[ClassName] allows to access an osgi service annotated to be a WebRenderingService
- */
- object dollar {
- def apply(key: String) = sharedRenderingValues.get(key)
-
- def update(key: String, value: Object) = sharedRenderingValues.put(key, value)
-
- def apply[T](implicit m: Manifest[T]): T = {
- val clazz = m.erasure.asInstanceOf[Class[T]]
- requestProperties.getRenderingService(clazz)
- }
- }
+ val RenderedPage.Arguments(
+ res: GraphNode,
+ context: GraphNode,
+ sharedRenderingValues: java.util.Map[String, Object],
+ renderer: CallbackRenderer,
+ renderingSpecificationOption: Option[URI],
+ modeOption: Option[String],
+ mediaType: MediaType,
+ requestProperties: RequestProperties,
+ os: OutputStream) = arguments;
+ val mode = modeOption match {
+ case Some(x) => x
+ case None => null
+ }
+
+ val uriInfo = requestProperties.getUriInfo
+ val requestHeaders = requestProperties.getRequestHeaders
+ val responseHeaders = requestProperties.getResponseHeaders
+
+ def render(resource: GraphNode): Seq[Node] = {
+ modeOption match {
+ case Some(m) => render(resource, m)
+ case None => render(resource, "naked")
+ }
+ }
+
+ def render(resource: GraphNode, mode: String) = {
+ def parseNodeSeq(string: String) = {
+ _root_.scala.xml.XML.loadString("<elem>" + string + "</elem>").child
+ }
+ val baos = new java.io.ByteArrayOutputStream
+ renderer.render(resource, context, mode, baos)
+ parseNodeSeq(new String(baos.toByteArray))
+ }
+
+ /**
+ * renders the specified resource without using the base-graph from resource
+ * rendered by the caller but getting a new context using the GraphNodeProvider
+ */
+ def render(resource: UriRef): Seq[Node] = {
+ modeOption match {
+ case Some(m) => render(resource, m)
+ case None => render(resource, "naked")
+ }
+ }
+
+ /**
+ * renders the specified resource without using the base-graph from resource
+ * rendered by the caller but getting a new context using the GraphNodeProvider
+ */
+ def render(resource: UriRef, mode: String) = {
+ def parseNodeSeq(string: String) = {
+ _root_.scala.xml.XML.loadString("<elem>" + string + "</elem>").child
+ }
+ val baos = new java.io.ByteArrayOutputStream
+ renderer.render(resource, context, mode, baos)
+ parseNodeSeq(new String(baos.toByteArray))
+ }
+
+ /**
+ * This is an object that allows one to use some nice shortcuts in scala based subclasses
+ * - $variable will get the value of the sharedRenderingValues hash
+ * - $variable = value allows one to update the sharedRenderingValues hash
+ * - $[ClassName] allows to access an osgi service annotated to be a WebRenderingService
+ */
+ object dollar {
+ def apply(key: String) = sharedRenderingValues.get(key)
+
+ def update(key: String, value: Object) = sharedRenderingValues.put(key, value)
+
+ def apply[T](implicit m: Manifest[T]): T = {
+ val clazz = m.erasure.asInstanceOf[Class[T]]
+ requestProperties.getRenderingService(clazz)
+ }
+ }
/** no idea why, but since scala 2.10 it doesn't work if the object
* is called $ directly */
val $ = dollar
- def ifx[T](con: => Boolean)(f: => T): T = {
- if (con) f else null.asInstanceOf[T]
- }
+ def ifx[T](con: => Boolean)(f: => T): T = {
+ if (con) f else null.asInstanceOf[T]
+ }
- val resultDocModifier = org.apache.clerezza.platform.typerendering.ResultDocModifier.getInstance();
+ val resultDocModifier = org.apache.clerezza.platform.typerendering.ResultDocModifier.getInstance();
- val out = new PrintWriter(os)
+ val out = new PrintWriter(os)
- out.print(
- content match {
- case s: Seq[_] => s.mkString
- case o => o.toString
- }
- )
- out.flush()
+ out.print(
+ content match {
+ case s: Seq[_] => s.mkString
+ case o => o.toString
+ }
+ )
+ out.flush()
- /**
- * This is the main method/variable that needs to be implemented by subclasses
- */
- def content: AnyRef;
+ /**
+ * This is the main method/variable that needs to be implemented by subclasses
+ */
+ def content: AnyRef;
}
object RenderedPage {
- /**
- * Class to encapsulate information sent to the rendering engine.
- *
- * @param res RDF resource to be rendered with the template.
- * @param context RDF resource providing a rendering context.
- * @param sharedRenderingValues a map that can be used for sharing values
- * across the different Renderlets involved in a rendering process
- * @param callbackRenderer renderer for call backs.
- * @param renderingSpecification the rendering specification
- * @param modeOption the mode this Renderlet was invoked with, this is mainly used
- * so that the callbackRenderer can be claeed inheriting the mode.
- * @param mediaType the media type this media produces (a part of)
- * @param requestProperties properties of the http request, may be null
- * @param os where the output will be written to.
- */
- case class Arguments(res: GraphNode,
- context: GraphNode,
- sharedRenderingValues: java.util.Map[String, Object],
- renderer: CallbackRenderer,
- renderingSpecificationOption: Option[URI],
- modeOption: Option[String],
- mediaType: MediaType,
- requestProperties: RequestProperties,
- os: OutputStream);
+ /**
+ * Class to encapsulate information sent to the rendering engine.
+ *
+ * @param res RDF resource to be rendered with the template.
+ * @param context RDF resource providing a rendering context.
+ * @param sharedRenderingValues a map that can be used for sharing values
+ * across the different Renderlets involved in a rendering process
+ * @param callbackRenderer renderer for call backs.
+ * @param renderingSpecification the rendering specification
+ * @param modeOption the mode this Renderlet was invoked with, this is mainly used
+ * so that the callbackRenderer can be claeed inheriting the mode.
+ * @param mediaType the media type this media produces (a part of)
+ * @param requestProperties properties of the http request, may be null
+ * @param os where the output will be written to.
+ */
+ case class Arguments(res: GraphNode,
+ context: GraphNode,
+ sharedRenderingValues: java.util.Map[String, Object],
+ renderer: CallbackRenderer,
+ renderingSpecificationOption: Option[URI],
+ modeOption: Option[String],
+ mediaType: MediaType,
+ requestProperties: RequestProperties,
+ os: OutputStream);
}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/platform.typerendering.scala/src/main/scala/org/apache/clerezza/platform/typerendering/scala/SRenderlet.scala
----------------------------------------------------------------------
diff --git a/platform.typerendering.scala/src/main/scala/org/apache/clerezza/platform/typerendering/scala/SRenderlet.scala b/platform.typerendering.scala/src/main/scala/org/apache/clerezza/platform/typerendering/scala/SRenderlet.scala
index 981377b..ad082bb 100644
--- a/platform.typerendering.scala/src/main/scala/org/apache/clerezza/platform/typerendering/scala/SRenderlet.scala
+++ b/platform.typerendering.scala/src/main/scala/org/apache/clerezza/platform/typerendering/scala/SRenderlet.scala
@@ -45,46 +45,46 @@ import org.apache.clerezza.rdf.scala.utils.Preamble._
*
* class BookFormRenderlet extends SRenderlet {
*
- * override def renderedPage(arguments: RenderedPage.Arguments) = {
- * new XmlResult(arguments) {
+ * override def renderedPage(arguments: RenderedPage.Arguments) = {
+ * new XmlResult(arguments) {
*
- * override def content = <div xmlns="http://www.w3.org/1999/xhtml">
- * ....
- * </div>
- * }
- * }
+ * override def content = <div xmlns="http://www.w3.org/1999/xhtml">
+ * ....
+ * </div>
+ * }
+ * }
* }
*/
trait SRenderlet extends TypeRenderlet {
- def renderedPage(renderingArguments: XmlResult.Arguments): XmlResult
+ def renderedPage(renderingArguments: XmlResult.Arguments): XmlResult
- def ifx[T](con: => Boolean)(f: => T) : T = {
- if (con) f else null.asInstanceOf[T]
- }
+ def ifx[T](con: => Boolean)(f: => T) : T = {
+ if (con) f else null.asInstanceOf[T]
+ }
- val resultDocModifier = org.apache.clerezza.platform.typerendering.ResultDocModifier.getInstance();
+ val resultDocModifier = org.apache.clerezza.platform.typerendering.ResultDocModifier.getInstance();
- @throws(classOf[IOException])
- override def render(res: GraphNode, context: GraphNode,
- sharedRenderingValues: java.util.Map[String, Object],
- renderer: CallbackRenderer ,
- requestProperties: RequestProperties,
- os: OutputStream) = {
- if (os == null) {
- throw new IllegalArgumentException("Exception!")
- }
- val modeOption = if (requestProperties.getMode != null) {Some(requestProperties.getMode)} else {None}
- renderedPage(
- XmlResult.Arguments(res, context, sharedRenderingValues, renderer,
- modeOption,
- requestProperties.getMediaType, requestProperties, os));
+ @throws(classOf[IOException])
+ override def render(res: GraphNode, context: GraphNode,
+ sharedRenderingValues: java.util.Map[String, Object],
+ renderer: CallbackRenderer ,
+ requestProperties: RequestProperties,
+ os: OutputStream) = {
+ if (os == null) {
+ throw new IllegalArgumentException("Exception!")
+ }
+ val modeOption = if (requestProperties.getMode != null) {Some(requestProperties.getMode)} else {None}
+ renderedPage(
+ XmlResult.Arguments(res, context, sharedRenderingValues, renderer,
+ modeOption,
+ requestProperties.getMediaType, requestProperties, os));
- }
+ }
- override def getMediaType() = MediaType.APPLICATION_XHTML_XML_TYPE
+ override def getMediaType() = MediaType.APPLICATION_XHTML_XML_TYPE
- def getModePattern = "naked"
+ def getModePattern = "naked"
}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/platform.typerendering.scala/src/main/scala/org/apache/clerezza/platform/typerendering/scala/XmlResult.scala
----------------------------------------------------------------------
diff --git a/platform.typerendering.scala/src/main/scala/org/apache/clerezza/platform/typerendering/scala/XmlResult.scala b/platform.typerendering.scala/src/main/scala/org/apache/clerezza/platform/typerendering/scala/XmlResult.scala
index b605dd9..bcf3dcf 100644
--- a/platform.typerendering.scala/src/main/scala/org/apache/clerezza/platform/typerendering/scala/XmlResult.scala
+++ b/platform.typerendering.scala/src/main/scala/org/apache/clerezza/platform/typerendering/scala/XmlResult.scala
@@ -42,132 +42,132 @@ import org.apache.clerezza.rdf.scala.utils.RichGraphNode
*/
abstract class XmlResult(arguments: XmlResult.Arguments) {
- val XmlResult.Arguments(
- res: GraphNode,
- context: GraphNode,
- sharedRenderingValues: java.util.Map[String, Object],
- renderer: CallbackRenderer,
- modeOption: Option[String],
- mediaType: MediaType,
- requestProperties: RequestProperties,
- os: OutputStream) = arguments;
- val mode = modeOption match {
- case Some(x) => x
- case None => null
- }
-
- val uriInfo = requestProperties.getUriInfo
- val requestHeaders = requestProperties.getRequestHeaders
- val responseHeaders = requestProperties.getResponseHeaders
-
- def render(resource: GraphNode): Seq[Node] = {
- modeOption match {
- case Some(m) => render(resource, m)
- case None => render(resource, "naked")
- }
- }
-
- def render(resource: GraphNode, mode: String) = {
- def parseNodeSeq(string: String) = {
- _root_.scala.xml.XML.loadString("<elem>" + string + "</elem>").child
- }
- val baos = new java.io.ByteArrayOutputStream
- renderer.render(resource, context, mode, baos)
- parseNodeSeq(new String(baos.toByteArray))
- }
-
- /**
- * renders the specified resource without using the base-graph from resource
- * rendered by the caller but getting a new context using the GraphNodeProvider
- */
- def render(resource: UriRef): Seq[Node] = {
- modeOption match {
- case Some(m) => render(resource, m)
- case None => render(resource, "naked")
- }
- }
-
- /**
- * renders the specified resource without using the base-graph from resource
- * rendered by the caller but getting a new context using the GraphNodeProvider
- */
- def render(resource: UriRef, mode: String) = {
- def parseNodeSeq(string: String) = {
- _root_.scala.xml.XML.loadString("<elem>" + string + "</elem>").child
- }
- val baos = new java.io.ByteArrayOutputStream
- renderer.render(resource, context, mode, baos)
- parseNodeSeq(new String(baos.toByteArray))
- }
-
- /**
- * This is an object that allows one to use some nice shortcuts in scala based subclasses
- * - $variable will get the value of the sharedRenderingValues hash
- * - $variable = value allows one to update the sharedRenderingValues hash
- * - $[ClassName] allows to access an osgi service annotated to be a WebRenderingService
- */
- object dollar {
- def apply(key: String) = sharedRenderingValues.get(key)
-
- def update(key: String, value: Object) = sharedRenderingValues.put(key, value)
-
- def apply[T](implicit m: Manifest[T]): T = {
- val clazz = m.erasure.asInstanceOf[Class[T]]
- requestProperties.getRenderingService(clazz)
- }
- }
+ val XmlResult.Arguments(
+ res: GraphNode,
+ context: GraphNode,
+ sharedRenderingValues: java.util.Map[String, Object],
+ renderer: CallbackRenderer,
+ modeOption: Option[String],
+ mediaType: MediaType,
+ requestProperties: RequestProperties,
+ os: OutputStream) = arguments;
+ val mode = modeOption match {
+ case Some(x) => x
+ case None => null
+ }
+
+ val uriInfo = requestProperties.getUriInfo
+ val requestHeaders = requestProperties.getRequestHeaders
+ val responseHeaders = requestProperties.getResponseHeaders
+
+ def render(resource: GraphNode): Seq[Node] = {
+ modeOption match {
+ case Some(m) => render(resource, m)
+ case None => render(resource, "naked")
+ }
+ }
+
+ def render(resource: GraphNode, mode: String) = {
+ def parseNodeSeq(string: String) = {
+ _root_.scala.xml.XML.loadString("<elem>" + string + "</elem>").child
+ }
+ val baos = new java.io.ByteArrayOutputStream
+ renderer.render(resource, context, mode, baos)
+ parseNodeSeq(new String(baos.toByteArray))
+ }
+
+ /**
+ * renders the specified resource without using the base-graph from resource
+ * rendered by the caller but getting a new context using the GraphNodeProvider
+ */
+ def render(resource: UriRef): Seq[Node] = {
+ modeOption match {
+ case Some(m) => render(resource, m)
+ case None => render(resource, "naked")
+ }
+ }
+
+ /**
+ * renders the specified resource without using the base-graph from resource
+ * rendered by the caller but getting a new context using the GraphNodeProvider
+ */
+ def render(resource: UriRef, mode: String) = {
+ def parseNodeSeq(string: String) = {
+ _root_.scala.xml.XML.loadString("<elem>" + string + "</elem>").child
+ }
+ val baos = new java.io.ByteArrayOutputStream
+ renderer.render(resource, context, mode, baos)
+ parseNodeSeq(new String(baos.toByteArray))
+ }
+
+ /**
+ * This is an object that allows one to use some nice shortcuts in scala based subclasses
+ * - $variable will get the value of the sharedRenderingValues hash
+ * - $variable = value allows one to update the sharedRenderingValues hash
+ * - $[ClassName] allows to access an osgi service annotated to be a WebRenderingService
+ */
+ object dollar {
+ def apply(key: String) = sharedRenderingValues.get(key)
+
+ def update(key: String, value: Object) = sharedRenderingValues.put(key, value)
+
+ def apply[T](implicit m: Manifest[T]): T = {
+ val clazz = m.erasure.asInstanceOf[Class[T]]
+ requestProperties.getRenderingService(clazz)
+ }
+ }
/** no idea why, but since scala 2.10 it doesn't work if the object
* is called $ directly */
val $ = dollar
- def ifx[T](con: => Boolean)(f: => T): T = {
- if (con) f else null.asInstanceOf[T]
- }
+ def ifx[T](con: => Boolean)(f: => T): T = {
+ if (con) f else null.asInstanceOf[T]
+ }
- val resultDocModifier = org.apache.clerezza.platform.typerendering.ResultDocModifier.getInstance();
+ val resultDocModifier = org.apache.clerezza.platform.typerendering.ResultDocModifier.getInstance();
- val out = new PrintWriter(os)
+ val out = new PrintWriter(os)
- out.print(
- content match {
- case s: Seq[_] => s.mkString
- case o => o.toString
- }
- )
- out.flush()
+ out.print(
+ content match {
+ case s: Seq[_] => s.mkString
+ case o => o.toString
+ }
+ )
+ out.flush()
- /**
- * This is the main method/variable that needs to be implemented by subclasses
- */
- def content: AnyRef;
+ /**
+ * This is the main method/variable that needs to be implemented by subclasses
+ */
+ def content: AnyRef;
}
object XmlResult {
- /**
- * Class to encapsulate information sent to the rendering engine.
- *
- * @param res RDF resource to be rendered with the template.
- * @param context RDF resource providing a rendering context.
- * @param sharedRenderingValues a map that can be used for sharing values
- * across the different Renderlets involved in a rendering process
- * @param callbackRenderer renderer for call backs.
- * @param renderingSpecification the rendering specification
- * @param modeOption the mode this Renderlet was invoked with, this is mainly used
- * so that the callbackRenderer can be claeed inheriting the mode.
- * @param mediaType the media type this media produces (a part of)
- * @param requestProperties properties of the http request, may be null
- * @param os where the output will be written to.
- */
- case class Arguments(res: GraphNode,
- context: GraphNode,
- sharedRenderingValues: java.util.Map[String, Object],
- renderer: CallbackRenderer,
- modeOption: Option[String],
- mediaType: MediaType,
- requestProperties: RequestProperties,
- os: OutputStream);
+ /**
+ * Class to encapsulate information sent to the rendering engine.
+ *
+ * @param res RDF resource to be rendered with the template.
+ * @param context RDF resource providing a rendering context.
+ * @param sharedRenderingValues a map that can be used for sharing values
+ * across the different Renderlets involved in a rendering process
+ * @param callbackRenderer renderer for call backs.
+ * @param renderingSpecification the rendering specification
+ * @param modeOption the mode this Renderlet was invoked with, this is mainly used
+ * so that the callbackRenderer can be claeed inheriting the mode.
+ * @param mediaType the media type this media produces (a part of)
+ * @param requestProperties properties of the http request, may be null
+ * @param os where the output will be written to.
+ */
+ case class Arguments(res: GraphNode,
+ context: GraphNode,
+ sharedRenderingValues: java.util.Map[String, Object],
+ renderer: CallbackRenderer,
+ modeOption: Option[String],
+ mediaType: MediaType,
+ requestProperties: RequestProperties,
+ os: OutputStream);
}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/platform.users/core/src/main/scala/org/apache/clerezza/platform/users/UserGraphAcessPermissionProvider.scala
----------------------------------------------------------------------
diff --git a/platform.users/core/src/main/scala/org/apache/clerezza/platform/users/UserGraphAcessPermissionProvider.scala b/platform.users/core/src/main/scala/org/apache/clerezza/platform/users/UserGraphAcessPermissionProvider.scala
index eadaa92..72f2324 100644
--- a/platform.users/core/src/main/scala/org/apache/clerezza/platform/users/UserGraphAcessPermissionProvider.scala
+++ b/platform.users/core/src/main/scala/org/apache/clerezza/platform/users/UserGraphAcessPermissionProvider.scala
@@ -21,19 +21,19 @@ import org.apache.clerezza.platform.security.WebIdBasedPermissionProvider
import org.apache.clerezza.rdf.core.UriRef
class UserGraphAcessPermissionProvider extends WebIdBasedPermissionProvider {
-
- override def getPermissions(webId: UriRef) : java.util.Collection[String] = {
- import scala.collection.JavaConversions._
- val uriString = webId.getUnicodeString
- def uriStringWithoutFragment = {
- val hashPos = uriString.indexOf('#')
- if (hashPos != -1) {
- uriString.substring(0, hashPos)
- } else {
- uriString
- }
- }
- List("(org.apache.clerezza.rdf.core.access.security.TcPermission \""+uriStringWithoutFragment+"\" \"readwrite\")")
- }
+
+ override def getPermissions(webId: UriRef) : java.util.Collection[String] = {
+ import scala.collection.JavaConversions._
+ val uriString = webId.getUnicodeString
+ def uriStringWithoutFragment = {
+ val hashPos = uriString.indexOf('#')
+ if (hashPos != -1) {
+ uriString.substring(0, hashPos)
+ } else {
+ uriString
+ }
+ }
+ List("(org.apache.clerezza.rdf.core.access.security.TcPermission \""+uriStringWithoutFragment+"\" \"readwrite\")")
+ }
}
*/
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/platform.users/core/src/main/scala/org/apache/clerezza/platform/users/WebIdGraphsService.scala
----------------------------------------------------------------------
diff --git a/platform.users/core/src/main/scala/org/apache/clerezza/platform/users/WebIdGraphsService.scala b/platform.users/core/src/main/scala/org/apache/clerezza/platform/users/WebIdGraphsService.scala
index 788056f..78eca2a 100644
--- a/platform.users/core/src/main/scala/org/apache/clerezza/platform/users/WebIdGraphsService.scala
+++ b/platform.users/core/src/main/scala/org/apache/clerezza/platform/users/WebIdGraphsService.scala
@@ -45,168 +45,168 @@ import org.apache.clerezza.rdf.core.serializedform.{SupportedFormat, Parser}
*/
class WebIdGraphsService {
- private var proxy: WebProxy = null
-
- protected def bindProxy(proxy: WebProxy) = {
- this.proxy = proxy
- }
-
- protected def unbindProxy(proxy: WebProxy) = {
- this.proxy = null
- }
- private var tcManager: TcManager = null;
-
- protected def bindTcManager(tcManager: TcManager) = {
- this.tcManager = tcManager
- }
-
- protected def unbindTcManager(tcManager: TcManager) = {
- this.tcManager = null
- }
-
- private var platformConfig: PlatformConfig = null;
-
- protected def bindPlatformConfig(c: PlatformConfig) = {
- this.platformConfig = c
- }
-
- protected def unbindPlatformConfig(c: PlatformConfig) = {
- this.platformConfig = null
- }
-
- /**
- *
- * @param uri the Web-Id
- * @return a WebIdInfo allowing to access the graphs of the user
- */
- def getWebIdInfo(uri: UriRef): WebIdInfo = {
- return new WebIdInfo {
-
- private val uriString = uri.getUnicodeString
-
-
- /**
- * We don't know if there are multiple rediects from the person to the
- * Document with the triples which one is the Document
- */
- private lazy val profileDocumentUriString = {
- val hashPos = uriString.indexOf('#')
- if (hashPos != -1) {
- uriString.substring(0, hashPos)
- } else {
- redirectLocationString
- }
- }
-
- /**
- * the graph for putting local information in addition to the remote graph
- */
- private lazy val localGraphUri = {
- if (isLocal) uri
- else {
- new UriRef("urn:x-localinstance:/user/"+hashTruncatedUriString)
- }
- }
-
- private lazy val hashTruncatedUriString = {
- val hashPos = uriString.indexOf('#')
- if (hashPos != -1) {
- uriString.substring(0, hashPos)
- } else {
- uriString
- }
- }
-
-
- private lazy val profileDocumentUri = {
- new UriRef(profileDocumentUriString)
- }
-
- /**
- * As the webid identifies a person an not a document, a webid without hash sign
- * should redirect to the profile document
- */
- private lazy val redirectLocationString = {
- val url = new URL(uriString)
- val connection = url.openConnection()
- connection match {
- case hc : HttpURLConnection => {
- hc.setRequestMethod("HEAD");
- hc.setInstanceFollowRedirects(false)
- hc.addRequestProperty("Accept", acceptHeader)
- hc.getResponseCode match {
- case HttpURLConnection.HTTP_SEE_OTHER => {
- val location = hc.getHeaderField("Location")
- if (location == null) {
- throw new RuntimeException("No Location Headers in 303 response")
- }
- location
- }
- case _ => uriString
- }
- }
- case _ => uriString
- }
- }
-
- /**
- * A webbid identifying a person should redirect to the uri identifying the document,
- * it is possible that it redirects directly to the "correct" representation, this is why
- * we set this to prefer rdf over other formats
- */
- private lazy val acceptHeader = "application/rdf+xml,*/*;q.1"
-
-
- private def systemTriples = {
- AccessController.doPrivileged(new PrivilegedAction[MGraph]() {
- def run() = {
- val systemGraph = tcManager.getMGraph(Constants.SYSTEM_GRAPH_URI)
- val triples = systemGraph.filter(uri, PLATFORM.userName, null)
- val result = new SimpleMGraph
- while (triples.hasNext) {
- result.add(triples.next())
- }
- result
- }
- })
- }
-
- private lazy val localGraph = try {
- val g = tcManager.getMGraph(localGraphUri)
- g
- } catch {
- case e: NoSuchEntityException => {
- import scala.collection.JavaConversions._
- tcManager.getTcAccessController.
- setRequiredReadPermissionStrings(localGraphUri,
- List(new TcPermission(Constants.CONTENT_GRAPH_URI_STRING, TcPermission.READ).toString))
- tcManager.createMGraph(localGraphUri)
- }
- }
- //implementing exposed methods (from WebIdInfo trait)
- def publicProfile: TripleCollection = {
- tcManager.getMGraph(profileDocumentUri)
- }
-
- def localPublicUserData: LockableMGraph = {
- if (isLocal) {
- new UnionMGraph(tcManager.getMGraph(profileDocumentUri), systemTriples)
- } else {
- new UnionMGraph(localGraph, systemTriples, publicProfile)
- }
- }
-
- lazy val isLocal: Boolean = {
- import scala.collection.JavaConversions._
- platformConfig.getBaseUris.exists(baseUri => uriString.startsWith(baseUri.getUnicodeString))
- }
-
- val webId = uri
-
- def forceCacheUpdate() = {
- proxy.getGraph(profileDocumentUri)
- }
- }
-
- }
+ private var proxy: WebProxy = null
+
+ protected def bindProxy(proxy: WebProxy) = {
+ this.proxy = proxy
+ }
+
+ protected def unbindProxy(proxy: WebProxy) = {
+ this.proxy = null
+ }
+ private var tcManager: TcManager = null;
+
+ protected def bindTcManager(tcManager: TcManager) = {
+ this.tcManager = tcManager
+ }
+
+ protected def unbindTcManager(tcManager: TcManager) = {
+ this.tcManager = null
+ }
+
+ private var platformConfig: PlatformConfig = null;
+
+ protected def bindPlatformConfig(c: PlatformConfig) = {
+ this.platformConfig = c
+ }
+
+ protected def unbindPlatformConfig(c: PlatformConfig) = {
+ this.platformConfig = null
+ }
+
+ /**
+ *
+ * @param uri the Web-Id
+ * @return a WebIdInfo allowing to access the graphs of the user
+ */
+ def getWebIdInfo(uri: UriRef): WebIdInfo = {
+ return new WebIdInfo {
+
+ private val uriString = uri.getUnicodeString
+
+
+ /**
+ * We don't know if there are multiple rediects from the person to the
+ * Document with the triples which one is the Document
+ */
+ private lazy val profileDocumentUriString = {
+ val hashPos = uriString.indexOf('#')
+ if (hashPos != -1) {
+ uriString.substring(0, hashPos)
+ } else {
+ redirectLocationString
+ }
+ }
+
+ /**
+ * the graph for putting local information in addition to the remote graph
+ */
+ private lazy val localGraphUri = {
+ if (isLocal) uri
+ else {
+ new UriRef("urn:x-localinstance:/user/"+hashTruncatedUriString)
+ }
+ }
+
+ private lazy val hashTruncatedUriString = {
+ val hashPos = uriString.indexOf('#')
+ if (hashPos != -1) {
+ uriString.substring(0, hashPos)
+ } else {
+ uriString
+ }
+ }
+
+
+ private lazy val profileDocumentUri = {
+ new UriRef(profileDocumentUriString)
+ }
+
+ /**
+ * As the webid identifies a person an not a document, a webid without hash sign
+ * should redirect to the profile document
+ */
+ private lazy val redirectLocationString = {
+ val url = new URL(uriString)
+ val connection = url.openConnection()
+ connection match {
+ case hc : HttpURLConnection => {
+ hc.setRequestMethod("HEAD");
+ hc.setInstanceFollowRedirects(false)
+ hc.addRequestProperty("Accept", acceptHeader)
+ hc.getResponseCode match {
+ case HttpURLConnection.HTTP_SEE_OTHER => {
+ val location = hc.getHeaderField("Location")
+ if (location == null) {
+ throw new RuntimeException("No Location Headers in 303 response")
+ }
+ location
+ }
+ case _ => uriString
+ }
+ }
+ case _ => uriString
+ }
+ }
+
+ /**
+ * A webbid identifying a person should redirect to the uri identifying the document,
+ * it is possible that it redirects directly to the "correct" representation, this is why
+ * we set this to prefer rdf over other formats
+ */
+ private lazy val acceptHeader = "application/rdf+xml,*/*;q.1"
+
+
+ private def systemTriples = {
+ AccessController.doPrivileged(new PrivilegedAction[MGraph]() {
+ def run() = {
+ val systemGraph = tcManager.getMGraph(Constants.SYSTEM_GRAPH_URI)
+ val triples = systemGraph.filter(uri, PLATFORM.userName, null)
+ val result = new SimpleMGraph
+ while (triples.hasNext) {
+ result.add(triples.next())
+ }
+ result
+ }
+ })
+ }
+
+ private lazy val localGraph = try {
+ val g = tcManager.getMGraph(localGraphUri)
+ g
+ } catch {
+ case e: NoSuchEntityException => {
+ import scala.collection.JavaConversions._
+ tcManager.getTcAccessController.
+ setRequiredReadPermissionStrings(localGraphUri,
+ List(new TcPermission(Constants.CONTENT_GRAPH_URI_STRING, TcPermission.READ).toString))
+ tcManager.createMGraph(localGraphUri)
+ }
+ }
+ //implementing exposed methods (from WebIdInfo trait)
+ def publicProfile: TripleCollection = {
+ tcManager.getMGraph(profileDocumentUri)
+ }
+
+ def localPublicUserData: LockableMGraph = {
+ if (isLocal) {
+ new UnionMGraph(tcManager.getMGraph(profileDocumentUri), systemTriples)
+ } else {
+ new UnionMGraph(localGraph, systemTriples, publicProfile)
+ }
+ }
+
+ lazy val isLocal: Boolean = {
+ import scala.collection.JavaConversions._
+ platformConfig.getBaseUris.exists(baseUri => uriString.startsWith(baseUri.getUnicodeString))
+ }
+
+ val webId = uri
+
+ def forceCacheUpdate() = {
+ proxy.getGraph(profileDocumentUri)
+ }
+ }
+
+ }
}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/platform.users/core/src/main/scala/org/apache/clerezza/platform/users/WebIdInfo.scala
----------------------------------------------------------------------
diff --git a/platform.users/core/src/main/scala/org/apache/clerezza/platform/users/WebIdInfo.scala b/platform.users/core/src/main/scala/org/apache/clerezza/platform/users/WebIdInfo.scala
index f2bf977..228c327 100644
--- a/platform.users/core/src/main/scala/org/apache/clerezza/platform/users/WebIdInfo.scala
+++ b/platform.users/core/src/main/scala/org/apache/clerezza/platform/users/WebIdInfo.scala
@@ -31,31 +31,31 @@ import org.apache.clerezza.rdf.core.access.LockableMGraph
*/
trait WebIdInfo {
- /**
- * The WebID this instance is about
- */
- def webId: UriRef
-
- /**
- * The WebId profile graph, for remote users this is immutable
- */
- def publicProfile: TripleCollection
-
- /**
- * An MGraph used to store public information about the user. For local
- * users this is the same as publicProfile. In any case this contains the
- * triples of the publicProfile.
- */
- def localPublicUserData: LockableMGraph
-
- /**
- * indicates if this WebId is local.
- */
- def isLocal: Boolean
-
- /**
- * forces an update of cached graphs associated with thie WebID (if any)
- */
- def forceCacheUpdate(): Unit
+ /**
+ * The WebID this instance is about
+ */
+ def webId: UriRef
+
+ /**
+ * The WebId profile graph, for remote users this is immutable
+ */
+ def publicProfile: TripleCollection
+
+ /**
+ * An MGraph used to store public information about the user. For local
+ * users this is the same as publicProfile. In any case this contains the
+ * triples of the publicProfile.
+ */
+ def localPublicUserData: LockableMGraph
+
+ /**
+ * indicates if this WebId is local.
+ */
+ def isLocal: Boolean
+
+ /**
+ * forces an update of cached graphs associated with thie WebID (if any)
+ */
+ def forceCacheUpdate(): Unit
}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/rdf.scala.utils/src/main/scala/org/apache/clerezza/rdf/scala/utils/CollectedIter.scala
----------------------------------------------------------------------
diff --git a/rdf.scala.utils/src/main/scala/org/apache/clerezza/rdf/scala/utils/CollectedIter.scala b/rdf.scala.utils/src/main/scala/org/apache/clerezza/rdf/scala/utils/CollectedIter.scala
index 8617647..b0ae23a 100644
--- a/rdf.scala.utils/src/main/scala/org/apache/clerezza/rdf/scala/utils/CollectedIter.scala
+++ b/rdf.scala.utils/src/main/scala/org/apache/clerezza/rdf/scala/utils/CollectedIter.scala
@@ -37,32 +37,32 @@ import java.util.concurrent.locks.Lock
*/
class CollectedIter[T](iterCreator: () => Iterator[T], readLock: Lock) extends immutable.Seq[T] {
- def this(jList : java.util.List[T], readLock: Lock) = this(() => jList.iterator(), readLock)
- def this() = this( ()=> java.util.Collections.emptyList[T].iterator(),null)
+ def this(jList : java.util.List[T], readLock: Lock) = this(() => jList.iterator(), readLock)
+ def this() = this( ()=> java.util.Collections.emptyList[T].iterator(),null)
- var iter = iterCreator()
- var firstIter = true
+ var iter = iterCreator()
+ var firstIter = true
- private val collectedElems = new ArrayBuffer[T]()
+ private val collectedElems = new ArrayBuffer[T]()
- /**
+ /**
* This method allows the position to be expressed between parenthesis
*/
def apply(pos : Int) = {
- ensureReadTill(pos)
- collectedElems(pos)
+ ensureReadTill(pos)
+ collectedElems(pos)
}
- /**
- * returns a new fully expanded and sorted CollectediterCreator
- */
- def sort(lt : (T,T) => Boolean) = {
- val sortedElems = iterator.toList.sortWith(lt)
- //TODO this re-expands everything, return sorted-list directly
- new CollectedIter[T](sortedElems, readLock)
+ /**
+ * returns a new fully expanded and sorted CollectediterCreator
+ */
+ def sort(lt : (T,T) => Boolean) = {
+ val sortedElems = iterator.toList.sortWith(lt)
+ //TODO this re-expands everything, return sorted-list directly
+ new CollectedIter[T](sortedElems, readLock)
- }
+ }
/**
* Operator style syntax to access a position.
@@ -70,42 +70,42 @@ class CollectedIter[T](iterCreator: () => Iterator[T], readLock: Lock) extends i
def %(pos: Int) = apply(pos)
private def ensureReadTill(pos: Int) {
- try {
-
- while (iter.hasNext && (collectedElems.length-1 <= pos)) {
- val next = iter.next()
- if (firstIter || !collectedElems.contains(next)) {
- collectedElems += next
- }
- }
- } catch {
- case e: ConcurrentModificationException => {
- readLock.lock()
- try {
- iter = iterCreator()
- firstIter = false
- //going beyond pos, do reduce chance we have to aquire another lock
- val biggerPos = if (pos < (Integer.MAX_VALUE - 100)) {
- pos + 100
- } else {
- Integer.MAX_VALUE
- }
- while (iter.hasNext && (collectedElems.length-1 <= biggerPos)) {
- val next = iter.next()
- if (!collectedElems.contains(next)) {
- collectedElems += next
- }
- }
- } finally {
- readLock.unlock()
- }
- }
- case e => throw e
- }
+ try {
+
+ while (iter.hasNext && (collectedElems.length-1 <= pos)) {
+ val next = iter.next()
+ if (firstIter || !collectedElems.contains(next)) {
+ collectedElems += next
+ }
+ }
+ } catch {
+ case e: ConcurrentModificationException => {
+ readLock.lock()
+ try {
+ iter = iterCreator()
+ firstIter = false
+ //going beyond pos, do reduce chance we have to aquire another lock
+ val biggerPos = if (pos < (Integer.MAX_VALUE - 100)) {
+ pos + 100
+ } else {
+ Integer.MAX_VALUE
+ }
+ while (iter.hasNext && (collectedElems.length-1 <= biggerPos)) {
+ val next = iter.next()
+ if (!collectedElems.contains(next)) {
+ collectedElems += next
+ }
+ }
+ } finally {
+ readLock.unlock()
+ }
+ }
+ case e => throw e
+ }
}
override def length : Int = {
- length(Integer.MAX_VALUE)
+ length(Integer.MAX_VALUE)
}
/**
@@ -114,20 +114,20 @@ class CollectedIter[T](iterCreator: () => Iterator[T], readLock: Lock) extends i
* the result is smaller than max it is the length of the collection.
*/
def length(max: Int) : Int = {
- ensureReadTill(max)
- collectedElems.length
- }
+ ensureReadTill(max)
+ collectedElems.length
+ }
override def toString() = {
- if (length(1) > 0) {
- apply(0).toString
- } else {
- "empty"
+ if (length(1) > 0) {
+ apply(0).toString
+ } else {
+ "empty"
}
}
override def iterator = {
- ensureReadTill(Integer.MAX_VALUE)
+ ensureReadTill(Integer.MAX_VALUE)
collectedElems.iterator
}
}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/rdf.scala.utils/src/main/scala/org/apache/clerezza/rdf/scala/utils/EzLiteral.scala
----------------------------------------------------------------------
diff --git a/rdf.scala.utils/src/main/scala/org/apache/clerezza/rdf/scala/utils/EzLiteral.scala b/rdf.scala.utils/src/main/scala/org/apache/clerezza/rdf/scala/utils/EzLiteral.scala
index e96ea6f..b7e7313 100644
--- a/rdf.scala.utils/src/main/scala/org/apache/clerezza/rdf/scala/utils/EzLiteral.scala
+++ b/rdf.scala.utils/src/main/scala/org/apache/clerezza/rdf/scala/utils/EzLiteral.scala
@@ -27,7 +27,7 @@ object EzLiteral extends EzLiteralImplicits
trait EzLiteralImplicits {
- implicit def string2lit(str: String) = new EzLiteral(str)
+ implicit def string2lit(str: String) = new EzLiteral(str)
}
@@ -47,24 +47,24 @@ trait EzLiteralImplicits {
*/
class EzLiteral(string: String) extends TypedLiteralImpl(string,XSD.string) {
- /**
- * @return a plain literal with language specified by lang
- */
- def lang(lng: String): PlainLiteral = lang(new Language(lng))
+ /**
+ * @return a plain literal with language specified by lang
+ */
+ def lang(lng: String): PlainLiteral = lang(new Language(lng))
- /**
- * @return a plain literal with language specified by lang
- */
- def lang(lng: Language): PlainLiteral = new PlainLiteralImpl(string, lng)
+ /**
+ * @return a plain literal with language specified by lang
+ */
+ def lang(lng: Language): PlainLiteral = new PlainLiteralImpl(string, lng)
- /**
- * Map to a Typed Literal of given type
- */
- def ^^(typ: UriRef): TypedLiteral = new TypedLiteralImpl(string, typ)
+ /**
+ * Map to a Typed Literal of given type
+ */
+ def ^^(typ: UriRef): TypedLiteral = new TypedLiteralImpl(string, typ)
- /**
- * Map to a URI of given lexical form
- */
- def uri = new UriRef(string)
+ /**
+ * Map to a URI of given lexical form
+ */
+ def uri = new UriRef(string)
}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/rdf.scala.utils/src/main/scala/org/apache/clerezza/rdf/scala/utils/EzMGraph.scala
----------------------------------------------------------------------
diff --git a/rdf.scala.utils/src/main/scala/org/apache/clerezza/rdf/scala/utils/EzMGraph.scala b/rdf.scala.utils/src/main/scala/org/apache/clerezza/rdf/scala/utils/EzMGraph.scala
index ce7e3a7..485f939 100644
--- a/rdf.scala.utils/src/main/scala/org/apache/clerezza/rdf/scala/utils/EzMGraph.scala
+++ b/rdf.scala.utils/src/main/scala/org/apache/clerezza/rdf/scala/utils/EzMGraph.scala
@@ -34,44 +34,44 @@ import scala.collection.mutable.HashMap
class EzMGraph(val baseTc: MGraph) extends AbstractMGraph with TcDependentConversions {
- def this() = this (new SimpleMGraph())
-
- def performFilter(subject: NonLiteral, predicate: UriRef,
- obj: Resource): java.util.Iterator[Triple] = baseTc.filter(subject, predicate, obj)
-
- override def size = baseTc.size
-
- override def add(t: Triple) = baseTc.add(t)
-
- /**
- * Add all triples into the other graph to this one
- */
- def +=(other: Graph) = {
- if (baseTc ne other) baseTc.addAll(other)
- }
-
- /**
- * create a new bnode
- */
- def bnode: BNode = {
- new BNode
- }
-
- private val namedBnodes = new HashMap[String,BNode]
-
- /**
- * create a new named bnode based EzGraphNode with the preferred writing style
- */
- def b_(name: String): BNode = {
- namedBnodes.get(name) match {
- case Some(bnode) => bnode
- case None => {
- val bn = new BNode
- namedBnodes.put(name, bn);
- bn
- }
- }
- }
+ def this() = this (new SimpleMGraph())
+
+ def performFilter(subject: NonLiteral, predicate: UriRef,
+ obj: Resource): java.util.Iterator[Triple] = baseTc.filter(subject, predicate, obj)
+
+ override def size = baseTc.size
+
+ override def add(t: Triple) = baseTc.add(t)
+
+ /**
+ * Add all triples into the other graph to this one
+ */
+ def +=(other: Graph) = {
+ if (baseTc ne other) baseTc.addAll(other)
+ }
+
+ /**
+ * create a new bnode
+ */
+ def bnode: BNode = {
+ new BNode
+ }
+
+ private val namedBnodes = new HashMap[String,BNode]
+
+ /**
+ * create a new named bnode based EzGraphNode with the preferred writing style
+ */
+ def b_(name: String): BNode = {
+ namedBnodes.get(name) match {
+ case Some(bnode) => bnode
+ case None => {
+ val bn = new BNode
+ namedBnodes.put(name, bn);
+ bn
+ }
+ }
+ }
}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/rdf.scala.utils/src/main/scala/org/apache/clerezza/rdf/scala/utils/NameSpace.scala
----------------------------------------------------------------------
diff --git a/rdf.scala.utils/src/main/scala/org/apache/clerezza/rdf/scala/utils/NameSpace.scala b/rdf.scala.utils/src/main/scala/org/apache/clerezza/rdf/scala/utils/NameSpace.scala
index 6581543..ff67919 100644
--- a/rdf.scala.utils/src/main/scala/org/apache/clerezza/rdf/scala/utils/NameSpace.scala
+++ b/rdf.scala.utils/src/main/scala/org/apache/clerezza/rdf/scala/utils/NameSpace.scala
@@ -25,13 +25,13 @@ import org.apache.clerezza.rdf.core.UriRef
*/
class NameSpace(prefix: String) {
- /**
- * returns a UriRef applying this namespace prefix to the given symbol
- */
- def +(s: Symbol) = new UriRef(prefix + s.name)
+ /**
+ * returns a UriRef applying this namespace prefix to the given symbol
+ */
+ def +(s: Symbol) = new UriRef(prefix + s.name)
- /**
- * returns a UriRef applying this prefix to the given string
- */
- def +(s: String) = new UriRef(prefix + s)
+ /**
+ * returns a UriRef applying this prefix to the given string
+ */
+ def +(s: String) = new UriRef(prefix + s)
}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/rdf.scala.utils/src/main/scala/org/apache/clerezza/rdf/scala/utils/Preamble.scala
----------------------------------------------------------------------
diff --git a/rdf.scala.utils/src/main/scala/org/apache/clerezza/rdf/scala/utils/Preamble.scala b/rdf.scala.utils/src/main/scala/org/apache/clerezza/rdf/scala/utils/Preamble.scala
index 6a9686f..d5ff494 100644
--- a/rdf.scala.utils/src/main/scala/org/apache/clerezza/rdf/scala/utils/Preamble.scala
+++ b/rdf.scala.utils/src/main/scala/org/apache/clerezza/rdf/scala/utils/Preamble.scala
@@ -59,59 +59,59 @@ object Preamble extends TcIndependentConversions {
* @author bblfish, reto
*/
class Preamble(val baseTc: TripleCollection) extends TcDependentConversions {
-
+
}
protected trait TcDependentConversions extends TcIndependentConversions {
-
- def baseTc: TripleCollection
-
- implicit def toRichGraphNode(resource: Resource) = {
- new RichGraphNode(new GraphNode(resource, baseTc))
- }
+
+ def baseTc: TripleCollection
+
+ implicit def toRichGraphNode(resource: Resource) = {
+ new RichGraphNode(new GraphNode(resource, baseTc))
+ }
}
protected trait TcIndependentConversions extends EzLiteralImplicits {
- implicit def toRichGraphNode(node: GraphNode) = {
- new RichGraphNode(node)
- }
+ implicit def toRichGraphNode(node: GraphNode) = {
+ new RichGraphNode(node)
+ }
- implicit def toFirstElement(c: CollectedIter[RichGraphNode]) = {
- if (c.length(1) > 0) {
- c(0)
- } else {
- TcIndependentConversions.emptyLiteral
- }
- }
+ implicit def toFirstElement(c: CollectedIter[RichGraphNode]) = {
+ if (c.length(1) > 0) {
+ c(0)
+ } else {
+ TcIndependentConversions.emptyLiteral
+ }
+ }
- private val litFactory = LiteralFactory.getInstance
+ private val litFactory = LiteralFactory.getInstance
- implicit def lit2String(lit: Literal) = lit.getLexicalForm
+ implicit def lit2String(lit: Literal) = lit.getLexicalForm
- implicit def date2lit(date: Date) = litFactory.createTypedLiteral(date)
+ implicit def date2lit(date: Date) = litFactory.createTypedLiteral(date)
- implicit def int2lit(int: Int) = litFactory.createTypedLiteral(int)
+ implicit def int2lit(int: Int) = litFactory.createTypedLiteral(int)
- implicit def bigint2lit(bint: BigInt) = litFactory.createTypedLiteral(bint.underlying())
+ implicit def bigint2lit(bint: BigInt) = litFactory.createTypedLiteral(bint.underlying())
- implicit def bigint2lit(bigInt: BigInteger) = litFactory.createTypedLiteral(bigInt)
+ implicit def bigint2lit(bigInt: BigInteger) = litFactory.createTypedLiteral(bigInt)
- implicit def bool2lit(boolean: Boolean) = litFactory.createTypedLiteral(boolean)
+ implicit def bool2lit(boolean: Boolean) = litFactory.createTypedLiteral(boolean)
- implicit def long2lit(long: Long) = litFactory.createTypedLiteral(long)
+ implicit def long2lit(long: Long) = litFactory.createTypedLiteral(long)
- implicit def double2lit(double: Double) = litFactory.createTypedLiteral(double)
+ implicit def double2lit(double: Double) = litFactory.createTypedLiteral(double)
- implicit def uriRef2Prefix(uriRef: UriRef) = new NameSpace(uriRef.getUnicodeString)
+ implicit def uriRef2Prefix(uriRef: UriRef) = new NameSpace(uriRef.getUnicodeString)
- implicit def URItoUriRef(uri: URI) = new UriRef(uri.toString)
+ implicit def URItoUriRef(uri: URI) = new UriRef(uri.toString)
- implicit def URLtoUriRef(url: URL) = new UriRef(url.toExternalForm)
-
+ implicit def URLtoUriRef(url: URL) = new UriRef(url.toExternalForm)
+
}
protected object TcIndependentConversions {
- val emptyGraph = new impl.SimpleGraph(new impl.SimpleMGraph)
- val emptyLiteral = new RichGraphNode(new GraphNode(new impl.PlainLiteralImpl(""), emptyGraph))
+ val emptyGraph = new impl.SimpleGraph(new impl.SimpleMGraph)
+ val emptyLiteral = new RichGraphNode(new GraphNode(new impl.PlainLiteralImpl(""), emptyGraph))
}
[6/9] CLEREZZA-435: repaced tabs with spaces in scala files
Posted by re...@apache.org.
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/platform.accountcontrolpanel/platform.accountcontrolpanel.core/src/main/scala/org/apache/clerezza/platform/accountcontrolpanel/html/PersonBox.scala
----------------------------------------------------------------------
diff --git a/platform.accountcontrolpanel/platform.accountcontrolpanel.core/src/main/scala/org/apache/clerezza/platform/accountcontrolpanel/html/PersonBox.scala b/platform.accountcontrolpanel/platform.accountcontrolpanel.core/src/main/scala/org/apache/clerezza/platform/accountcontrolpanel/html/PersonBox.scala
index ada733a..2b9913c 100644
--- a/platform.accountcontrolpanel/platform.accountcontrolpanel.core/src/main/scala/org/apache/clerezza/platform/accountcontrolpanel/html/PersonBox.scala
+++ b/platform.accountcontrolpanel/platform.accountcontrolpanel.core/src/main/scala/org/apache/clerezza/platform/accountcontrolpanel/html/PersonBox.scala
@@ -32,32 +32,32 @@ import scala.xml.Text
* Metadata class for the person panel
*/
class PersonBox extends SRenderlet {
- def getRdfType() = FOAF.Person
-
- override def getModePattern = "box-naked"
-
- override def renderedPage(arguments: XmlResult.Arguments) = new XmlPerson(arguments)
-
- /**
- * Content class for the Person Panel
- */
- class XmlPerson(args: XmlResult.Arguments) extends XmlResult(args) {
-
- import RenderingUtility._
-
- //
- // the content itself.
- // This is the piece that is closest to a pure ssp, though there is still too much code in it
- //
-
- override def content = {
- val pixml= getAgentPix(res)
- <div class="personInABox">
- <table><tr><td>{pixml}</td></tr>
- <tr><td>{new Text(getName(res))}</td></tr>
- </table>
- </div>
- }
-
- }
+ def getRdfType() = FOAF.Person
+
+ override def getModePattern = "box-naked"
+
+ override def renderedPage(arguments: XmlResult.Arguments) = new XmlPerson(arguments)
+
+ /**
+ * Content class for the Person Panel
+ */
+ class XmlPerson(args: XmlResult.Arguments) extends XmlResult(args) {
+
+ import RenderingUtility._
+
+ //
+ // the content itself.
+ // This is the piece that is closest to a pure ssp, though there is still too much code in it
+ //
+
+ override def content = {
+ val pixml= getAgentPix(res)
+ <div class="personInABox">
+ <table><tr><td>{pixml}</td></tr>
+ <tr><td>{new Text(getName(res))}</td></tr>
+ </table>
+ </div>
+ }
+
+ }
}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/platform.accountcontrolpanel/platform.accountcontrolpanel.core/src/main/scala/org/apache/clerezza/platform/accountcontrolpanel/html/ProfilePanel.scala
----------------------------------------------------------------------
diff --git a/platform.accountcontrolpanel/platform.accountcontrolpanel.core/src/main/scala/org/apache/clerezza/platform/accountcontrolpanel/html/ProfilePanel.scala b/platform.accountcontrolpanel/platform.accountcontrolpanel.core/src/main/scala/org/apache/clerezza/platform/accountcontrolpanel/html/ProfilePanel.scala
index d0d095e..7d65dff 100644
--- a/platform.accountcontrolpanel/platform.accountcontrolpanel.core/src/main/scala/org/apache/clerezza/platform/accountcontrolpanel/html/ProfilePanel.scala
+++ b/platform.accountcontrolpanel/platform.accountcontrolpanel.core/src/main/scala/org/apache/clerezza/platform/accountcontrolpanel/html/ProfilePanel.scala
@@ -33,263 +33,263 @@ import org.apache.clerezza.rdf.ontologies.{RDFS, DC, FOAF}
class ProfilePanel extends SRenderlet {
- override def getRdfType() = CONTROLPANEL.ProfilePage
-
- override def renderedPage(arguments: XmlResult.Arguments) = new ProfilePanelXHTML(arguments)
-
- class ProfilePanelXHTML(arguments: XmlResult.Arguments) extends XmlResult(arguments ) {
-
- //set header properties
-
- resultDocModifier.addStyleSheet("/account-control-panel/style/profile.css");
- resultDocModifier.addScriptReference("/account-control-panel/scripts/profile.js");
- resultDocModifier.addScriptReference("/account-control-panel/scripts/IEKeygen.js");
- resultDocModifier.setTitle("Account Control Panel");
- resultDocModifier.addNodes2Elem("tx-module", <h1>Account Control Panel</h1>);
- resultDocModifier.addNodes2Elem("tx-module-tabs-ol", <li class="tx-active"><a href="#">Profile</a></li>);
- resultDocModifier.addNodes2Elem("tx-module-tabs-ol", <li><a href="control-panel">Settings</a></li>);
-
- //constants and variables
-
- lazy val agent: RichGraphNode = res / FOAF.primaryTopic
-
-
- // the content itself
- // clearly in this case there is so much more in the the methods, that one could hesitate to call this an ssp
-
- override def content = {
- <div id="tx-content">
- <h2>Personal Profile</h2>{agent ! match {
- case _: BNode => createWebId()
- case _: UriRef => existingWebId()
- }}
- </div>
-
- }
-
- //methods used to create content
-
- def cp(s: Any) = new UriRef("http://clerezza.org/2009/03/controlpanel#" + s)
- def platform(s: Any) = new UriRef("http://clerezza.org/2009/08/platform#" + s)
-
-
- def createWebId() = {
- <h3>Associate Profile to WebID</h3>
- <div id="newOrExistingSelection">
- <p>Your profile is not currently associated to a WebID. A WebID allows you
- to link your friends as well as to log-in to many sites (supporting foaf+ssl
- or open-id).
- </p>
- <p>You may either create a new WebID or associate your account to an
- existing WebID. Only creating a WebID here will allow you to manage your
- profile here.
- </p>
- <form action="#" id="associateSelection">
- <button type="button" id="newWebIdButton">Create a new Web-Id</button>
- <button type="button" id="existingWebIdButton">I already have a Web-ID and want to use it</button>
- </form>
- </div>
- <div id="createNewWebId">
- <p>You have chosen to create a new Web-Id.</p>
- <p>The Web-ID will be created as follows:
- <br/>
- <ol>
- <li>Web-Id:
- {var webId = res / cp("suggestedPPDUri") *;
- webId += "#me";
- webId}
- </li>
- <li>Personal-Profile Document: {res/cp("suggestedPPDUri")*}</li>
- </ol>
- </p>
- <form method="post" action="profile/create-new-web-id">
- <input value="Create it!" type="submit"/>
- </form>
- </div>
- <div id="setExistingWebId">
- <p>Please enter your Web-Id, if your Web-Id supports Foaf+SSL you will
- be able to use it to log in to this site.</p>
- <form method="post" action="profile/set-existing-webid">
- <label for="webid">WebID</label> <input type="text" name="webid" size="80" title="Web-ID"/>
- <br/>
- <input value="Associate Profile to Web-Id" type="submit"/>
- <p/>
- </form>
- </div>
-
- }
-
- def existingWebId() = {
- if ((res / cp("isLocalProfile")).as[Boolean]) {
- existingLocalWebId()
- } else {
- roamingUser()
- }
- }
-
-
- def existingLocalWebId() = {
- <h3>Manage your profile</h3>
- <p>Here you can change your public profile.</p>
-
- <form method="post" action="profile/modify">
- <input type="hidden" name="webId" value={agent *}/>
- <table>
- <tr><td class="formlabel">Name:</td>
- <td><input type="text" name="name" value={agent / FOAF.name *}/></td>
- </tr>
- <tr><td class="formlabel multiline">Description:</td>
- <td><textarea name="description" rows="3" cols="80">{agent / DC.description *}</textarea></td>
- </tr>
- <tr><td class="formlabel"><input value="Modify" type="submit"/></td><td/></tr>
- </table>
-
- <p/>
- </form>
-
- <h3>Contacts</h3>
-
- <table>{ var i =0
- val friends = for (friend <- agent/FOAF.knows) yield {
- <td><form method="post" action="profile/deleteContact">
- {
- friend! match {
- case webId: UriRef => render(webId, "box-naked")
- case _ => render(friend, "box-naked")
- }
- }
- <br/>
- <input type="hidden" name="contactWebId" value={friend*}/>
- <input type="submit" value="remove contact" />
- </form></td>
- /*render(friend!.asInstanceOf[UriRef])
- import PersonPanel._
- <td class="personInABox">{personInABox(friend)}</td>*/
- }
- for (row <- friends.grouped(5)) yield <tr>{row}</tr>
- }</table>
- <form id="addContact" method="get" action="profile/addContact">
- <label for="contactWebId">Add contact bei WebId:<br/></label>
- <input type="text" name="contactWebId" size="80"/><input type="submit" value="add contact" />
- </form>
-
- <h3>Key and Certificate Creation</h3>
-
- <script type="text/javascript"> <![CDATA[$(document).ready( function() { configurePage(); } ); ]]> </script>
-
- <div id="iehelptext" style="display: none;">
- <p>Using Internet Explorer under Windows Vista or above or Windows
- Server 2008, you need to configure the following for this to work:</p>
- <ul>
- <li>Add this site to the <i>Trusted Sites</i> list: in Internet
- Options -> Security -> Trusted Sites -> Sites -> Add ...</li>
- <li>You may need to configure the trust level (in this tab), using
- <i>Custom Level...</i>: enable <i>Initialize and script ActiveX
- controls not marked as safe for scripting</i>.</li>
- <li>If you are using Windows Vista without SP1 or above, you will
- probably need to install <a href="cacert.crt">this certificate</a> as a
- Trusted Root Certification Authority Certificate for your own
- certificate installation to succeed. You should probably remove that
- trusted root CA certificate afterwards.</li>
- </ul>
- </div>
- <form id="keygenform" method="post" action="profile/keygen">
- <input name="webId" id="webId" type="hidden" value={agent*} />
- <table>
- <colgroup><col width="1*"/><col/></colgroup>
- <tr>
- <td class="formlabel">Certificate Name:</td>
- <td>
- <input alt="create a certificate name that will help you distinguish it from others you may have" name="cn"
- size="35" id="cn" type="text" value={ ((agent/FOAF.name*)+"@clerezza")}/>
- </td>
- </tr>
- <tr>
- <td class="formlabel">Key strength:</td>
- <td id="keystrenghtd">
- <keygen id="spkac" name="spkac" challenge="TheChallenge1"/>
- </td>
- </tr>
- <tr>
- <td class="formlabel">Valid for:</td>
- <td>
- <input type="text" name="days" value="365" size="4"/>
- days <input type="text" name="hours" value="0.0" size="4"/> hours</td>
- </tr>
- <tr>
- <td class="formlabel">Comment:</td>
- <td><input type="text" name="comment" value="" size="80"/></td>
- </tr>
- <tr><td class="formlabel"><input id="keygensubmit" type="submit" value="create certificate" /></td><td/></tr>
- </table>
- </form>
- <h3>Existing Certificates</h3>
- <form method="post" action="profile/deletekey">
- <table>
- <tr><th>Delete</th><th>Certificate Details</th></tr>
- <input name="webId" id="webId" type="hidden" value={agent*} />
- <tbody>{
- for (key <- agent/-CERT.identity )
- yield { val modulus = (key/RSA.modulus).as[BigInteger]
- if (modulus == null) <span/> //todo: broken public key, should delete it
- else <tr><td><input type="checkbox" name="keyhash" value={modulus.hashCode().toString()}/></td>
- <td><table>
- <tr><td class="propvalue">Created:</td><td>{beautifyDate(key/DC.date )}</td></tr>
- <tr><td class="propvalue">Comment:</td><td>{ key/RDFS.comment* }</td></tr>
- <tr><td class="propvalue multiline">Modulus:</td><td><code>{ beautifyHex(key/RSA.modulus) }</code></td></tr>
- <tr><td class="propvalue">Exponent:</td><td><code>{ beautifyInt(key/RSA.public_exponent) }</code></td></tr>
- </table>
- </td>
- </tr>}
- }</tbody>
- </table>
- <input type="submit" value="Disable Keys"/>
- </form>
- <p></p>
-
- }
-
- def roamingUser() = {
- <h3>Using remote profile</h3>
- <p>
- {agent / FOAF.nick *}, you have accessed this site using your WebID
- {"<" + (agent *) + ">"}
- which has not been
- created on this site.To edit your profile you should visit the site issuing the
- profile.</p>
- }
-
-
-
-
- def beautifyDate(dtIt: CollectedIter[RichGraphNode]) {
- if (0 == dtIt.size) return "_"
- DateFormat.getDateTimeInstance(DateFormat.LONG,DateFormat.FULL).format(dtIt.as[Date])
- }
-
-
- def beautifyHex(dtIt: CollectedIter[RichGraphNode]): String = {
- if (0 == dtIt.size) return "warning! missing. Key invalid"
- //this is a problem, it should always be here or it is invalid, and key should be removed
- val bigint: BigInteger = dtIt.as[BigInteger]
- val bstr = bigint.toString(16).toUpperCase;
- val sbuf = new StringBuffer(bstr.size + (bstr.size/2)+10)
- var cnt = 0
- for (c <- bstr.toCharArray) {
- if ((cnt % 2) == 0) sbuf.append(' ')
- sbuf.append(c)
- cnt += 1
- }
- sbuf.toString
- }
-
-
-
- def beautifyInt(dtIt: CollectedIter[RichGraphNode] ) :String = {
- if (0 == dtIt.size) return "warning! missing. Key invalid"
- else return dtIt.as[BigInteger].toString
- }
- }
+ override def getRdfType() = CONTROLPANEL.ProfilePage
+
+ override def renderedPage(arguments: XmlResult.Arguments) = new ProfilePanelXHTML(arguments)
+
+ class ProfilePanelXHTML(arguments: XmlResult.Arguments) extends XmlResult(arguments ) {
+
+ //set header properties
+
+ resultDocModifier.addStyleSheet("/account-control-panel/style/profile.css");
+ resultDocModifier.addScriptReference("/account-control-panel/scripts/profile.js");
+ resultDocModifier.addScriptReference("/account-control-panel/scripts/IEKeygen.js");
+ resultDocModifier.setTitle("Account Control Panel");
+ resultDocModifier.addNodes2Elem("tx-module", <h1>Account Control Panel</h1>);
+ resultDocModifier.addNodes2Elem("tx-module-tabs-ol", <li class="tx-active"><a href="#">Profile</a></li>);
+ resultDocModifier.addNodes2Elem("tx-module-tabs-ol", <li><a href="control-panel">Settings</a></li>);
+
+ //constants and variables
+
+ lazy val agent: RichGraphNode = res / FOAF.primaryTopic
+
+
+ // the content itself
+ // clearly in this case there is so much more in the the methods, that one could hesitate to call this an ssp
+
+ override def content = {
+ <div id="tx-content">
+ <h2>Personal Profile</h2>{agent ! match {
+ case _: BNode => createWebId()
+ case _: UriRef => existingWebId()
+ }}
+ </div>
+
+ }
+
+ //methods used to create content
+
+ def cp(s: Any) = new UriRef("http://clerezza.org/2009/03/controlpanel#" + s)
+ def platform(s: Any) = new UriRef("http://clerezza.org/2009/08/platform#" + s)
+
+
+ def createWebId() = {
+ <h3>Associate Profile to WebID</h3>
+ <div id="newOrExistingSelection">
+ <p>Your profile is not currently associated to a WebID. A WebID allows you
+ to link your friends as well as to log-in to many sites (supporting foaf+ssl
+ or open-id).
+ </p>
+ <p>You may either create a new WebID or associate your account to an
+ existing WebID. Only creating a WebID here will allow you to manage your
+ profile here.
+ </p>
+ <form action="#" id="associateSelection">
+ <button type="button" id="newWebIdButton">Create a new Web-Id</button>
+ <button type="button" id="existingWebIdButton">I already have a Web-ID and want to use it</button>
+ </form>
+ </div>
+ <div id="createNewWebId">
+ <p>You have chosen to create a new Web-Id.</p>
+ <p>The Web-ID will be created as follows:
+ <br/>
+ <ol>
+ <li>Web-Id:
+ {var webId = res / cp("suggestedPPDUri") *;
+ webId += "#me";
+ webId}
+ </li>
+ <li>Personal-Profile Document: {res/cp("suggestedPPDUri")*}</li>
+ </ol>
+ </p>
+ <form method="post" action="profile/create-new-web-id">
+ <input value="Create it!" type="submit"/>
+ </form>
+ </div>
+ <div id="setExistingWebId">
+ <p>Please enter your Web-Id, if your Web-Id supports Foaf+SSL you will
+ be able to use it to log in to this site.</p>
+ <form method="post" action="profile/set-existing-webid">
+ <label for="webid">WebID</label> <input type="text" name="webid" size="80" title="Web-ID"/>
+ <br/>
+ <input value="Associate Profile to Web-Id" type="submit"/>
+ <p/>
+ </form>
+ </div>
+
+ }
+
+ def existingWebId() = {
+ if ((res / cp("isLocalProfile")).as[Boolean]) {
+ existingLocalWebId()
+ } else {
+ roamingUser()
+ }
+ }
+
+
+ def existingLocalWebId() = {
+ <h3>Manage your profile</h3>
+ <p>Here you can change your public profile.</p>
+
+ <form method="post" action="profile/modify">
+ <input type="hidden" name="webId" value={agent *}/>
+ <table>
+ <tr><td class="formlabel">Name:</td>
+ <td><input type="text" name="name" value={agent / FOAF.name *}/></td>
+ </tr>
+ <tr><td class="formlabel multiline">Description:</td>
+ <td><textarea name="description" rows="3" cols="80">{agent / DC.description *}</textarea></td>
+ </tr>
+ <tr><td class="formlabel"><input value="Modify" type="submit"/></td><td/></tr>
+ </table>
+
+ <p/>
+ </form>
+
+ <h3>Contacts</h3>
+
+ <table>{ var i =0
+ val friends = for (friend <- agent/FOAF.knows) yield {
+ <td><form method="post" action="profile/deleteContact">
+ {
+ friend! match {
+ case webId: UriRef => render(webId, "box-naked")
+ case _ => render(friend, "box-naked")
+ }
+ }
+ <br/>
+ <input type="hidden" name="contactWebId" value={friend*}/>
+ <input type="submit" value="remove contact" />
+ </form></td>
+ /*render(friend!.asInstanceOf[UriRef])
+ import PersonPanel._
+ <td class="personInABox">{personInABox(friend)}</td>*/
+ }
+ for (row <- friends.grouped(5)) yield <tr>{row}</tr>
+ }</table>
+ <form id="addContact" method="get" action="profile/addContact">
+ <label for="contactWebId">Add contact bei WebId:<br/></label>
+ <input type="text" name="contactWebId" size="80"/><input type="submit" value="add contact" />
+ </form>
+
+ <h3>Key and Certificate Creation</h3>
+
+ <script type="text/javascript"> <![CDATA[$(document).ready( function() { configurePage(); } ); ]]> </script>
+
+ <div id="iehelptext" style="display: none;">
+ <p>Using Internet Explorer under Windows Vista or above or Windows
+ Server 2008, you need to configure the following for this to work:</p>
+ <ul>
+ <li>Add this site to the <i>Trusted Sites</i> list: in Internet
+ Options -> Security -> Trusted Sites -> Sites -> Add ...</li>
+ <li>You may need to configure the trust level (in this tab), using
+ <i>Custom Level...</i>: enable <i>Initialize and script ActiveX
+ controls not marked as safe for scripting</i>.</li>
+ <li>If you are using Windows Vista without SP1 or above, you will
+ probably need to install <a href="cacert.crt">this certificate</a> as a
+ Trusted Root Certification Authority Certificate for your own
+ certificate installation to succeed. You should probably remove that
+ trusted root CA certificate afterwards.</li>
+ </ul>
+ </div>
+ <form id="keygenform" method="post" action="profile/keygen">
+ <input name="webId" id="webId" type="hidden" value={agent*} />
+ <table>
+ <colgroup><col width="1*"/><col/></colgroup>
+ <tr>
+ <td class="formlabel">Certificate Name:</td>
+ <td>
+ <input alt="create a certificate name that will help you distinguish it from others you may have" name="cn"
+ size="35" id="cn" type="text" value={ ((agent/FOAF.name*)+"@clerezza")}/>
+ </td>
+ </tr>
+ <tr>
+ <td class="formlabel">Key strength:</td>
+ <td id="keystrenghtd">
+ <keygen id="spkac" name="spkac" challenge="TheChallenge1"/>
+ </td>
+ </tr>
+ <tr>
+ <td class="formlabel">Valid for:</td>
+ <td>
+ <input type="text" name="days" value="365" size="4"/>
+ days <input type="text" name="hours" value="0.0" size="4"/> hours</td>
+ </tr>
+ <tr>
+ <td class="formlabel">Comment:</td>
+ <td><input type="text" name="comment" value="" size="80"/></td>
+ </tr>
+ <tr><td class="formlabel"><input id="keygensubmit" type="submit" value="create certificate" /></td><td/></tr>
+ </table>
+ </form>
+ <h3>Existing Certificates</h3>
+ <form method="post" action="profile/deletekey">
+ <table>
+ <tr><th>Delete</th><th>Certificate Details</th></tr>
+ <input name="webId" id="webId" type="hidden" value={agent*} />
+ <tbody>{
+ for (key <- agent/-CERT.identity )
+ yield { val modulus = (key/RSA.modulus).as[BigInteger]
+ if (modulus == null) <span/> //todo: broken public key, should delete it
+ else <tr><td><input type="checkbox" name="keyhash" value={modulus.hashCode().toString()}/></td>
+ <td><table>
+ <tr><td class="propvalue">Created:</td><td>{beautifyDate(key/DC.date )}</td></tr>
+ <tr><td class="propvalue">Comment:</td><td>{ key/RDFS.comment* }</td></tr>
+ <tr><td class="propvalue multiline">Modulus:</td><td><code>{ beautifyHex(key/RSA.modulus) }</code></td></tr>
+ <tr><td class="propvalue">Exponent:</td><td><code>{ beautifyInt(key/RSA.public_exponent) }</code></td></tr>
+ </table>
+ </td>
+ </tr>}
+ }</tbody>
+ </table>
+ <input type="submit" value="Disable Keys"/>
+ </form>
+ <p></p>
+
+ }
+
+ def roamingUser() = {
+ <h3>Using remote profile</h3>
+ <p>
+ {agent / FOAF.nick *}, you have accessed this site using your WebID
+ {"<" + (agent *) + ">"}
+ which has not been
+ created on this site.To edit your profile you should visit the site issuing the
+ profile.</p>
+ }
+
+
+
+
+ def beautifyDate(dtIt: CollectedIter[RichGraphNode]) {
+ if (0 == dtIt.size) return "_"
+ DateFormat.getDateTimeInstance(DateFormat.LONG,DateFormat.FULL).format(dtIt.as[Date])
+ }
+
+
+ def beautifyHex(dtIt: CollectedIter[RichGraphNode]): String = {
+ if (0 == dtIt.size) return "warning! missing. Key invalid"
+ //this is a problem, it should always be here or it is invalid, and key should be removed
+ val bigint: BigInteger = dtIt.as[BigInteger]
+ val bstr = bigint.toString(16).toUpperCase;
+ val sbuf = new StringBuffer(bstr.size + (bstr.size/2)+10)
+ var cnt = 0
+ for (c <- bstr.toCharArray) {
+ if ((cnt % 2) == 0) sbuf.append(' ')
+ sbuf.append(c)
+ cnt += 1
+ }
+ sbuf.toString
+ }
+
+
+
+ def beautifyInt(dtIt: CollectedIter[RichGraphNode] ) :String = {
+ if (0 == dtIt.size) return "warning! missing. Key invalid"
+ else return dtIt.as[BigInteger].toString
+ }
+ }
}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/platform.accountcontrolpanel/platform.accountcontrolpanel.core/src/main/scala/org/apache/clerezza/platform/accountcontrolpanel/html/RenderingUtility.scala
----------------------------------------------------------------------
diff --git a/platform.accountcontrolpanel/platform.accountcontrolpanel.core/src/main/scala/org/apache/clerezza/platform/accountcontrolpanel/html/RenderingUtility.scala b/platform.accountcontrolpanel/platform.accountcontrolpanel.core/src/main/scala/org/apache/clerezza/platform/accountcontrolpanel/html/RenderingUtility.scala
index 7de03f0..735aee0 100644
--- a/platform.accountcontrolpanel/platform.accountcontrolpanel.core/src/main/scala/org/apache/clerezza/platform/accountcontrolpanel/html/RenderingUtility.scala
+++ b/platform.accountcontrolpanel/platform.accountcontrolpanel.core/src/main/scala/org/apache/clerezza/platform/accountcontrolpanel/html/RenderingUtility.scala
@@ -35,60 +35,60 @@ import rdf.scala.utils.Preamble._
* Some utility methods for the renderlets
*/
object RenderingUtility {
- val emptyText = new Text("")
+ val emptyText = new Text("")
- def ifE[T](arg:T)(template: T=>Node ):NodeSeq = {
- def isEmpty(arg: Any): Boolean = {
- arg match {
- case prod: Product => prod.productIterator.forall(isEmpty(_))
- case str: String => (str.size == 0)
- case it: CollectedIter[RichGraphNode] => (it.size == 0)
- case node: RichGraphNode => (null == node)
- case other: AnyRef => (null == other)
- case _ => false //literals can't be empty
- }
- }
- if (isEmpty(arg)) return emptyText else template(arg)
- }
+ def ifE[T](arg:T)(template: T=>Node ):NodeSeq = {
+ def isEmpty(arg: Any): Boolean = {
+ arg match {
+ case prod: Product => prod.productIterator.forall(isEmpty(_))
+ case str: String => (str.size == 0)
+ case it: CollectedIter[RichGraphNode] => (it.size == 0)
+ case node: RichGraphNode => (null == node)
+ case other: AnyRef => (null == other)
+ case _ => false //literals can't be empty
+ }
+ }
+ if (isEmpty(arg)) return emptyText else template(arg)
+ }
- def firstOf(node: RichGraphNode, uris: UriRef*):CollectedIter[RichGraphNode] = {
- for (uri <- uris) {
- val res : CollectedIter[RichGraphNode] = node/uri
- if (res.size>0) return res
- }
- return new CollectedIter[RichGraphNode]()
- }
+ def firstOf(node: RichGraphNode, uris: UriRef*):CollectedIter[RichGraphNode] = {
+ for (uri <- uris) {
+ val res : CollectedIter[RichGraphNode] = node/uri
+ if (res.size>0) return res
+ }
+ return new CollectedIter[RichGraphNode]()
+ }
- /**
- * Show a person: a picture, a link to their local profile and their name
- * Different default icons should be shown if the agent is a person, company, group, robot...
- *
- * assumes the p is WebID node (can change later)
- */
- def getAgentPix(p: RichGraphNode) = {
- val pix = firstOf(p, FOAF.depiction, FOAF.logo, FOAF.img).getNode match {
- case uri: UriRef => uri.getUnicodeString
- case _ => "http://upload.wikimedia.org/wikipedia/commons/0/0a/Gnome-stock_person.svg"
- }
- <a href={"/browse/person?uri="+encode(p*)}><img class="mugshot" src={pix}/></a>
- }
+ /**
+ * Show a person: a picture, a link to their local profile and their name
+ * Different default icons should be shown if the agent is a person, company, group, robot...
+ *
+ * assumes the p is WebID node (can change later)
+ */
+ def getAgentPix(p: RichGraphNode) = {
+ val pix = firstOf(p, FOAF.depiction, FOAF.logo, FOAF.img).getNode match {
+ case uri: UriRef => uri.getUnicodeString
+ case _ => "http://upload.wikimedia.org/wikipedia/commons/0/0a/Gnome-stock_person.svg"
+ }
+ <a href={"/browse/person?uri="+encode(p*)}><img class="mugshot" src={pix}/></a>
+ }
- private def encode(url: String): String = URLEncoder.encode(url,"UTF8")
+ private def encode(url: String): String = URLEncoder.encode(url,"UTF8")
- /**
- * get a usable name from the properties available including nick
- */
- def getName(p: RichGraphNode): String = {
- val name = p/FOAF.name*;
- if ("" != name ) { return name }
- val firstNm: String = p/FOAF.firstName*;
- val fmlyNm :String = firstOf(p, FOAF.family_name,FOAF.familyName)*;
- if ("" != firstNm || "" != fmlyNm) { return firstNm+" "+fmlyNm }
- return p*
+ /**
+ * get a usable name from the properties available including nick
+ */
+ def getName(p: RichGraphNode): String = {
+ val name = p/FOAF.name*;
+ if ("" != name ) { return name }
+ val firstNm: String = p/FOAF.firstName*;
+ val fmlyNm :String = firstOf(p, FOAF.family_name,FOAF.familyName)*;
+ if ("" != firstNm || "" != fmlyNm) { return firstNm+" "+fmlyNm }
+ return p*
- }
+ }
}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/platform.accountcontrolpanel/platform.accountcontrolpanel.core/src/main/scala/org/apache/clerezza/platform/accountcontrolpanel/html/SettingsPanel.scala
----------------------------------------------------------------------
diff --git a/platform.accountcontrolpanel/platform.accountcontrolpanel.core/src/main/scala/org/apache/clerezza/platform/accountcontrolpanel/html/SettingsPanel.scala b/platform.accountcontrolpanel/platform.accountcontrolpanel.core/src/main/scala/org/apache/clerezza/platform/accountcontrolpanel/html/SettingsPanel.scala
index afa4ffa..a2a58e6 100644
--- a/platform.accountcontrolpanel/platform.accountcontrolpanel.core/src/main/scala/org/apache/clerezza/platform/accountcontrolpanel/html/SettingsPanel.scala
+++ b/platform.accountcontrolpanel/platform.accountcontrolpanel.core/src/main/scala/org/apache/clerezza/platform/accountcontrolpanel/html/SettingsPanel.scala
@@ -26,10 +26,10 @@ import org.apache.clerezza.platform.typerendering.scala._
class SettingsPanel extends SRenderlet {
- val getRdfType = CONTROLPANEL.SettingsPage
+ val getRdfType = CONTROLPANEL.SettingsPage
- override def renderedPage(arguments: XmlResult.Arguments) = new XmlResult(arguments ) {
- override def content = {
+ override def renderedPage(arguments: XmlResult.Arguments) = new XmlResult(arguments ) {
+ override def content = {
import org.apache.clerezza.rdf.core.UriRef
import scala.xml.NodeBuffer
import scala.collection.mutable.ListBuffer
@@ -43,121 +43,121 @@ resultDocModifier.addNodes2Elem("tx-module-tabs-ol", <li><a href="profile">Profi
resultDocModifier.addNodes2Elem("tx-module-tabs-ol", <li class="tx-active"><a href="#">Settings</a></li>);
if ((res/cp("userBundlePermission")*) == "true") {
- nodeBuff +=(<h2>Bundle Control Panel</h2>
- <h3>Install Bundle</h3>
-
- <form method="post" action="control-panel/install-bundle" enctype="multipart/form-data">
- <input type="file" class="FieldText" name="bundle" size="30" title="bundle path"/><br/><br/>
- <input style="width: 5em;" value="Install" type="submit"/><p />
- </form>
- <br/><br/>
- <h3>User Bundles</h3>
- <table border="1">
- <tbody>
- <tr>
- <th>Location</th>
- <th>Status</th>
- <th colspan="4">Action</th>
- </tr>
-
- {for (renderlet <- (res/-osgi("owner")).sort((a,b) => ((a*)<(b*)))) yield
- <tr>
- <td>{renderlet*}</td>
- <td>{renderlet/osgi("status")* match {
- case "2" => "Installed"
- case "4" => "Resolved"
- case "8" => "Starting"
- case "16" => "Stopping"
- case "32" => "Active"
- }}
- </td>
- {if (((renderlet/osgi("bundle_id")).length) > 0)
- <td>
- <form method="post" action="control-panel/start-bundle">
- <input name="bundleId" value={(renderlet/osgi("bundle_id"))*} type="hidden"/>
- <input value="start" type="submit"/>
- </form>
- </td>
- <td>
- <form method="post" action="control-panel/stop-bundle">
- <input name="bundleId" value={(renderlet/osgi("bundle_id"))*} type="hidden"/>
- <input value="stop" type="submit"/>
- </form>
- </td>
- <td>
- <form method="post" action="control-panel/uninstall-bundle">
- <input name="bundleId" value={(renderlet/osgi("bundle_id"))*} type="hidden"/>
- <input value="uninstall" type="submit"/>
- </form>
- </td>
- else
- <td colspan="3">Not registered as bundle</td>}
- </tr>
- }
- </tbody>
- </table>
- <br/>)
+ nodeBuff +=(<h2>Bundle Control Panel</h2>
+ <h3>Install Bundle</h3>
+
+ <form method="post" action="control-panel/install-bundle" enctype="multipart/form-data">
+ <input type="file" class="FieldText" name="bundle" size="30" title="bundle path"/><br/><br/>
+ <input style="width: 5em;" value="Install" type="submit"/><p />
+ </form>
+ <br/><br/>
+ <h3>User Bundles</h3>
+ <table border="1">
+ <tbody>
+ <tr>
+ <th>Location</th>
+ <th>Status</th>
+ <th colspan="4">Action</th>
+ </tr>
+
+ {for (renderlet <- (res/-osgi("owner")).sort((a,b) => ((a*)<(b*)))) yield
+ <tr>
+ <td>{renderlet*}</td>
+ <td>{renderlet/osgi("status")* match {
+ case "2" => "Installed"
+ case "4" => "Resolved"
+ case "8" => "Starting"
+ case "16" => "Stopping"
+ case "32" => "Active"
+ }}
+ </td>
+ {if (((renderlet/osgi("bundle_id")).length) > 0)
+ <td>
+ <form method="post" action="control-panel/start-bundle">
+ <input name="bundleId" value={(renderlet/osgi("bundle_id"))*} type="hidden"/>
+ <input value="start" type="submit"/>
+ </form>
+ </td>
+ <td>
+ <form method="post" action="control-panel/stop-bundle">
+ <input name="bundleId" value={(renderlet/osgi("bundle_id"))*} type="hidden"/>
+ <input value="stop" type="submit"/>
+ </form>
+ </td>
+ <td>
+ <form method="post" action="control-panel/uninstall-bundle">
+ <input name="bundleId" value={(renderlet/osgi("bundle_id"))*} type="hidden"/>
+ <input value="uninstall" type="submit"/>
+ </form>
+ </td>
+ else
+ <td colspan="3">Not registered as bundle</td>}
+ </tr>
+ }
+ </tbody>
+ </table>
+ <br/>)
}
if((res/cp("changePasswordPermission")*) == "true") {
- nodeBuff +=(<h2>Change Password</h2>
-
-
- <form action="control-panel/change-password" method="post">
- <fieldset>
- <ol style="display: block;">
- <li class="tx-line" style="background-image: none;">
- <label>Current Password:</label>
- <span class="tx-item">
- <input type="password" name="oldPW"/>
- </span>
- </li>
- <li class="tx-line" style="background-image: none;">
- <label>New Password:</label>
- <span class="tx-item">
- <input type="password" name="newPW"/>
- </span>
- </li>
- <li class="tx-line" style="background-image: none;">
- <label>Confirm new Password:</label>
- <span class="tx-item">
- <input type="password" name="confirmNewPW"/>
- </span>
- </li>
- <br />
- <input style="width: 5em;" type="submit" name="submit" value="Submit"/>
- </ol>
- <br/>
- </fieldset>
- </form>)
+ nodeBuff +=(<h2>Change Password</h2>
+
+
+ <form action="control-panel/change-password" method="post">
+ <fieldset>
+ <ol style="display: block;">
+ <li class="tx-line" style="background-image: none;">
+ <label>Current Password:</label>
+ <span class="tx-item">
+ <input type="password" name="oldPW"/>
+ </span>
+ </li>
+ <li class="tx-line" style="background-image: none;">
+ <label>New Password:</label>
+ <span class="tx-item">
+ <input type="password" name="newPW"/>
+ </span>
+ </li>
+ <li class="tx-line" style="background-image: none;">
+ <label>Confirm new Password:</label>
+ <span class="tx-item">
+ <input type="password" name="confirmNewPW"/>
+ </span>
+ </li>
+ <br />
+ <input style="width: 5em;" type="submit" name="submit" value="Submit"/>
+ </ol>
+ <br/>
+ </fieldset>
+ </form>)
}
if((res/cp("changedPassword")).length > 0) {
- nodeBuff +=(<br /><span>Password has not changed, either wrong current password or the
- new password and the confirmation didn't match!<br /><br /></span>)
+ nodeBuff +=(<br /><span>Password has not changed, either wrong current password or the
+ new password and the confirmation didn't match!<br /><br /></span>)
}
nodeBuff +=(<h2>Change user's default language</h2>
- <form method="post" action="control-panel/change-language">
- {render(context/platform("instance")/platform("languages"), "naked")}
- <br/><br/>
- <script type="text/javascript">$("#availablelanguages").val({"'" + (context/platform("user")/platform("preferredLangInISOCode")*) + "'"})</script>
- <input style="width: 5em;" type="submit" name="submit" value="Submit"/>
- <br/><br/>
- </form>)
+ <form method="post" action="control-panel/change-language">
+ {render(context/platform("instance")/platform("languages"), "naked")}
+ <br/><br/>
+ <script type="text/javascript">$("#availablelanguages").val({"'" + (context/platform("user")/platform("preferredLangInISOCode")*) + "'"})</script>
+ <input style="width: 5em;" type="submit" name="submit" value="Submit"/>
+ <br/><br/>
+ </form>)
<div id="tx-content">
- <div class="tx-edit" style="margin-left: 0.5em;">
- {if(nodeBuff.isEmpty)
- <span>There are no settings you can configure for this account!</span>
- else
- nodeBuff
- }
- </div>
+ <div class="tx-edit" style="margin-left: 0.5em;">
+ {if(nodeBuff.isEmpty)
+ <span>There are no settings you can configure for this account!</span>
+ else
+ nodeBuff
+ }
+ </div>
</div>
- }
- }
+ }
+ }
}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/platform.accountcontrolpanel/platform.accountcontrolpanel.core/src/main/scala/org/apache/clerezza/platform/accountcontrolpanel/permissions.scala
----------------------------------------------------------------------
diff --git a/platform.accountcontrolpanel/platform.accountcontrolpanel.core/src/main/scala/org/apache/clerezza/platform/accountcontrolpanel/permissions.scala b/platform.accountcontrolpanel/platform.accountcontrolpanel.core/src/main/scala/org/apache/clerezza/platform/accountcontrolpanel/permissions.scala
index 5684ba6..ae7953f 100644
--- a/platform.accountcontrolpanel/platform.accountcontrolpanel.core/src/main/scala/org/apache/clerezza/platform/accountcontrolpanel/permissions.scala
+++ b/platform.accountcontrolpanel/platform.accountcontrolpanel.core/src/main/scala/org/apache/clerezza/platform/accountcontrolpanel/permissions.scala
@@ -32,40 +32,40 @@ import org.slf4j.scala.Logging
*/
abstract
class AbstractPermission(val accountName: String, val actions: String ="")
- extends Permission(accountName) with Logging {
+ extends Permission(accountName) with Logging {
- if (actions != "") {
- throw new RuntimeException(getClass.getName+": actions must be an empty String "+
- "(second argument only in constructor for supporting building from canonical form")
- }
+ if (actions != "") {
+ throw new RuntimeException(getClass.getName+": actions must be an empty String "+
+ "(second argument only in constructor for supporting building from canonical form")
+ }
- def getActions: String = actions
+ def getActions: String = actions
- /**
- * A subclass implies another permission if and only if they are equals
- */
+ /**
+ * A subclass implies another permission if and only if they are equals
+ */
override
- def implies(permission: Permission): Boolean = {
- logger.debug("checking for "+permission+" is implied by "+ this)
- var result: Boolean = equals(permission)
- return result
- }
-
- override
- def equals(other: Any): Boolean =
- other match {
- case that: AbstractPermission =>
- (that eq this ) || ((this.getClass == that.getClass) && accountName == that.accountName )
- case _ => false
- }
-
- /**
- * For the hashCode the class and the accountName is considered
- */
- override
- def hashCode: Int = {
- return getClass.hashCode + (if (accountName != null) accountName.hashCode else 0)
- }
+ def implies(permission: Permission): Boolean = {
+ logger.debug("checking for "+permission+" is implied by "+ this)
+ var result: Boolean = equals(permission)
+ return result
+ }
+
+ override
+ def equals(other: Any): Boolean =
+ other match {
+ case that: AbstractPermission =>
+ (that eq this ) || ((this.getClass == that.getClass) && accountName == that.accountName )
+ case _ => false
+ }
+
+ /**
+ * For the hashCode the class and the accountName is considered
+ */
+ override
+ def hashCode: Int = {
+ return getClass.hashCode + (if (accountName != null) accountName.hashCode else 0)
+ }
}
/**
@@ -74,7 +74,7 @@ class AbstractPermission(val accountName: String, val actions: String ="")
*
*/
class ChangePasswordPermission(accountName: String, actions: String ="")
- extends AbstractPermission(accountName, actions) {
+ extends AbstractPermission(accountName, actions) {
}
@@ -85,7 +85,7 @@ class ChangePasswordPermission(accountName: String, actions: String ="")
*
*/
class AccountControlPanelAppPermission(accountName: String, actions: String ="")
- extends AbstractPermission(accountName) {
+ extends AbstractPermission(accountName) {
}
@@ -97,7 +97,7 @@ class AccountControlPanelAppPermission(accountName: String, actions: String ="")
*
*/
class UserBundlePermission( accountName: String, actions: String ="")
- extends AbstractPermission(accountName) {
+ extends AbstractPermission(accountName) {
}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/platform.content.default404/src/main/scala/org/apache/clerezza/platform/content/default404/DefaultPageNotFoundService.scala
----------------------------------------------------------------------
diff --git a/platform.content.default404/src/main/scala/org/apache/clerezza/platform/content/default404/DefaultPageNotFoundService.scala b/platform.content.default404/src/main/scala/org/apache/clerezza/platform/content/default404/DefaultPageNotFoundService.scala
index af7d6fe..a0c4ab6 100644
--- a/platform.content.default404/src/main/scala/org/apache/clerezza/platform/content/default404/DefaultPageNotFoundService.scala
+++ b/platform.content.default404/src/main/scala/org/apache/clerezza/platform/content/default404/DefaultPageNotFoundService.scala
@@ -35,30 +35,30 @@ import javax.ws.rs.core.Response.Status
*/
class DefaultPageNotFoundService extends PageNotFoundService {
- private val notFoundPagePath = "/page-not-found"
+ private val notFoundPagePath = "/page-not-found"
- override def createResponse(uriInfo: UriInfo) = {
- if (uriInfo.getPath == notFoundPagePath) {
- Response.status(Status.NOT_FOUND).build();
- } else {
- val pageNotFoundUrl = new URL(uriInfo.getBaseUri.toURL, notFoundPagePath)
- AccessController.doPrivileged(
- new PrivilegedAction[Option[(String, InputStream)]] {
- def run() = {
- val connection = pageNotFoundUrl.openConnection()
- try {
- Some(connection.getContentType, connection.getInputStream)
- } catch {
- case _: FileNotFoundException => None
- }
- }
- }
- ) match {
- case Some((mediaTypeString, in)) => Response.status(Status.NOT_FOUND).`type`(mediaTypeString).entity(in).build();
- case None => Response.status(Status.NOT_FOUND).build();
- }
+ override def createResponse(uriInfo: UriInfo) = {
+ if (uriInfo.getPath == notFoundPagePath) {
+ Response.status(Status.NOT_FOUND).build();
+ } else {
+ val pageNotFoundUrl = new URL(uriInfo.getBaseUri.toURL, notFoundPagePath)
+ AccessController.doPrivileged(
+ new PrivilegedAction[Option[(String, InputStream)]] {
+ def run() = {
+ val connection = pageNotFoundUrl.openConnection()
+ try {
+ Some(connection.getContentType, connection.getInputStream)
+ } catch {
+ case _: FileNotFoundException => None
+ }
+ }
+ }
+ ) match {
+ case Some((mediaTypeString, in)) => Response.status(Status.NOT_FOUND).`type`(mediaTypeString).entity(in).build();
+ case None => Response.status(Status.NOT_FOUND).build();
+ }
- }
- }
-
+ }
+ }
+
}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/platform.content.fsadaptor/src/main/scala/org/apache/clerezza/platform/content/fsadaptor/BundleFsLoader.scala
----------------------------------------------------------------------
diff --git a/platform.content.fsadaptor/src/main/scala/org/apache/clerezza/platform/content/fsadaptor/BundleFsLoader.scala b/platform.content.fsadaptor/src/main/scala/org/apache/clerezza/platform/content/fsadaptor/BundleFsLoader.scala
index 5aa7ef8..d9548c1 100644
--- a/platform.content.fsadaptor/src/main/scala/org/apache/clerezza/platform/content/fsadaptor/BundleFsLoader.scala
+++ b/platform.content.fsadaptor/src/main/scala/org/apache/clerezza/platform/content/fsadaptor/BundleFsLoader.scala
@@ -55,242 +55,242 @@ import scala.util._
*/
class BundleFsLoader extends BundleListener with Logger with WeightedTcProvider {
- private val RESOURCE_MGRAPH_URI = new UriRef(Constants.URN_LOCAL_INSTANCE+"/web-resources.graph")
- private val cacheGraphPrefix = Constants.URN_LOCAL_INSTANCE+"/web-resources-cache.graph"
- private var currentCacheUri: UriRef = null
-
- private var tcManager: TcManager = null
- private var cgProvider: ContentGraphProvider = null
- private var startLevel: StartLevel = null
- private var pathNodes: List[PathNode] = Nil
- private var bundleList = List[Bundle]()
- private var currentCacheMGraph: MGraph = null
-
- private var frequentUpdateDirectory: Option[PathNode] = None
-
- private val virtualMGraph: MGraph = new AbstractMGraph() {
-
- private def baseGraph: TripleCollection = frequentUpdateDirectory match {
- case Some(p) => new DirectoryOverlay(p, currentCacheMGraph)
- case None => currentCacheMGraph
- }
-
- override def performFilter(s: NonLiteral, p: UriRef,
- o: Resource): java.util.Iterator[Triple] = {
- val baseIter = baseGraph.filter(s,p,o)
- new java.util.Iterator[Triple]() {
- override def next = {
- baseIter.next
- }
- override def hasNext = baseIter.hasNext
- override def remove = throw new UnsupportedOperationException
- }
- }
-
- override def size = baseGraph.size
-
- override def toString = "BundleFsLoader virtual graph"
-
- }
-
- class UpdateThread extends Thread {
-
- private var updateRequested = false;
-
- start()
-
- override def run() {
- try {
- while (!isInterrupted) {
- synchronized {
- while (!updateRequested) wait();
- }
- updateRequested = false
- updateCache()
- }
- } catch {
- case e: InterruptedException => BundleFsLoader.log.debug("Update thread interrupted");
- }
- }
-
- def update() = {
- synchronized {
- updateRequested = true
- notify();
- }
- }
- }
-
- private var updateThread: UpdateThread = null
-
-
- private def deleteCacheGraphs() {
- import collection.JavaConversions._
- for(mGraphUri <- tcManager.listMGraphs) {
- if(mGraphUri.getUnicodeString.startsWith(cacheGraphPrefix)) {
- tcManager.deleteTripleCollection(mGraphUri);
- }
- }
- }
-
- protected def activate(context: ComponentContext) {
- synchronized {
- deleteCacheGraphs()
- for (bundle <- context.getBundleContext().getBundles();
- if bundle.getState == Bundle.ACTIVE) {
- bundleList ::= bundle
- }
- context.getBundleContext().addBundleListener(this);
- updateCache
- tcManager.getTcAccessController.setRequiredReadPermissions(
- RESOURCE_MGRAPH_URI, Collections.singleton(new TcPermission(Constants.CONTENT_GRAPH_URI_STRING, TcPermission.READ)))
- cgProvider.addTemporaryAdditionGraph(RESOURCE_MGRAPH_URI)
- updateThread = new UpdateThread()
- }
- }
- protected def deactivate(context: ComponentContext) {
- synchronized {
- context.getBundleContext().removeBundleListener(this);
- updateThread.interrupt()
- cgProvider.removeTemporaryAdditionGraph(RESOURCE_MGRAPH_URI)
- tcManager.deleteTripleCollection(currentCacheUri);
- }
- }
-
- private def updateCache() = {
- def getVirtualTripleCollection(bundles: Seq[Bundle]): TripleCollection = {
- if (bundles.isEmpty) {
- new SimpleMGraph()
- } else {
- val pathNode = new BundlePathNode(bundles.head, "CLEREZZA-INF/web-resources");
- if (pathNode.isDirectory) {
- BundleFsLoader.log.debug("Creating directory overlay for "+bundles.head)
- new DirectoryOverlay(pathNode, getVirtualTripleCollection(bundles.tail))
- } else {
- getVirtualTripleCollection(bundles.tail)
- }
- }
- }
- synchronized {
- val sortedList = Sorting.stableSort(bundleList, (b:Bundle) => -startLevel.getBundleStartLevel(b))
- val newCacheUri = new UriRef(cacheGraphPrefix+System.currentTimeMillis)
- val newChacheMGraph = tcManager.createMGraph(newCacheUri);
- tcManager.getTcAccessController.setRequiredReadPermissions(
- newCacheUri, Collections.singleton(new TcPermission(Constants.CONTENT_GRAPH_URI_STRING, TcPermission.READ)))
- newChacheMGraph.addAll(getVirtualTripleCollection(sortedList))
- currentCacheMGraph = newChacheMGraph
- val oldCacheUri = currentCacheUri
- currentCacheUri = newCacheUri
- if (oldCacheUri != null) tcManager.deleteTripleCollection(oldCacheUri);
- BundleFsLoader.log.debug("updated web-resource cache")
- }
- }
-
-
-
- override def getWeight() = 30
-
- override def getMGraph(name: UriRef) = {
- if (name.equals(RESOURCE_MGRAPH_URI)) {
- virtualMGraph
- } else {
- throw new NoSuchEntityException(name);
- }
- }
-
- override def getTriples(name: UriRef) = {
- getMGraph(name);
- }
-
- override def getGraph(name: UriRef) = {
- throw new NoSuchEntityException(name);
- }
-
-
- override def listMGraphs(): java.util.Set[UriRef] = {
- java.util.Collections.singleton(RESOURCE_MGRAPH_URI);
- }
-
- override def listGraphs() = {
- new java.util.HashSet[UriRef]();
- }
-
- override def listTripleCollections() = {
- Collections.singleton(RESOURCE_MGRAPH_URI);
- }
-
- override def createMGraph(name: UriRef) = {
- throw new UnsupportedOperationException("Not supported.");
- }
-
- override def createGraph(name: UriRef, triples: TripleCollection): Graph = {
- throw new UnsupportedOperationException("Not supported.");
- }
-
- override def deleteTripleCollection(name: UriRef) {
- throw new UnsupportedOperationException("Not supported.");
- }
-
- override def getNames(graph: Graph) = {
- val result = new java.util.HashSet[UriRef]();
- result;
- }
-
-
- def bundleChanged(event: BundleEvent) {
- val bundle = event.getBundle();
- event.getType() match {
- case BundleEvent.STARTED => {
- bundleList ::= bundle
- updateThread.update()
- }
- case BundleEvent.STOPPED => {
- bundleList = bundleList.filterNot(b => b == bundle)
- updateThread.update()
- }
- case _ => BundleFsLoader.log.debug("only reacting on bundle start and stop")
- }
- }
-
-
- def bindTcManager(tcManager: TcManager) {
- this.tcManager = tcManager;
- }
-
- def unbindTcManager(tcManager: TcManager) {
- this.tcManager = null;
- }
-
- def bindContentGraphProvider(p: ContentGraphProvider) {
- cgProvider = p
- }
-
- def unbindContentGraphProvider(p: ContentGraphProvider) {
- cgProvider = null
- }
-
- def bindStartLevel(startLevel: StartLevel) {
- this.startLevel = startLevel;
- }
-
- def unbindStartLevel(startLevel: StartLevel) {
- this.startLevel = null;
- }
-
- def bindPathNode(pathNode: PathNode) {
- this.pathNodes ::= pathNode;
- frequentUpdateDirectory = Some(new MultiPathNode(pathNodes: _*))
- }
-
- def unbindPathNode(pathNode: PathNode) {
- this.pathNodes = this.pathNodes.filter(_ != pathNode);
- frequentUpdateDirectory = pathNodes match {
- case Nil => None
- case _ => Some(new MultiPathNode(pathNodes: _*))
- }
- }
-
+ private val RESOURCE_MGRAPH_URI = new UriRef(Constants.URN_LOCAL_INSTANCE+"/web-resources.graph")
+ private val cacheGraphPrefix = Constants.URN_LOCAL_INSTANCE+"/web-resources-cache.graph"
+ private var currentCacheUri: UriRef = null
+
+ private var tcManager: TcManager = null
+ private var cgProvider: ContentGraphProvider = null
+ private var startLevel: StartLevel = null
+ private var pathNodes: List[PathNode] = Nil
+ private var bundleList = List[Bundle]()
+ private var currentCacheMGraph: MGraph = null
+
+ private var frequentUpdateDirectory: Option[PathNode] = None
+
+ private val virtualMGraph: MGraph = new AbstractMGraph() {
+
+ private def baseGraph: TripleCollection = frequentUpdateDirectory match {
+ case Some(p) => new DirectoryOverlay(p, currentCacheMGraph)
+ case None => currentCacheMGraph
+ }
+
+ override def performFilter(s: NonLiteral, p: UriRef,
+ o: Resource): java.util.Iterator[Triple] = {
+ val baseIter = baseGraph.filter(s,p,o)
+ new java.util.Iterator[Triple]() {
+ override def next = {
+ baseIter.next
+ }
+ override def hasNext = baseIter.hasNext
+ override def remove = throw new UnsupportedOperationException
+ }
+ }
+
+ override def size = baseGraph.size
+
+ override def toString = "BundleFsLoader virtual graph"
+
+ }
+
+ class UpdateThread extends Thread {
+
+ private var updateRequested = false;
+
+ start()
+
+ override def run() {
+ try {
+ while (!isInterrupted) {
+ synchronized {
+ while (!updateRequested) wait();
+ }
+ updateRequested = false
+ updateCache()
+ }
+ } catch {
+ case e: InterruptedException => BundleFsLoader.log.debug("Update thread interrupted");
+ }
+ }
+
+ def update() = {
+ synchronized {
+ updateRequested = true
+ notify();
+ }
+ }
+ }
+
+ private var updateThread: UpdateThread = null
+
+
+ private def deleteCacheGraphs() {
+ import collection.JavaConversions._
+ for(mGraphUri <- tcManager.listMGraphs) {
+ if(mGraphUri.getUnicodeString.startsWith(cacheGraphPrefix)) {
+ tcManager.deleteTripleCollection(mGraphUri);
+ }
+ }
+ }
+
+ protected def activate(context: ComponentContext) {
+ synchronized {
+ deleteCacheGraphs()
+ for (bundle <- context.getBundleContext().getBundles();
+ if bundle.getState == Bundle.ACTIVE) {
+ bundleList ::= bundle
+ }
+ context.getBundleContext().addBundleListener(this);
+ updateCache
+ tcManager.getTcAccessController.setRequiredReadPermissions(
+ RESOURCE_MGRAPH_URI, Collections.singleton(new TcPermission(Constants.CONTENT_GRAPH_URI_STRING, TcPermission.READ)))
+ cgProvider.addTemporaryAdditionGraph(RESOURCE_MGRAPH_URI)
+ updateThread = new UpdateThread()
+ }
+ }
+ protected def deactivate(context: ComponentContext) {
+ synchronized {
+ context.getBundleContext().removeBundleListener(this);
+ updateThread.interrupt()
+ cgProvider.removeTemporaryAdditionGraph(RESOURCE_MGRAPH_URI)
+ tcManager.deleteTripleCollection(currentCacheUri);
+ }
+ }
+
+ private def updateCache() = {
+ def getVirtualTripleCollection(bundles: Seq[Bundle]): TripleCollection = {
+ if (bundles.isEmpty) {
+ new SimpleMGraph()
+ } else {
+ val pathNode = new BundlePathNode(bundles.head, "CLEREZZA-INF/web-resources");
+ if (pathNode.isDirectory) {
+ BundleFsLoader.log.debug("Creating directory overlay for "+bundles.head)
+ new DirectoryOverlay(pathNode, getVirtualTripleCollection(bundles.tail))
+ } else {
+ getVirtualTripleCollection(bundles.tail)
+ }
+ }
+ }
+ synchronized {
+ val sortedList = Sorting.stableSort(bundleList, (b:Bundle) => -startLevel.getBundleStartLevel(b))
+ val newCacheUri = new UriRef(cacheGraphPrefix+System.currentTimeMillis)
+ val newChacheMGraph = tcManager.createMGraph(newCacheUri);
+ tcManager.getTcAccessController.setRequiredReadPermissions(
+ newCacheUri, Collections.singleton(new TcPermission(Constants.CONTENT_GRAPH_URI_STRING, TcPermission.READ)))
+ newChacheMGraph.addAll(getVirtualTripleCollection(sortedList))
+ currentCacheMGraph = newChacheMGraph
+ val oldCacheUri = currentCacheUri
+ currentCacheUri = newCacheUri
+ if (oldCacheUri != null) tcManager.deleteTripleCollection(oldCacheUri);
+ BundleFsLoader.log.debug("updated web-resource cache")
+ }
+ }
+
+
+
+ override def getWeight() = 30
+
+ override def getMGraph(name: UriRef) = {
+ if (name.equals(RESOURCE_MGRAPH_URI)) {
+ virtualMGraph
+ } else {
+ throw new NoSuchEntityException(name);
+ }
+ }
+
+ override def getTriples(name: UriRef) = {
+ getMGraph(name);
+ }
+
+ override def getGraph(name: UriRef) = {
+ throw new NoSuchEntityException(name);
+ }
+
+
+ override def listMGraphs(): java.util.Set[UriRef] = {
+ java.util.Collections.singleton(RESOURCE_MGRAPH_URI);
+ }
+
+ override def listGraphs() = {
+ new java.util.HashSet[UriRef]();
+ }
+
+ override def listTripleCollections() = {
+ Collections.singleton(RESOURCE_MGRAPH_URI);
+ }
+
+ override def createMGraph(name: UriRef) = {
+ throw new UnsupportedOperationException("Not supported.");
+ }
+
+ override def createGraph(name: UriRef, triples: TripleCollection): Graph = {
+ throw new UnsupportedOperationException("Not supported.");
+ }
+
+ override def deleteTripleCollection(name: UriRef) {
+ throw new UnsupportedOperationException("Not supported.");
+ }
+
+ override def getNames(graph: Graph) = {
+ val result = new java.util.HashSet[UriRef]();
+ result;
+ }
+
+
+ def bundleChanged(event: BundleEvent) {
+ val bundle = event.getBundle();
+ event.getType() match {
+ case BundleEvent.STARTED => {
+ bundleList ::= bundle
+ updateThread.update()
+ }
+ case BundleEvent.STOPPED => {
+ bundleList = bundleList.filterNot(b => b == bundle)
+ updateThread.update()
+ }
+ case _ => BundleFsLoader.log.debug("only reacting on bundle start and stop")
+ }
+ }
+
+
+ def bindTcManager(tcManager: TcManager) {
+ this.tcManager = tcManager;
+ }
+
+ def unbindTcManager(tcManager: TcManager) {
+ this.tcManager = null;
+ }
+
+ def bindContentGraphProvider(p: ContentGraphProvider) {
+ cgProvider = p
+ }
+
+ def unbindContentGraphProvider(p: ContentGraphProvider) {
+ cgProvider = null
+ }
+
+ def bindStartLevel(startLevel: StartLevel) {
+ this.startLevel = startLevel;
+ }
+
+ def unbindStartLevel(startLevel: StartLevel) {
+ this.startLevel = null;
+ }
+
+ def bindPathNode(pathNode: PathNode) {
+ this.pathNodes ::= pathNode;
+ frequentUpdateDirectory = Some(new MultiPathNode(pathNodes: _*))
+ }
+
+ def unbindPathNode(pathNode: PathNode) {
+ this.pathNodes = this.pathNodes.filter(_ != pathNode);
+ frequentUpdateDirectory = pathNodes match {
+ case Nil => None
+ case _ => Some(new MultiPathNode(pathNodes: _*))
+ }
+ }
+
}
object BundleFsLoader {
- private val log = LoggerFactory.getLogger(classOf[BundleFsLoader])
+ private val log = LoggerFactory.getLogger(classOf[BundleFsLoader])
}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/platform.content.fsadaptor/src/main/scala/org/apache/clerezza/platform/content/fsadaptor/DirectoryOverlay.scala
----------------------------------------------------------------------
diff --git a/platform.content.fsadaptor/src/main/scala/org/apache/clerezza/platform/content/fsadaptor/DirectoryOverlay.scala b/platform.content.fsadaptor/src/main/scala/org/apache/clerezza/platform/content/fsadaptor/DirectoryOverlay.scala
index 8c78010..40bfb21 100644
--- a/platform.content.fsadaptor/src/main/scala/org/apache/clerezza/platform/content/fsadaptor/DirectoryOverlay.scala
+++ b/platform.content.fsadaptor/src/main/scala/org/apache/clerezza/platform/content/fsadaptor/DirectoryOverlay.scala
@@ -31,56 +31,56 @@ import org.wymiwyg.commons.util.dirbrowser.PathNode
import java.util.Iterator
class DirectoryOverlay(pathNode: PathNode, base: TripleCollection)
- extends AbstractTripleCollection {
+ extends AbstractTripleCollection {
-
+
- import collection.JavaConversions._
+ import collection.JavaConversions._
-
+
- override def performFilter(s: NonLiteral, p: UriRef,
- o: Resource): Iterator[Triple] = {
- val addedTriples = new SimpleMGraph()
+ override def performFilter(s: NonLiteral, p: UriRef,
+ o: Resource): Iterator[Triple] = {
+ val addedTriples = new SimpleMGraph()
- PathNode2MGraph.describeInGraph(pathNode, addedTriples)
-
- val subjects = (for (triple <- addedTriples; subject = triple.getSubject) yield {
- subject
- }).toSet
-
- class FilteringIterator(baseIter: Iterator[Triple]) extends Iterator[Triple] {
- var nextElem: Triple = null
- def prepareNext {
- nextElem = if (baseIter.hasNext) baseIter.next else null
- if ((nextElem != null) &&
- (subjects.contains(nextElem.getSubject))) {
- //println("skipping "+nextElem)
- prepareNext
- }
- }
- prepareNext
-
- override def next = {
- val result = nextElem
- prepareNext
- result
- }
- override def hasNext = nextElem != null
- override def remove = throw new UnsupportedOperationException
- }
-
- new IteratorMerger(new FilteringIterator(base.filter(s, p, o)), addedTriples.filter(s,p, o))
- }
+ PathNode2MGraph.describeInGraph(pathNode, addedTriples)
+
+ val subjects = (for (triple <- addedTriples; subject = triple.getSubject) yield {
+ subject
+ }).toSet
+
+ class FilteringIterator(baseIter: Iterator[Triple]) extends Iterator[Triple] {
+ var nextElem: Triple = null
+ def prepareNext {
+ nextElem = if (baseIter.hasNext) baseIter.next else null
+ if ((nextElem != null) &&
+ (subjects.contains(nextElem.getSubject))) {
+ //println("skipping "+nextElem)
+ prepareNext
+ }
+ }
+ prepareNext
+
+ override def next = {
+ val result = nextElem
+ prepareNext
+ result
+ }
+ override def hasNext = nextElem != null
+ override def remove = throw new UnsupportedOperationException
+ }
+
+ new IteratorMerger(new FilteringIterator(base.filter(s, p, o)), addedTriples.filter(s,p, o))
+ }
- /**
- * returns an upper bound of the size (removals in abse are not deducted)
- */
- override def size = {
- val addedTriples = new SimpleMGraph()
+ /**
+ * returns an upper bound of the size (removals in abse are not deducted)
+ */
+ override def size = {
+ val addedTriples = new SimpleMGraph()
- PathNode2MGraph.describeInGraph(pathNode, addedTriples)
+ PathNode2MGraph.describeInGraph(pathNode, addedTriples)
- base.size+addedTriples.size
- }
+ base.size+addedTriples.size
+ }
}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/platform.content.fsadaptor/src/main/scala/org/apache/clerezza/platform/content/fsadaptor/Logger.scala
----------------------------------------------------------------------
diff --git a/platform.content.fsadaptor/src/main/scala/org/apache/clerezza/platform/content/fsadaptor/Logger.scala b/platform.content.fsadaptor/src/main/scala/org/apache/clerezza/platform/content/fsadaptor/Logger.scala
index bac16ce..684992a 100644
--- a/platform.content.fsadaptor/src/main/scala/org/apache/clerezza/platform/content/fsadaptor/Logger.scala
+++ b/platform.content.fsadaptor/src/main/scala/org/apache/clerezza/platform/content/fsadaptor/Logger.scala
@@ -24,7 +24,7 @@ import org.slf4j.LoggerFactory
trait Logger {
- private val slf4jLogger = LoggerFactory.getLogger(this.getClass)
-// val logger: org.slf4j.Logger = new LoggerWrapper(slf4jLogger, this.getClass.getName)
+ private val slf4jLogger = LoggerFactory.getLogger(this.getClass)
+// val logger: org.slf4j.Logger = new LoggerWrapper(slf4jLogger, this.getClass.getName)
}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/platform.content.fsadaptor/src/main/scala/org/apache/clerezza/platform/content/fsadaptor/PathNode2MGraph.scala
----------------------------------------------------------------------
diff --git a/platform.content.fsadaptor/src/main/scala/org/apache/clerezza/platform/content/fsadaptor/PathNode2MGraph.scala b/platform.content.fsadaptor/src/main/scala/org/apache/clerezza/platform/content/fsadaptor/PathNode2MGraph.scala
index ad9b189..8a62774 100644
--- a/platform.content.fsadaptor/src/main/scala/org/apache/clerezza/platform/content/fsadaptor/PathNode2MGraph.scala
+++ b/platform.content.fsadaptor/src/main/scala/org/apache/clerezza/platform/content/fsadaptor/PathNode2MGraph.scala
@@ -41,106 +41,106 @@ import org.wymiwyg.commons.util.dirbrowser.PathNode
*/
object PathNode2MGraph {
- private val URI_PREFIX = Constants.URN_LOCAL_INSTANCE
+ private val URI_PREFIX = Constants.URN_LOCAL_INSTANCE
- private val literalFactory = LiteralFactory.getInstance
+ private val literalFactory = LiteralFactory.getInstance
- private def getMediaType(file: PathNode) = {
- val guessedMediaType: MediaType = MediaTypeGuesser.getInstance().guessTypeForName(file.getPath());
- if (guessedMediaType != null) {
- guessedMediaType.toString
- } else {
- "application/octet-stream"
- }
+ private def getMediaType(file: PathNode) = {
+ val guessedMediaType: MediaType = MediaTypeGuesser.getInstance().guessTypeForName(file.getPath());
+ if (guessedMediaType != null) {
+ guessedMediaType.toString
+ } else {
+ "application/octet-stream"
+ }
- }
+ }
- private def getData(file: PathNode) = {
- val baos = new ByteArrayOutputStream
- val in = file.getInputStream()
- val buffer = new Array[Byte](4096)
- var read = in.read(buffer)
- while (read != -1) {
- baos.write(buffer, 0, read)
- read = in.read(buffer)
- }
- in.close()
- baos.toByteArray
- }
+ private def getData(file: PathNode) = {
+ val baos = new ByteArrayOutputStream
+ val in = file.getInputStream()
+ val buffer = new Array[Byte](4096)
+ var read = in.read(buffer)
+ while (read != -1) {
+ baos.write(buffer, 0, read)
+ read = in.read(buffer)
+ }
+ in.close()
+ baos.toByteArray
+ }
- def describeInGraph(directory: PathNode, mGraph: MGraph) {
- val basePathLength = directory.getPath.length
- def createUriRef(file: PathNode, isDirectory: Boolean) = {
- def addSlashIfNeeded(s: String) = {
- if (s.endsWith("/")) {
- s
- } else {
- s+'/'
- }
- }
- val path = if (isDirectory) {
- addSlashIfNeeded(file.getPath.substring(basePathLength))
- } else {
- file.getPath.substring(basePathLength)
- }
- new UriRef(URI_PREFIX+path)
- }
- def processDirectory(directory: PathNode) {
- val directoryResource = createUriRef(directory, true)
- mGraph.add(new TripleImpl(directoryResource, RDF.`type`, HIERARCHY.Collection))
- for (subPath <- directory.list) {
- val file = directory.getSubPath(subPath)
- val isDirectory = file.isDirectory
- val resource = createUriRef(file, isDirectory)
- mGraph.add(new TripleImpl(resource, HIERARCHY.parent, directoryResource))
- if (isDirectory) {
- processDirectory(file)
- } else {
- mGraph.add(new TripleImpl(resource, RDF.`type`, DISCOBITS.InfoDiscoBit))
- val data = getData(file)
- mGraph.add(new TripleImpl(resource, DISCOBITS.infoBit, literalFactory.createTypedLiteral(data)))
- mGraph.add(new TripleImpl(resource, DISCOBITS.mediaType,
- literalFactory.createTypedLiteral(getMediaType(file))));
- }
- }
- }
- processDirectory(directory)
- }
+ def describeInGraph(directory: PathNode, mGraph: MGraph) {
+ val basePathLength = directory.getPath.length
+ def createUriRef(file: PathNode, isDirectory: Boolean) = {
+ def addSlashIfNeeded(s: String) = {
+ if (s.endsWith("/")) {
+ s
+ } else {
+ s+'/'
+ }
+ }
+ val path = if (isDirectory) {
+ addSlashIfNeeded(file.getPath.substring(basePathLength))
+ } else {
+ file.getPath.substring(basePathLength)
+ }
+ new UriRef(URI_PREFIX+path)
+ }
+ def processDirectory(directory: PathNode) {
+ val directoryResource = createUriRef(directory, true)
+ mGraph.add(new TripleImpl(directoryResource, RDF.`type`, HIERARCHY.Collection))
+ for (subPath <- directory.list) {
+ val file = directory.getSubPath(subPath)
+ val isDirectory = file.isDirectory
+ val resource = createUriRef(file, isDirectory)
+ mGraph.add(new TripleImpl(resource, HIERARCHY.parent, directoryResource))
+ if (isDirectory) {
+ processDirectory(file)
+ } else {
+ mGraph.add(new TripleImpl(resource, RDF.`type`, DISCOBITS.InfoDiscoBit))
+ val data = getData(file)
+ mGraph.add(new TripleImpl(resource, DISCOBITS.infoBit, literalFactory.createTypedLiteral(data)))
+ mGraph.add(new TripleImpl(resource, DISCOBITS.mediaType,
+ literalFactory.createTypedLiteral(getMediaType(file))));
+ }
+ }
+ }
+ processDirectory(directory)
+ }
- def removeNodesFromGraph(directory: PathNode, mGraph: MGraph) {
- val basePathLength = directory.getPath.length
- def createUriRef(file: PathNode, isDirectory: Boolean) = {
- def addSlashIfNeeded(s: String) = {
- if (s.endsWith("/")) {
- s
- } else {
- s+'/'
- }
- }
- val path = if (isDirectory) {
- addSlashIfNeeded(file.getPath.substring(basePathLength))
- } else {
- file.getPath.substring(basePathLength)
- }
- new UriRef(URI_PREFIX+path)
- }
- def processDirectory(directory: PathNode) {
- val directoryResource = createUriRef(directory, true)
- mGraph.remove(new TripleImpl(directoryResource, RDF.`type`, HIERARCHY.Collection))
- for (subPath <- directory.list) {
- val file = directory.getSubPath(subPath)
- val isDirectory = file.isDirectory
- val resource = createUriRef(file, isDirectory)
- val node = new GraphNode(resource, mGraph)
- if (isDirectory) {
- processDirectory(file)
- }
- node.deleteProperties(HIERARCHY.parent)
- node.deleteProperties(RDF.`type`)
- node.deleteProperties(DISCOBITS.infoBit)
- node.deleteProperties(DISCOBITS.mediaType)
- }
- }
- processDirectory(directory)
- }
+ def removeNodesFromGraph(directory: PathNode, mGraph: MGraph) {
+ val basePathLength = directory.getPath.length
+ def createUriRef(file: PathNode, isDirectory: Boolean) = {
+ def addSlashIfNeeded(s: String) = {
+ if (s.endsWith("/")) {
+ s
+ } else {
+ s+'/'
+ }
+ }
+ val path = if (isDirectory) {
+ addSlashIfNeeded(file.getPath.substring(basePathLength))
+ } else {
+ file.getPath.substring(basePathLength)
+ }
+ new UriRef(URI_PREFIX+path)
+ }
+ def processDirectory(directory: PathNode) {
+ val directoryResource = createUriRef(directory, true)
+ mGraph.remove(new TripleImpl(directoryResource, RDF.`type`, HIERARCHY.Collection))
+ for (subPath <- directory.list) {
+ val file = directory.getSubPath(subPath)
+ val isDirectory = file.isDirectory
+ val resource = createUriRef(file, isDirectory)
+ val node = new GraphNode(resource, mGraph)
+ if (isDirectory) {
+ processDirectory(file)
+ }
+ node.deleteProperties(HIERARCHY.parent)
+ node.deleteProperties(RDF.`type`)
+ node.deleteProperties(DISCOBITS.infoBit)
+ node.deleteProperties(DISCOBITS.mediaType)
+ }
+ }
+ processDirectory(directory)
+ }
}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/platform.editor/src/main/scala/org/apache/clerezza/platform/editor/renderlets/HtmlInfoDicobitRDFaNaked.scala
----------------------------------------------------------------------
diff --git a/platform.editor/src/main/scala/org/apache/clerezza/platform/editor/renderlets/HtmlInfoDicobitRDFaNaked.scala b/platform.editor/src/main/scala/org/apache/clerezza/platform/editor/renderlets/HtmlInfoDicobitRDFaNaked.scala
index 408ac6d..5b5c23b 100644
--- a/platform.editor/src/main/scala/org/apache/clerezza/platform/editor/renderlets/HtmlInfoDicobitRDFaNaked.scala
+++ b/platform.editor/src/main/scala/org/apache/clerezza/platform/editor/renderlets/HtmlInfoDicobitRDFaNaked.scala
@@ -15,22 +15,22 @@ import org.apache.felix.scr.annotations.Service;import scala.xml.Unparsed
@Service(Array(classOf[TypeRenderlet]))
class HtmlInfoDicobitRDFaNaked extends SRenderlet {
- val getRdfType = DISCOBITS.XHTMLInfoDiscoBit
+ val getRdfType = DISCOBITS.XHTMLInfoDiscoBit
override val getMediaType = MediaType.TEXT_HTML_TYPE
- override def getModePattern = "rdfa-naked"
+ override def getModePattern = "rdfa-naked"
- override def renderedPage(arguments: XmlResult.Arguments) = {
- new XmlResult(arguments) {
- override def content = {
+ override def renderedPage(arguments: XmlResult.Arguments) = {
+ new XmlResult(arguments) {
+ override def content = {
<div typeof="disco:XHTMLInfoDiscoBit" about={res*}>
<span property="disco:infoBit">
{Unparsed(res/DISCOBITS.infoBit*)}
</span>
</div>
- }
- }
- }
+ }
+ }
+ }
}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/platform.editor/src/main/scala/org/apache/clerezza/platform/editor/renderlets/OrderedContentRDFaNaked.scala
----------------------------------------------------------------------
diff --git a/platform.editor/src/main/scala/org/apache/clerezza/platform/editor/renderlets/OrderedContentRDFaNaked.scala b/platform.editor/src/main/scala/org/apache/clerezza/platform/editor/renderlets/OrderedContentRDFaNaked.scala
index 1427f34..e8e00f5 100644
--- a/platform.editor/src/main/scala/org/apache/clerezza/platform/editor/renderlets/OrderedContentRDFaNaked.scala
+++ b/platform.editor/src/main/scala/org/apache/clerezza/platform/editor/renderlets/OrderedContentRDFaNaked.scala
@@ -14,15 +14,15 @@ import org.apache.felix.scr.annotations.Service;
@Service(Array(classOf[TypeRenderlet]))
class OrderedContentRDFaNaked extends SRenderlet {
- val getRdfType = DISCOBITS.OrderedContent
+ val getRdfType = DISCOBITS.OrderedContent
override val getMediaType = MediaType.TEXT_HTML_TYPE
- override def getModePattern = "rdfa-naked"
+ override def getModePattern = "rdfa-naked"
- override def renderedPage(arguments: XmlResult.Arguments) = {
- new XmlResult(arguments) {
- override def content = {
+ override def renderedPage(arguments: XmlResult.Arguments) = {
+ new XmlResult(arguments) {
+ override def content = {
<div about={res*} typeof="disco:OrderedContent">
{for (part <- (res/DISCOBITS.contains).sortBy(part => (part/DISCOBITS.pos*).toInt))
yield <div property="disco:contains" typeof="disco:Entry">
@@ -31,8 +31,8 @@ class OrderedContentRDFaNaked extends SRenderlet {
</div>
}
</div>
- }
- }
- }
+ }
+ }
+ }
}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/platform.editor/src/main/scala/org/apache/clerezza/platform/editor/renderlets/TitledContentRDFaNaked.scala
----------------------------------------------------------------------
diff --git a/platform.editor/src/main/scala/org/apache/clerezza/platform/editor/renderlets/TitledContentRDFaNaked.scala b/platform.editor/src/main/scala/org/apache/clerezza/platform/editor/renderlets/TitledContentRDFaNaked.scala
index ad0deda..5e1e1cc 100644
--- a/platform.editor/src/main/scala/org/apache/clerezza/platform/editor/renderlets/TitledContentRDFaNaked.scala
+++ b/platform.editor/src/main/scala/org/apache/clerezza/platform/editor/renderlets/TitledContentRDFaNaked.scala
@@ -14,15 +14,15 @@ import org.apache.felix.scr.annotations.Service;
@Service(Array(classOf[TypeRenderlet]))
class TitledContentRDFaNaked extends SRenderlet {
- val getRdfType = DISCOBITS.TitledContent
+ val getRdfType = DISCOBITS.TitledContent
override val getMediaType = MediaType.TEXT_HTML_TYPE
- override def getModePattern = "rdfa-naked"
+ override def getModePattern = "rdfa-naked"
- override def renderedPage(arguments: XmlResult.Arguments) = {
- new XmlResult(arguments) {
- override def content = {
+ override def renderedPage(arguments: XmlResult.Arguments) = {
+ new XmlResult(arguments) {
+ override def content = {
<div typeof="disco:TitledContent" about={res*}>
{for (part <- res/DISCOBITS.contains; if ((part/DISCOBITS.pos*) == "0"))
yield <span property="disco:holds" typeof="disco:Entry">
@@ -35,8 +35,8 @@ class TitledContentRDFaNaked extends SRenderlet {
<div property="disco:holds" resource={part/DISCOBITS.holds*}>{render(part/DISCOBITS.holds, "rdfa-naked")}</div>
</div>}
</div>
- }
- }
- }
+ }
+ }
+ }
}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/platform.graphnodeprovider/src/main/scala/org/apache/clerezza/platform/graphnodeprovider/GraphNodeProvider.scala
----------------------------------------------------------------------
diff --git a/platform.graphnodeprovider/src/main/scala/org/apache/clerezza/platform/graphnodeprovider/GraphNodeProvider.scala b/platform.graphnodeprovider/src/main/scala/org/apache/clerezza/platform/graphnodeprovider/GraphNodeProvider.scala
index e8d3edd..5c9f12b 100644
--- a/platform.graphnodeprovider/src/main/scala/org/apache/clerezza/platform/graphnodeprovider/GraphNodeProvider.scala
+++ b/platform.graphnodeprovider/src/main/scala/org/apache/clerezza/platform/graphnodeprovider/GraphNodeProvider.scala
@@ -40,27 +40,27 @@ import java.security.{PrivilegedAction, AccessController}
*/
class GraphNodeProvider extends Logging {
- /**
- * Get a GraphNode for the specified resource, see class comments for details.
- */
- def get(uriRef: UriRef): GraphNode = {
- val uriString = uriRef.getUnicodeString
- val isLocal: Boolean = {
- import scala.collection.JavaConversions._
- //we assume all non http* uris to be local
- !uriString.toLowerCase.startsWith("http") || platformConfig.getBaseUris.exists(baseUri => uriString.startsWith(baseUri.getUnicodeString))
- }
- get(uriRef, isLocal)
- }
-
- /**
- * Get a GraphNode for the specified resource, The resource is assumed to be local, i.e. the method behaves like
- * get(UriRef) for a Uri with an authority section contained in the Set retuned by
- * <code>org.apache.clerezza.platform.config.PlatformConfig#getBaseUris()</code>
- */
- def getLocal(uriRef: UriRef): GraphNode = {
- get(uriRef, true)
- }
+ /**
+ * Get a GraphNode for the specified resource, see class comments for details.
+ */
+ def get(uriRef: UriRef): GraphNode = {
+ val uriString = uriRef.getUnicodeString
+ val isLocal: Boolean = {
+ import scala.collection.JavaConversions._
+ //we assume all non http* uris to be local
+ !uriString.toLowerCase.startsWith("http") || platformConfig.getBaseUris.exists(baseUri => uriString.startsWith(baseUri.getUnicodeString))
+ }
+ get(uriRef, isLocal)
+ }
+
+ /**
+ * Get a GraphNode for the specified resource, The resource is assumed to be local, i.e. the method behaves like
+ * get(UriRef) for a Uri with an authority section contained in the Set retuned by
+ * <code>org.apache.clerezza.platform.config.PlatformConfig#getBaseUris()</code>
+ */
+ def getLocal(uriRef: UriRef): GraphNode = {
+ get(uriRef, true)
+ }
/**
@@ -70,8 +70,8 @@ class GraphNodeProvider extends Logging {
val cgGraph = cgProvider.getContentGraph
lazy val localInstanceUri = {
val uri = new java.net.URI(uriRef.getUnicodeString)
- new UriRef(Constants.URN_LOCAL_INSTANCE + uri.getPath)
- }
+ new UriRef(Constants.URN_LOCAL_INSTANCE + uri.getPath)
+ }
//TODO handle /user/
existsInGraph(uriRef,cgGraph) || existsInGraph(localInstanceUri, cgGraph)
}
@@ -88,157 +88,157 @@ class GraphNodeProvider extends Logging {
}
- private def get(uriRef: UriRef, isLocal: Boolean): GraphNode = {
- val uriString = uriRef.getUnicodeString
-
-
- val uriPath = {
- val uri = new java.net.URI(uriString)
- uri.getPath
- }
-
- lazy val uriPrefix = {
- val uri = new java.net.URI(uriString)
- uri.getScheme+"://"+uri.getAuthority
- }
-
- val anyHostUri = new UriRef(Constants.URN_LOCAL_INSTANCE + uriPath)
-
- var mGraphs: List[TripleCollection] = Nil
-
- def addToUnion(mGraph: LockableMGraph) {
- //adding uncondinionately if (existsInGraph(uriRef, mGraph)) {
- mGraphs ::= mGraph
- //}
- if (isLocal) {
- if (existsInGraph(anyHostUri, mGraph)) {
- mGraphs ::= new UriMutatingTripleCollection(mGraph, Constants.URN_LOCAL_INSTANCE, uriPrefix)
- }
- }
- }
-
- val cgGraph = cgProvider.getContentGraph
-
- addToUnion(cgGraph)
-
- if (isLocal && uriPath.startsWith("/user/")) {
- val nextSlash = uriPath.indexOf('/',6)
- if (nextSlash != -1) {
- val userName = uriPath.substring(6, nextSlash)
- val webIdOption = AccessController.doPrivileged(new PrivilegedAction[Option[UriRef]]() {
- def run(): Option[UriRef] = {
- val userNode: GraphNode = userManager.getUserInSystemGraph(userName)
- if (userNode != null) {
- userNode.getNode match {
- case u: UriRef => Some(u)
- case _ => None
- }
- } else {
- None
- }
- }
- }
- )
- webIdOption match {
- case Some(u) => {
- val webIdInfo = webIdGraphsService.getWebIdInfo(u)
- addToUnion(webIdInfo.localPublicUserData)
- }
- case None => ;
- }
- }
- }
-
- if (!isLocal) {
- /**
- * As the resource might identify something other than a document we use this to find the redirect location
- */
- lazy val redirectLocationString = {
- val acceptHeader = "application/rdf+xml,*/*;q.1"
- val url = new URL(uriString)
- val connection = url.openConnection()
- connection match {
- case hc : HttpURLConnection => {
- hc.setRequestMethod("HEAD");
- hc.setInstanceFollowRedirects(false)
- hc.addRequestProperty("Accept", acceptHeader)
- hc.getResponseCode match {
- case HttpURLConnection.HTTP_SEE_OTHER => {
- val location = hc.getHeaderField("Location")
- if (location == null) {
- throw new RuntimeException("No Location Headers in 303 response")
- }
- location
- }
- case _ => uriString
- }
- }
- case _ => uriString
- }
- }
-
- //TODO add method to WebProxy to get the graph location location
- val graphUriString = {
- val hashPos = uriString.indexOf('#')
- if (hashPos != -1) {
- uriString.substring(0, hashPos)
- } else {
- redirectLocationString
- }
- }
-
- addToUnion(tcManager.getMGraph(new UriRef(graphUriString)))
- }
-
- val unionMGraph = new UnionMGraph(mGraphs:_*);
- new GraphNode(uriRef, unionMGraph)
- }
-
- private var tcManager: TcManager = null;
-
- protected def bindTcManager(tcManager: TcManager) = {
- this.tcManager = tcManager
- }
-
- protected def unbindTcManager(tcManager: TcManager) = {
- this.tcManager = null
- }
-
- private var platformConfig: PlatformConfig = null;
-
- protected def bindPlatformConfig(c: PlatformConfig) = {
- this.platformConfig = c
- }
-
- protected def unbindPlatformConfig(c: PlatformConfig) = {
- this.platformConfig = null
- }
-
- private var cgProvider: ContentGraphProvider = null
- protected def bindCgProvider(p: ContentGraphProvider) {
- this.cgProvider = p
- }
- protected def unbindCgProvider(p: ContentGraphProvider) {
- this.cgProvider = null
- }
-
- private var webIdGraphsService: WebIdGraphsService = null
- protected def bindWebIdGraphsService(webIdGraphsService: WebIdGraphsService): Unit = {
- this.webIdGraphsService = webIdGraphsService
- }
-
- protected def unbindWebIdGraphsService(webIdGraphsService: WebIdGraphsService): Unit = {
- this.webIdGraphsService = null
- }
-
- private var userManager: UserManager = null
-
- protected def bindUserManager(userManager: UserManager): Unit = {
- this.userManager = userManager
- }
-
- protected def unbindUserManager(userManager: UserManager): Unit = {
- this.userManager = null
- }
+ private def get(uriRef: UriRef, isLocal: Boolean): GraphNode = {
+ val uriString = uriRef.getUnicodeString
+
+
+ val uriPath = {
+ val uri = new java.net.URI(uriString)
+ uri.getPath
+ }
+
+ lazy val uriPrefix = {
+ val uri = new java.net.URI(uriString)
+ uri.getScheme+"://"+uri.getAuthority
+ }
+
+ val anyHostUri = new UriRef(Constants.URN_LOCAL_INSTANCE + uriPath)
+
+ var mGraphs: List[TripleCollection] = Nil
+
+ def addToUnion(mGraph: LockableMGraph) {
+ //adding uncondinionately if (existsInGraph(uriRef, mGraph)) {
+ mGraphs ::= mGraph
+ //}
+ if (isLocal) {
+ if (existsInGraph(anyHostUri, mGraph)) {
+ mGraphs ::= new UriMutatingTripleCollection(mGraph, Constants.URN_LOCAL_INSTANCE, uriPrefix)
+ }
+ }
+ }
+
+ val cgGraph = cgProvider.getContentGraph
+
+ addToUnion(cgGraph)
+
+ if (isLocal && uriPath.startsWith("/user/")) {
+ val nextSlash = uriPath.indexOf('/',6)
+ if (nextSlash != -1) {
+ val userName = uriPath.substring(6, nextSlash)
+ val webIdOption = AccessController.doPrivileged(new PrivilegedAction[Option[UriRef]]() {
+ def run(): Option[UriRef] = {
+ val userNode: GraphNode = userManager.getUserInSystemGraph(userName)
+ if (userNode != null) {
+ userNode.getNode match {
+ case u: UriRef => Some(u)
+ case _ => None
+ }
+ } else {
+ None
+ }
+ }
+ }
+ )
+ webIdOption match {
+ case Some(u) => {
+ val webIdInfo = webIdGraphsService.getWebIdInfo(u)
+ addToUnion(webIdInfo.localPublicUserData)
+ }
+ case None => ;
+ }
+ }
+ }
+
+ if (!isLocal) {
+ /**
+ * As the resource might identify something other than a document we use this to find the redirect location
+ */
+ lazy val redirectLocationString = {
+ val acceptHeader = "application/rdf+xml,*/*;q.1"
+ val url = new URL(uriString)
+ val connection = url.openConnection()
+ connection match {
+ case hc : HttpURLConnection => {
+ hc.setRequestMethod("HEAD");
+ hc.setInstanceFollowRedirects(false)
+ hc.addRequestProperty("Accept", acceptHeader)
+ hc.getResponseCode match {
+ case HttpURLConnection.HTTP_SEE_OTHER => {
+ val location = hc.getHeaderField("Location")
+ if (location == null) {
+ throw new RuntimeException("No Location Headers in 303 response")
+ }
+ location
+ }
+ case _ => uriString
+ }
+ }
+ case _ => uriString
+ }
+ }
+
+ //TODO add method to WebProxy to get the graph location location
+ val graphUriString = {
+ val hashPos = uriString.indexOf('#')
+ if (hashPos != -1) {
+ uriString.substring(0, hashPos)
+ } else {
+ redirectLocationString
+ }
+ }
+
+ addToUnion(tcManager.getMGraph(new UriRef(graphUriString)))
+ }
+
+ val unionMGraph = new UnionMGraph(mGraphs:_*);
+ new GraphNode(uriRef, unionMGraph)
+ }
+
+ private var tcManager: TcManager = null;
+
+ protected def bindTcManager(tcManager: TcManager) = {
+ this.tcManager = tcManager
+ }
+
+ protected def unbindTcManager(tcManager: TcManager) = {
+ this.tcManager = null
+ }
+
+ private var platformConfig: PlatformConfig = null;
+
+ protected def bindPlatformConfig(c: PlatformConfig) = {
+ this.platformConfig = c
+ }
+
+ protected def unbindPlatformConfig(c: PlatformConfig) = {
+ this.platformConfig = null
+ }
+
+ private var cgProvider: ContentGraphProvider = null
+ protected def bindCgProvider(p: ContentGraphProvider) {
+ this.cgProvider = p
+ }
+ protected def unbindCgProvider(p: ContentGraphProvider) {
+ this.cgProvider = null
+ }
+
+ private var webIdGraphsService: WebIdGraphsService = null
+ protected def bindWebIdGraphsService(webIdGraphsService: WebIdGraphsService): Unit = {
+ this.webIdGraphsService = webIdGraphsService
+ }
+
+ protected def unbindWebIdGraphsService(webIdGraphsService: WebIdGraphsService): Unit = {
+ this.webIdGraphsService = null
+ }
+
+ private var userManager: UserManager = null
+
+ protected def bindUserManager(userManager: UserManager): Unit = {
+ this.userManager = userManager
+ }
+
+ protected def unbindUserManager(userManager: UserManager): Unit = {
+ this.userManager = null
+ }
}
[7/9] CLEREZZA-435: repaced tabs with spaces in scala files
Posted by re...@apache.org.
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/platform.accountcontrolpanel/platform.accountcontrolpanel.core/src/main/scala/org/apache/clerezza/platform/accountcontrolpanel/AcpPermissionDescriptionsProvider.scala
----------------------------------------------------------------------
diff --git a/platform.accountcontrolpanel/platform.accountcontrolpanel.core/src/main/scala/org/apache/clerezza/platform/accountcontrolpanel/AcpPermissionDescriptionsProvider.scala b/platform.accountcontrolpanel/platform.accountcontrolpanel.core/src/main/scala/org/apache/clerezza/platform/accountcontrolpanel/AcpPermissionDescriptionsProvider.scala
index a357de8..5d41410 100644
--- a/platform.accountcontrolpanel/platform.accountcontrolpanel.core/src/main/scala/org/apache/clerezza/platform/accountcontrolpanel/AcpPermissionDescriptionsProvider.scala
+++ b/platform.accountcontrolpanel/platform.accountcontrolpanel.core/src/main/scala/org/apache/clerezza/platform/accountcontrolpanel/AcpPermissionDescriptionsProvider.scala
@@ -30,46 +30,46 @@ import org.apache.felix.scr.annotations.Service
* <code>PermissionDescripton</code>s of Account Control Panel permissions.
* The following permissions are described:
* <ul>
- * <li>org.apache.clerezza.platform.accountcontrolpanel.AccountControlPanelAppPermission</li>
- * <li>org.apache.clerezza.platform.accountcontrolpanel.ChangePasswordPermission</li>
- * <li>org.apache.clerezza.platform.accountcontrolpanel.UserBundlePermission</li>
+ * <li>org.apache.clerezza.platform.accountcontrolpanel.AccountControlPanelAppPermission</li>
+ * <li>org.apache.clerezza.platform.accountcontrolpanel.ChangePasswordPermission</li>
+ * <li>org.apache.clerezza.platform.accountcontrolpanel.UserBundlePermission</li>
* </ul>
*
* @author mir
*/
object AcpPermissionDescriptionsProvider {
- private val ACP_PERMISSION_DESCRIPTIONS: Set[PermissionDescripton] = new HashSet[PermissionDescripton]
- ACP_PERMISSION_DESCRIPTIONS.add(
- new PermissionDescripton("Change Own Password Permission",
- "Grants permission to the user to change its own password",
- null, classOf[ChangePasswordPermission],
- "(org.apache.clerezza.platform.accountcontrolpanel.ChangePasswordPermission \"{username}\" \"\")"
- )
- )
+ private val ACP_PERMISSION_DESCRIPTIONS: Set[PermissionDescripton] = new HashSet[PermissionDescripton]
+ ACP_PERMISSION_DESCRIPTIONS.add(
+ new PermissionDescripton("Change Own Password Permission",
+ "Grants permission to the user to change its own password",
+ null, classOf[ChangePasswordPermission],
+ "(org.apache.clerezza.platform.accountcontrolpanel.ChangePasswordPermission \"{username}\" \"\")"
+ )
+ )
- ACP_PERMISSION_DESCRIPTIONS.add(
- new PermissionDescripton("Access Own Account Control Panel Permission",
- "Grants permission to the user to access its own Account Control Panel",
- null, classOf[AccountControlPanelAppPermission],
- "(org.apache.clerezza.platform.accountcontrolpanel.AccountControlPanelAppPermission \"{username}\" \"\")"
- )
- )
+ ACP_PERMISSION_DESCRIPTIONS.add(
+ new PermissionDescripton("Access Own Account Control Panel Permission",
+ "Grants permission to the user to access its own Account Control Panel",
+ null, classOf[AccountControlPanelAppPermission],
+ "(org.apache.clerezza.platform.accountcontrolpanel.AccountControlPanelAppPermission \"{username}\" \"\")"
+ )
+ )
- ACP_PERMISSION_DESCRIPTIONS.add(
- new PermissionDescripton("Bundle Upload Permission",
- "Grants permission to the user to upload a bundle",
- null, classOf[AccountControlPanelAppPermission],
- "(org.apache.clerezza.platform.accountcontrolpanel.UserBundlePermission \"{username}\" \"\")"
- )
- )
+ ACP_PERMISSION_DESCRIPTIONS.add(
+ new PermissionDescripton("Bundle Upload Permission",
+ "Grants permission to the user to upload a bundle",
+ null, classOf[AccountControlPanelAppPermission],
+ "(org.apache.clerezza.platform.accountcontrolpanel.UserBundlePermission \"{username}\" \"\")"
+ )
+ )
}
class AcpPermissionDescriptionsProvider extends PermissionDescriptionsProvider {
- import AcpPermissionDescriptionsProvider._
+ import AcpPermissionDescriptionsProvider._
- def getPermissionDescriptors: Set[PermissionDescripton] = {
- return ACP_PERMISSION_DESCRIPTIONS
- }
+ def getPermissionDescriptors: Set[PermissionDescripton] = {
+ return ACP_PERMISSION_DESCRIPTIONS
+ }
}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/platform.accountcontrolpanel/platform.accountcontrolpanel.core/src/main/scala/org/apache/clerezza/platform/accountcontrolpanel/MenuItemProvider.scala
----------------------------------------------------------------------
diff --git a/platform.accountcontrolpanel/platform.accountcontrolpanel.core/src/main/scala/org/apache/clerezza/platform/accountcontrolpanel/MenuItemProvider.scala b/platform.accountcontrolpanel/platform.accountcontrolpanel.core/src/main/scala/org/apache/clerezza/platform/accountcontrolpanel/MenuItemProvider.scala
index 3d9e3c1..7ab15dd 100644
--- a/platform.accountcontrolpanel/platform.accountcontrolpanel.core/src/main/scala/org/apache/clerezza/platform/accountcontrolpanel/MenuItemProvider.scala
+++ b/platform.accountcontrolpanel/platform.accountcontrolpanel.core/src/main/scala/org/apache/clerezza/platform/accountcontrolpanel/MenuItemProvider.scala
@@ -44,28 +44,28 @@ import org.apache.stanbol.commons.security.UserUtil
* @author reto
*/
class MenuItemProvider extends GlobalMenuItemsProvider {
- def getMenuItems: Set[GlobalMenuItem] = {
- var items: Set[GlobalMenuItem] = new HashSet[GlobalMenuItem]
- var userName: String = UserUtil.getCurrentUserName
- if (userName != null) {
- try {
- AccessController.checkPermission(new AccountControlPanelAppPermission(userName, ""))
- }
- catch {
- case e: AccessControlException => {
- return items
- }
- }
- try {
- var path: String = "/user/" + URLEncoder.encode(userName, "utf-8") + "/control-panel"
- items.add(new GlobalMenuItem(path, "ACP", "Account Control Panel", 5, "Administration"))
- }
- catch {
- case e: UnsupportedEncodingException => {
- throw new RuntimeException(e)
- }
- }
- }
- return items
- }
+ def getMenuItems: Set[GlobalMenuItem] = {
+ var items: Set[GlobalMenuItem] = new HashSet[GlobalMenuItem]
+ var userName: String = UserUtil.getCurrentUserName
+ if (userName != null) {
+ try {
+ AccessController.checkPermission(new AccountControlPanelAppPermission(userName, ""))
+ }
+ catch {
+ case e: AccessControlException => {
+ return items
+ }
+ }
+ try {
+ var path: String = "/user/" + URLEncoder.encode(userName, "utf-8") + "/control-panel"
+ items.add(new GlobalMenuItem(path, "ACP", "Account Control Panel", 5, "Administration"))
+ }
+ catch {
+ case e: UnsupportedEncodingException => {
+ throw new RuntimeException(e)
+ }
+ }
+ }
+ return items
+ }
}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/platform.accountcontrolpanel/platform.accountcontrolpanel.core/src/main/scala/org/apache/clerezza/platform/accountcontrolpanel/ProfilePanel.scala
----------------------------------------------------------------------
diff --git a/platform.accountcontrolpanel/platform.accountcontrolpanel.core/src/main/scala/org/apache/clerezza/platform/accountcontrolpanel/ProfilePanel.scala b/platform.accountcontrolpanel/platform.accountcontrolpanel.core/src/main/scala/org/apache/clerezza/platform/accountcontrolpanel/ProfilePanel.scala
index 5a4ef94..0104077 100644
--- a/platform.accountcontrolpanel/platform.accountcontrolpanel.core/src/main/scala/org/apache/clerezza/platform/accountcontrolpanel/ProfilePanel.scala
+++ b/platform.accountcontrolpanel/platform.accountcontrolpanel.core/src/main/scala/org/apache/clerezza/platform/accountcontrolpanel/ProfilePanel.scala
@@ -65,402 +65,402 @@ import org.apache.clerezza.rdf.scala.utils._
@Path("/user/{id}/profile")
class ProfilePanel extends Logging {
- import collection.JavaConversions._
- import Preamble._
-
- /**
- * Returns a GraphNode describing a ProfilePage for the user identified by
- * the specified UserName. A ProfilePage resourcve is retuned for any user
- * disregarding if they have a WebId and if this is local. The renderlet
- * may provide instrcutions on how a WebId is created for users that do
- * not have a WebId and redirect them to their WebId provider if they have
- * a remote WebId.
- */
- @GET
- def getPersonalProfilePage(@Context uriInfo: UriInfo,
- @PathParam(value = "id") userName: String): GraphNode = {
- TrailingSlash.enforceNotPresent(uriInfo)
- //not checking as public profile must be public, more selective access control TBD
- //AccessController.checkPermission(new AccountControlPanelAppPermission(userName, ""))
- val resultNode= getPersonalProfile(userName, uriInfo)
- return resultNode
- }
-
- private def getPersonalProfile(userName: String, info: UriInfo): GraphNode = {
- lazy val suggestedPPDUri = getSuggestedPPDUri(userName)
-
- val profile = AccessController.doPrivileged(new PrivilegedAction[GraphNode] {
- def run: GraphNode = {
- val userInSysGraph = userManager.getUserInSystemGraph(userName)
- val userResource = userInSysGraph.getNode
- val profile: GraphNode = userResource match {
- case blank: BNode => {
- //user does not have a webId yet
- val g = new EzMGraph()
- import g._
- val profile = bnode
- (profile -- CONTROLPANEL.isLocalProfile --> bool2lit(true)
- -- CONTROLPANEL.suggestedPPDUri --> suggestedPPDUri
- -- FOAF.primaryTopic --> (bnode -- PLATFORM.userName --> userName))
- profile
- }
- case webid: UriRef => {
- var webIDInfo = webIdGraphsService.getWebIdInfo(webid)
- var res = new GraphNode(suggestedPPDUri, new UnionMGraph(new SimpleMGraph, webIDInfo.localPublicUserData))
- (res -- CONTROLPANEL.isLocalProfile --> bool2lit(webIDInfo.isLocal)
- -- FOAF.primaryTopic --> webid)
- res
- }
- }
- /*val friendInfo:Iterator[TripleCollection] = for (kn: Triple <- profile.getGraph.filter(userResource.asInstanceOf[NonLiteral], FOAF.knows, null)
- if kn.getObject.isInstanceOf[UriRef];
- friend = kn.getObject.asInstanceOf[UriRef]
- if (friend != suggestedPPDUri)
- ) yield {
- try {
- val friendGraph = tcManager.getGraph(FoafBrowser.removeHash(friend))
- new RichGraphNode(friend, friendGraph).getNodeContext
- } catch {
- case e => {
- logger.warn("cought exception trying to fetch graph - these graphs should already be in store " + friend, e)
- new EzMGraph() {
- friend -- SKOS.note --> ("problem with fetching this node: " + e)
- }
- }
- }
- }
- //vera bad: mixing data from different sources
- for (g <- friendInfo) profile.getGraph.addAll(g) */
- profile
- }
- })
-
-
- (profile a PLATFORM.HeadedPage
- a CONTROLPANEL.ProfilePage)
- }
-
- /**
- * @param userName
- * @return the suggested Personal Profile Document URI
- */
- def getSuggestedPPDUri(userName: String): UriRef = {
- return new UriRef(platformConfig.getDefaultBaseUri.getUnicodeString + "user/" + userName + "/profile")
- }
-
- @POST
- @Path("set-existing-webid")
- def setExistingWebId(@Context uriInfo: UriInfo,
- @FormParam("webid") webId: UriRef,
- @PathParam(value = "id") userName: String): Response = {
- AccessController.checkPermission(new AccountControlPanelAppPermission(userName, ""))
- return AccessController.doPrivileged(new PrivilegedAction[Response] {
- def run: Response = {
- var userInSystemGraph: GraphNode = userManager.getUserInSystemGraph(userName)
- userInSystemGraph.replaceWith(webId)
- return RedirectUtil.createSeeOtherResponse("../profile", uriInfo)
- }
- })
- }
-
- @POST
- @Path("create-new-web-id")
- def createNewWebId(@Context uriInfo: UriInfo,
- @PathParam(value = "id") userName: String): Response = {
- val ppd: UriRef = getSuggestedPPDUri(userName)
- val webId: UriRef = new UriRef(ppd.getUnicodeString + "#me")
- AccessController.checkPermission(new AccountControlPanelAppPermission(userName, ""))
- return AccessController.doPrivileged(new PrivilegedAction[Response] {
- def run: Response = {
- userManager.assignPermissionsToUser(userName, java.util.Collections.singletonList(new TcPermission(
- webId.getUnicodeString, TcPermission.READWRITE).toString))
- tcManager.getTcAccessController.setRequiredReadPermissionStrings(
- ppd, Collections.singleton(new TcPermission(
- Constants.CONTENT_GRAPH_URI_STRING, TcPermission.READ).toString))
- tcManager.createMGraph(ppd)
- val webIDInfo = webIdGraphsService.getWebIdInfo(webId)
- webIDInfo.localPublicUserData.addAll(
- Arrays.asList(
- new TripleImpl(ppd, RDF.`type`, FOAF.PersonalProfileDocument),
- new TripleImpl(ppd, FOAF.primaryTopic, webId))
- )
- var userInSystemGraph: GraphNode = userManager.getUserInSystemGraph(userName)
- userInSystemGraph.replaceWith(webId)
- return RedirectUtil.createSeeOtherResponse("../profile", uriInfo)
- }
- })
- }
-
- /**
- * Presents a confirmation form for adding a contact
- */
- @GET
- @Path("addContact")
- def addContactConfirm(@PathParam(value = "id") userName: String,
- @QueryParam("contactWebId") contactWebId: UriRef): GraphNode = {
- AccessController.checkPermission(new AccountControlPanelAppPermission(userName, ""))
- val contactNode = AccessController.doPrivileged(new PrivilegedAction[GraphNode] {
- def run = {
- graphNodeProvider.get(contactWebId);
- }
- })
- val resultGraph = new EzMGraph(new UnionMGraph(new SimpleMGraph, contactNode.getGraph))
- import resultGraph._
- val result: GraphNode = bnode
- result a CONTROLPANEL.ContactConfirmPage
- result -- FOAF.primaryTopic --> contactNode
- }
-
- @POST
- @Path("addContact")
- def addContact(@PathParam(value = "id") userName: String, @Context uriInfo: UriInfo,
- @FormParam("webId") newContacts: java.util.List[UriRef]): Response = {
- import collection.JavaConversions._
- if (newContacts.size > 0) {
- var me: GraphNode = AccessController.doPrivileged(new PrivilegedAction[GraphNode] {
- def run: GraphNode = {
- return userManager.getUserGraphNode(userName)
- }
- })
- for (contactWebID <- newContacts) {
- val webIdGraphs = webIdGraphsService.getWebIdInfo(me.getNode.asInstanceOf[UriRef])
- var meGrph: GraphNode = new GraphNode(me.getNode, webIdGraphs.localPublicUserData)
- meGrph.addProperty(FOAF.knows, contactWebID)
- } //todo: one should catch errors here (bad uris sent for ex
- }
- return RedirectUtil.createSeeOtherResponse("../profile", uriInfo)
- }
-
- /**
- * Removes a contact
- */
- @POST
- @Path("deleteContact")
- def deleteContact(@PathParam(value = "id") userName: String, @Context uriInfo: UriInfo,
- @FormParam("contactWebId") contactWebId: UriRef): Response = {
- import collection.JavaConversions._
- var me: GraphNode = AccessController.doPrivileged(new PrivilegedAction[GraphNode] {
- def run: GraphNode = {
- return userManager.getUserGraphNode(userName)
- }
- })
- val webIdGraphs = webIdGraphsService.getWebIdInfo(me.getNode.asInstanceOf[UriRef])
- var meGrph: GraphNode = new GraphNode(me.getNode, webIdGraphs.localPublicUserData)
- meGrph.deleteProperty(FOAF.knows, contactWebId)
- return RedirectUtil.createSeeOtherResponse("../profile", uriInfo)
- }
-
- /**
- * @parm webId: A list of WebIDs to be added as Subject Alternative Names
- * @param cn Common Name, the name that usually appears in the certificate selection box
- * @param spkac key request in format generated by Netscape, Safari, Opera
- * @param crmf hey request in format generated by M$ Explorer
- * @param csr key request as generated by Javascript of Netscape
- * @param hours the certificate should last (hours and days add up)
- * @param days the certificate should last
- * @param comment a comment to be attached to the public key in the database
- */
- @POST
- @Path("keygen")
- def createCert(@FormParam("webId") webIds: java.util.List[URI],
- @FormParam("cn") commonName: String,
- @FormParam("spkac") spkac: String,
- @FormParam("crmf") crmf: String,
- @FormParam("csr") csr: String,
- @FormParam("hours") hours: String,
- @FormParam("days") days: String,
- @FormParam("comment") comment: String): Response = {
- import scala.collection.JavaConversions._
- var cert: Certificate = null
- if (spkac != null && spkac.length > 0) {
- cert = keygenSrvc.createFromSpkac(spkac)
- if (cert == null) {
- logger.warn("unable to create certificate from spkac request")
- }
- }
- if (cert == null && crmf != null && crmf.length > 0) {
- cert = keygenSrvc.createFromCRMF(crmf)
- if (cert == null) {
- logger.warn("unable to create certificate from crmf requrest :" + crmf)
- }
- }
- if (cert == null && csr != null && csr.length > 0) {
- cert = keygenSrvc.createFromPEM(csr)
- if (cert == null) {
- logger.warn("unable to create certificate from csr request :" + csr)
- }
- }
- if (cert == null) {
- throw new RuntimeException("The server was unable to create a certificate")
- }
- cert.setSubjectCommonName(commonName)
- cert.addDurationInHours(hours)
- cert.addDurationInDays(days)
- cert.startEarlier("2")
- for(san: URI<-webIds) {
- cert.addSubjectAlternativeName(san.toString)
- }
- var ser: CertSerialisation = null
- try {
- ser = cert.getSerialisation
- }
- catch {
- case ex: Exception => {
- throw new RuntimeException(ex)
- }
- }
- var pubKey: RSAPublicKey = cert.getSubjectPublicKey.getPublicKey.asInstanceOf[RSAPublicKey]
- var publicExponent: BigInteger = pubKey.getPublicExponent
- var modulus: BigInteger = pubKey.getModulus
-
- for (webid: URI<-webIds
- if (webid.getScheme=="https"||webid.getScheme=="http");
- val webidRef = new UriRef(webid.toString);
- val webIdInfo = webIdGraphsService.getWebIdInfo(webidRef);
- if (webIdInfo.isLocal)
- ) {
- val certGraph = new EzMGraph(webIdInfo.localPublicUserData)
- import certGraph._
- val certNode = certGraph.bnode
- ( (certNode a RSA.RSAPublicKey)
- -- CERT.identity --> webidRef
- -- RSA.modulus --> modulus
- -- RSA.public_exponent --> publicExponent
- -- DC.date --> cert.getStartDate )
- if (comment != null && comment.length > 0) {
- certNode -- RDFS.comment --> comment
- }
- }
- var resBuild: Response.ResponseBuilder = Response.ok(ser.getContent, MediaType.valueOf(ser.getMimeType))
- return resBuild.build
- }
-
- @POST
- @Path("deletekey")
- def deleteKey(@Context uriInfo: UriInfo,
- @FormParam("webId") webId: UriRef,
- @FormParam("keyhash") keys: List[String]): Response = {
- val webIDInfo = webIdGraphsService.getWebIdInfo(webId)
- val agent: GraphNode = new GraphNode(webId, webIDInfo.localPublicUserData)
- var subjects: Iterator[GraphNode] = agent.getSubjectNodes(CERT.identity)
- import scala.util.control.Breaks._
- breakable {
- import scala.collection.JavaConversions._
- //to for loop through iterators
- for (nl <- subjects) {
- var modulusIt: Iterator[Resource] = nl.getObjects(RSA.modulus)
- if (!modulusIt.hasNext) break
- var modLit: Resource = modulusIt.next
- if (modulusIt.hasNext) logger.warn("data error, a modulus too many in cert for " + webId)
- if (!(modLit.isInstanceOf[TypedLiteral])) {
- logger.warn("a public key has a modulus that is not a literal for " + webId)
- break
- }
- var modulus: BigInteger = LiteralFactory.getInstance.createObject(classOf[BigInteger], modLit.asInstanceOf[TypedLiteral])
- for (key <- keys) {
- if (modulus.hashCode == Integer.decode(key)) {
- nl.deleteNodeContext
- break
- }
- }
- }
- }
- return RedirectUtil.createSeeOtherResponse("../profile", uriInfo)
- }
-
- @POST
- @Path("modify")
- def modifyProfile(@Context uriInfo: UriInfo,
- @PathParam("id") userName: String,
- @FormParam("webId") webId: UriRef,
- @FormParam("name") name: String,
- @FormParam("description") description: String): Response = {
- val webIDInfo = AccessController.doPrivileged(new PrivilegedAction[WebIdInfo] {
- def run = {
- webIdGraphsService.getWebIdInfo(webId)
- }
- })
- val agent: GraphNode = new GraphNode(webId, webIDInfo.localPublicUserData)
- agent.deleteProperties(FOAF.name)
- agent.addPropertyValue(FOAF.name, name)
- agent.deleteProperties(DC.description)
- agent.addPropertyValue(DC.description, description)
- logger.debug("local graph (uri: {}) is now of size {}".format(webIDInfo.webId, webIDInfo.localPublicUserData.size))
- RedirectUtil.createSeeOtherResponse("../profile", uriInfo)
- }
-
- protected def bindUserManager(usermanager: UserManager): Unit = {
- userManager = usermanager
- }
-
- protected def unbindUserManager(usermanager: UserManager): Unit = {
- if (userManager == usermanager) {
- userManager = null
- }
- }
-
- protected def bindGraphNodeProvider(graphNodeProvider: GraphNodeProvider): Unit = {
- this.graphNodeProvider = graphNodeProvider
- }
-
- protected def unbindGraphNodeProvider(graphNodeProvider: GraphNodeProvider): Unit = {
- this.graphNodeProvider = null
- }
-
- protected def bindKeygenSrvc(keygenservice: KeygenService): Unit = {
- keygenSrvc = keygenservice
- }
-
- protected def unbindKeygenSrvc(keygenservice: KeygenService): Unit = {
- if (keygenSrvc == keygenservice) {
- keygenSrvc = null
- }
- }
-
-
- protected def bindWebIdGraphsService(webidgraphsservice: WebIdGraphsService): Unit = {
- webIdGraphsService = webidgraphsservice
- }
-
- protected def unbindWebIdGraphsService(webidgraphsservice: WebIdGraphsService): Unit = {
- webIdGraphsService = null
- }
-
- protected def bindPlatformConfig(platformconfig: PlatformConfig): Unit = {
- platformConfig = platformconfig
- }
-
- protected def unbindPlatformConfig(platformconfig: PlatformConfig): Unit = {
- if (platformConfig == platformconfig) {
- platformConfig = null
- }
- }
-
- protected def bindTcManager(tcManager: TcManager) = {
- this.tcManager = tcManager
- }
-
- protected def unbindTcManager(tcManager: TcManager) = {
- this.tcManager = null
- }
-
- protected def activate(componentContext: ComponentContext): Unit = {
- this.componentContext = componentContext
- }
-
-
- private var userManager: UserManager = null
-
- private var graphNodeProvider: GraphNodeProvider = null
-
- private var webIdGraphsService: WebIdGraphsService = null
-
- private var keygenSrvc: KeygenService = null
- private var platformConfig: PlatformConfig = null
-
-
- private var componentContext: ComponentContext = null
-
- private var tcManager: TcManager = null;
+ import collection.JavaConversions._
+ import Preamble._
+
+ /**
+ * Returns a GraphNode describing a ProfilePage for the user identified by
+ * the specified UserName. A ProfilePage resourcve is retuned for any user
+ * disregarding if they have a WebId and if this is local. The renderlet
+ * may provide instrcutions on how a WebId is created for users that do
+ * not have a WebId and redirect them to their WebId provider if they have
+ * a remote WebId.
+ */
+ @GET
+ def getPersonalProfilePage(@Context uriInfo: UriInfo,
+ @PathParam(value = "id") userName: String): GraphNode = {
+ TrailingSlash.enforceNotPresent(uriInfo)
+ //not checking as public profile must be public, more selective access control TBD
+ //AccessController.checkPermission(new AccountControlPanelAppPermission(userName, ""))
+ val resultNode= getPersonalProfile(userName, uriInfo)
+ return resultNode
+ }
+
+ private def getPersonalProfile(userName: String, info: UriInfo): GraphNode = {
+ lazy val suggestedPPDUri = getSuggestedPPDUri(userName)
+
+ val profile = AccessController.doPrivileged(new PrivilegedAction[GraphNode] {
+ def run: GraphNode = {
+ val userInSysGraph = userManager.getUserInSystemGraph(userName)
+ val userResource = userInSysGraph.getNode
+ val profile: GraphNode = userResource match {
+ case blank: BNode => {
+ //user does not have a webId yet
+ val g = new EzMGraph()
+ import g._
+ val profile = bnode
+ (profile -- CONTROLPANEL.isLocalProfile --> bool2lit(true)
+ -- CONTROLPANEL.suggestedPPDUri --> suggestedPPDUri
+ -- FOAF.primaryTopic --> (bnode -- PLATFORM.userName --> userName))
+ profile
+ }
+ case webid: UriRef => {
+ var webIDInfo = webIdGraphsService.getWebIdInfo(webid)
+ var res = new GraphNode(suggestedPPDUri, new UnionMGraph(new SimpleMGraph, webIDInfo.localPublicUserData))
+ (res -- CONTROLPANEL.isLocalProfile --> bool2lit(webIDInfo.isLocal)
+ -- FOAF.primaryTopic --> webid)
+ res
+ }
+ }
+ /*val friendInfo:Iterator[TripleCollection] = for (kn: Triple <- profile.getGraph.filter(userResource.asInstanceOf[NonLiteral], FOAF.knows, null)
+ if kn.getObject.isInstanceOf[UriRef];
+ friend = kn.getObject.asInstanceOf[UriRef]
+ if (friend != suggestedPPDUri)
+ ) yield {
+ try {
+ val friendGraph = tcManager.getGraph(FoafBrowser.removeHash(friend))
+ new RichGraphNode(friend, friendGraph).getNodeContext
+ } catch {
+ case e => {
+ logger.warn("cought exception trying to fetch graph - these graphs should already be in store " + friend, e)
+ new EzMGraph() {
+ friend -- SKOS.note --> ("problem with fetching this node: " + e)
+ }
+ }
+ }
+ }
+ //vera bad: mixing data from different sources
+ for (g <- friendInfo) profile.getGraph.addAll(g) */
+ profile
+ }
+ })
+
+
+ (profile a PLATFORM.HeadedPage
+ a CONTROLPANEL.ProfilePage)
+ }
+
+ /**
+ * @param userName
+ * @return the suggested Personal Profile Document URI
+ */
+ def getSuggestedPPDUri(userName: String): UriRef = {
+ return new UriRef(platformConfig.getDefaultBaseUri.getUnicodeString + "user/" + userName + "/profile")
+ }
+
+ @POST
+ @Path("set-existing-webid")
+ def setExistingWebId(@Context uriInfo: UriInfo,
+ @FormParam("webid") webId: UriRef,
+ @PathParam(value = "id") userName: String): Response = {
+ AccessController.checkPermission(new AccountControlPanelAppPermission(userName, ""))
+ return AccessController.doPrivileged(new PrivilegedAction[Response] {
+ def run: Response = {
+ var userInSystemGraph: GraphNode = userManager.getUserInSystemGraph(userName)
+ userInSystemGraph.replaceWith(webId)
+ return RedirectUtil.createSeeOtherResponse("../profile", uriInfo)
+ }
+ })
+ }
+
+ @POST
+ @Path("create-new-web-id")
+ def createNewWebId(@Context uriInfo: UriInfo,
+ @PathParam(value = "id") userName: String): Response = {
+ val ppd: UriRef = getSuggestedPPDUri(userName)
+ val webId: UriRef = new UriRef(ppd.getUnicodeString + "#me")
+ AccessController.checkPermission(new AccountControlPanelAppPermission(userName, ""))
+ return AccessController.doPrivileged(new PrivilegedAction[Response] {
+ def run: Response = {
+ userManager.assignPermissionsToUser(userName, java.util.Collections.singletonList(new TcPermission(
+ webId.getUnicodeString, TcPermission.READWRITE).toString))
+ tcManager.getTcAccessController.setRequiredReadPermissionStrings(
+ ppd, Collections.singleton(new TcPermission(
+ Constants.CONTENT_GRAPH_URI_STRING, TcPermission.READ).toString))
+ tcManager.createMGraph(ppd)
+ val webIDInfo = webIdGraphsService.getWebIdInfo(webId)
+ webIDInfo.localPublicUserData.addAll(
+ Arrays.asList(
+ new TripleImpl(ppd, RDF.`type`, FOAF.PersonalProfileDocument),
+ new TripleImpl(ppd, FOAF.primaryTopic, webId))
+ )
+ var userInSystemGraph: GraphNode = userManager.getUserInSystemGraph(userName)
+ userInSystemGraph.replaceWith(webId)
+ return RedirectUtil.createSeeOtherResponse("../profile", uriInfo)
+ }
+ })
+ }
+
+ /**
+ * Presents a confirmation form for adding a contact
+ */
+ @GET
+ @Path("addContact")
+ def addContactConfirm(@PathParam(value = "id") userName: String,
+ @QueryParam("contactWebId") contactWebId: UriRef): GraphNode = {
+ AccessController.checkPermission(new AccountControlPanelAppPermission(userName, ""))
+ val contactNode = AccessController.doPrivileged(new PrivilegedAction[GraphNode] {
+ def run = {
+ graphNodeProvider.get(contactWebId);
+ }
+ })
+ val resultGraph = new EzMGraph(new UnionMGraph(new SimpleMGraph, contactNode.getGraph))
+ import resultGraph._
+ val result: GraphNode = bnode
+ result a CONTROLPANEL.ContactConfirmPage
+ result -- FOAF.primaryTopic --> contactNode
+ }
+
+ @POST
+ @Path("addContact")
+ def addContact(@PathParam(value = "id") userName: String, @Context uriInfo: UriInfo,
+ @FormParam("webId") newContacts: java.util.List[UriRef]): Response = {
+ import collection.JavaConversions._
+ if (newContacts.size > 0) {
+ var me: GraphNode = AccessController.doPrivileged(new PrivilegedAction[GraphNode] {
+ def run: GraphNode = {
+ return userManager.getUserGraphNode(userName)
+ }
+ })
+ for (contactWebID <- newContacts) {
+ val webIdGraphs = webIdGraphsService.getWebIdInfo(me.getNode.asInstanceOf[UriRef])
+ var meGrph: GraphNode = new GraphNode(me.getNode, webIdGraphs.localPublicUserData)
+ meGrph.addProperty(FOAF.knows, contactWebID)
+ } //todo: one should catch errors here (bad uris sent for ex
+ }
+ return RedirectUtil.createSeeOtherResponse("../profile", uriInfo)
+ }
+
+ /**
+ * Removes a contact
+ */
+ @POST
+ @Path("deleteContact")
+ def deleteContact(@PathParam(value = "id") userName: String, @Context uriInfo: UriInfo,
+ @FormParam("contactWebId") contactWebId: UriRef): Response = {
+ import collection.JavaConversions._
+ var me: GraphNode = AccessController.doPrivileged(new PrivilegedAction[GraphNode] {
+ def run: GraphNode = {
+ return userManager.getUserGraphNode(userName)
+ }
+ })
+ val webIdGraphs = webIdGraphsService.getWebIdInfo(me.getNode.asInstanceOf[UriRef])
+ var meGrph: GraphNode = new GraphNode(me.getNode, webIdGraphs.localPublicUserData)
+ meGrph.deleteProperty(FOAF.knows, contactWebId)
+ return RedirectUtil.createSeeOtherResponse("../profile", uriInfo)
+ }
+
+ /**
+ * @parm webId: A list of WebIDs to be added as Subject Alternative Names
+ * @param cn Common Name, the name that usually appears in the certificate selection box
+ * @param spkac key request in format generated by Netscape, Safari, Opera
+ * @param crmf hey request in format generated by M$ Explorer
+ * @param csr key request as generated by Javascript of Netscape
+ * @param hours the certificate should last (hours and days add up)
+ * @param days the certificate should last
+ * @param comment a comment to be attached to the public key in the database
+ */
+ @POST
+ @Path("keygen")
+ def createCert(@FormParam("webId") webIds: java.util.List[URI],
+ @FormParam("cn") commonName: String,
+ @FormParam("spkac") spkac: String,
+ @FormParam("crmf") crmf: String,
+ @FormParam("csr") csr: String,
+ @FormParam("hours") hours: String,
+ @FormParam("days") days: String,
+ @FormParam("comment") comment: String): Response = {
+ import scala.collection.JavaConversions._
+ var cert: Certificate = null
+ if (spkac != null && spkac.length > 0) {
+ cert = keygenSrvc.createFromSpkac(spkac)
+ if (cert == null) {
+ logger.warn("unable to create certificate from spkac request")
+ }
+ }
+ if (cert == null && crmf != null && crmf.length > 0) {
+ cert = keygenSrvc.createFromCRMF(crmf)
+ if (cert == null) {
+ logger.warn("unable to create certificate from crmf requrest :" + crmf)
+ }
+ }
+ if (cert == null && csr != null && csr.length > 0) {
+ cert = keygenSrvc.createFromPEM(csr)
+ if (cert == null) {
+ logger.warn("unable to create certificate from csr request :" + csr)
+ }
+ }
+ if (cert == null) {
+ throw new RuntimeException("The server was unable to create a certificate")
+ }
+ cert.setSubjectCommonName(commonName)
+ cert.addDurationInHours(hours)
+ cert.addDurationInDays(days)
+ cert.startEarlier("2")
+ for(san: URI<-webIds) {
+ cert.addSubjectAlternativeName(san.toString)
+ }
+ var ser: CertSerialisation = null
+ try {
+ ser = cert.getSerialisation
+ }
+ catch {
+ case ex: Exception => {
+ throw new RuntimeException(ex)
+ }
+ }
+ var pubKey: RSAPublicKey = cert.getSubjectPublicKey.getPublicKey.asInstanceOf[RSAPublicKey]
+ var publicExponent: BigInteger = pubKey.getPublicExponent
+ var modulus: BigInteger = pubKey.getModulus
+
+ for (webid: URI<-webIds
+ if (webid.getScheme=="https"||webid.getScheme=="http");
+ val webidRef = new UriRef(webid.toString);
+ val webIdInfo = webIdGraphsService.getWebIdInfo(webidRef);
+ if (webIdInfo.isLocal)
+ ) {
+ val certGraph = new EzMGraph(webIdInfo.localPublicUserData)
+ import certGraph._
+ val certNode = certGraph.bnode
+ ( (certNode a RSA.RSAPublicKey)
+ -- CERT.identity --> webidRef
+ -- RSA.modulus --> modulus
+ -- RSA.public_exponent --> publicExponent
+ -- DC.date --> cert.getStartDate )
+ if (comment != null && comment.length > 0) {
+ certNode -- RDFS.comment --> comment
+ }
+ }
+ var resBuild: Response.ResponseBuilder = Response.ok(ser.getContent, MediaType.valueOf(ser.getMimeType))
+ return resBuild.build
+ }
+
+ @POST
+ @Path("deletekey")
+ def deleteKey(@Context uriInfo: UriInfo,
+ @FormParam("webId") webId: UriRef,
+ @FormParam("keyhash") keys: List[String]): Response = {
+ val webIDInfo = webIdGraphsService.getWebIdInfo(webId)
+ val agent: GraphNode = new GraphNode(webId, webIDInfo.localPublicUserData)
+ var subjects: Iterator[GraphNode] = agent.getSubjectNodes(CERT.identity)
+ import scala.util.control.Breaks._
+ breakable {
+ import scala.collection.JavaConversions._
+ //to for loop through iterators
+ for (nl <- subjects) {
+ var modulusIt: Iterator[Resource] = nl.getObjects(RSA.modulus)
+ if (!modulusIt.hasNext) break
+ var modLit: Resource = modulusIt.next
+ if (modulusIt.hasNext) logger.warn("data error, a modulus too many in cert for " + webId)
+ if (!(modLit.isInstanceOf[TypedLiteral])) {
+ logger.warn("a public key has a modulus that is not a literal for " + webId)
+ break
+ }
+ var modulus: BigInteger = LiteralFactory.getInstance.createObject(classOf[BigInteger], modLit.asInstanceOf[TypedLiteral])
+ for (key <- keys) {
+ if (modulus.hashCode == Integer.decode(key)) {
+ nl.deleteNodeContext
+ break
+ }
+ }
+ }
+ }
+ return RedirectUtil.createSeeOtherResponse("../profile", uriInfo)
+ }
+
+ @POST
+ @Path("modify")
+ def modifyProfile(@Context uriInfo: UriInfo,
+ @PathParam("id") userName: String,
+ @FormParam("webId") webId: UriRef,
+ @FormParam("name") name: String,
+ @FormParam("description") description: String): Response = {
+ val webIDInfo = AccessController.doPrivileged(new PrivilegedAction[WebIdInfo] {
+ def run = {
+ webIdGraphsService.getWebIdInfo(webId)
+ }
+ })
+ val agent: GraphNode = new GraphNode(webId, webIDInfo.localPublicUserData)
+ agent.deleteProperties(FOAF.name)
+ agent.addPropertyValue(FOAF.name, name)
+ agent.deleteProperties(DC.description)
+ agent.addPropertyValue(DC.description, description)
+ logger.debug("local graph (uri: {}) is now of size {}".format(webIDInfo.webId, webIDInfo.localPublicUserData.size))
+ RedirectUtil.createSeeOtherResponse("../profile", uriInfo)
+ }
+
+ protected def bindUserManager(usermanager: UserManager): Unit = {
+ userManager = usermanager
+ }
+
+ protected def unbindUserManager(usermanager: UserManager): Unit = {
+ if (userManager == usermanager) {
+ userManager = null
+ }
+ }
+
+ protected def bindGraphNodeProvider(graphNodeProvider: GraphNodeProvider): Unit = {
+ this.graphNodeProvider = graphNodeProvider
+ }
+
+ protected def unbindGraphNodeProvider(graphNodeProvider: GraphNodeProvider): Unit = {
+ this.graphNodeProvider = null
+ }
+
+ protected def bindKeygenSrvc(keygenservice: KeygenService): Unit = {
+ keygenSrvc = keygenservice
+ }
+
+ protected def unbindKeygenSrvc(keygenservice: KeygenService): Unit = {
+ if (keygenSrvc == keygenservice) {
+ keygenSrvc = null
+ }
+ }
+
+
+ protected def bindWebIdGraphsService(webidgraphsservice: WebIdGraphsService): Unit = {
+ webIdGraphsService = webidgraphsservice
+ }
+
+ protected def unbindWebIdGraphsService(webidgraphsservice: WebIdGraphsService): Unit = {
+ webIdGraphsService = null
+ }
+
+ protected def bindPlatformConfig(platformconfig: PlatformConfig): Unit = {
+ platformConfig = platformconfig
+ }
+
+ protected def unbindPlatformConfig(platformconfig: PlatformConfig): Unit = {
+ if (platformConfig == platformconfig) {
+ platformConfig = null
+ }
+ }
+
+ protected def bindTcManager(tcManager: TcManager) = {
+ this.tcManager = tcManager
+ }
+
+ protected def unbindTcManager(tcManager: TcManager) = {
+ this.tcManager = null
+ }
+
+ protected def activate(componentContext: ComponentContext): Unit = {
+ this.componentContext = componentContext
+ }
+
+
+ private var userManager: UserManager = null
+
+ private var graphNodeProvider: GraphNodeProvider = null
+
+ private var webIdGraphsService: WebIdGraphsService = null
+
+ private var keygenSrvc: KeygenService = null
+ private var platformConfig: PlatformConfig = null
+
+
+ private var componentContext: ComponentContext = null
+
+ private var tcManager: TcManager = null;
}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/platform.accountcontrolpanel/platform.accountcontrolpanel.core/src/main/scala/org/apache/clerezza/platform/accountcontrolpanel/SettingsPanel.scala
----------------------------------------------------------------------
diff --git a/platform.accountcontrolpanel/platform.accountcontrolpanel.core/src/main/scala/org/apache/clerezza/platform/accountcontrolpanel/SettingsPanel.scala b/platform.accountcontrolpanel/platform.accountcontrolpanel.core/src/main/scala/org/apache/clerezza/platform/accountcontrolpanel/SettingsPanel.scala
index d7631a1..3d8d929 100644
--- a/platform.accountcontrolpanel/platform.accountcontrolpanel.core/src/main/scala/org/apache/clerezza/platform/accountcontrolpanel/SettingsPanel.scala
+++ b/platform.accountcontrolpanel/platform.accountcontrolpanel.core/src/main/scala/org/apache/clerezza/platform/accountcontrolpanel/SettingsPanel.scala
@@ -92,7 +92,7 @@ import org.apache.clerezza.rdf.utils.GraphNode
import org.apache.clerezza.rdf.utils.UnionMGraph
object SettingPanel {
- val logger: Logger = LoggerFactory.getLogger(classOf[SettingsPanel])
+ val logger: Logger = LoggerFactory.getLogger(classOf[SettingsPanel])
}
/**
@@ -104,543 +104,543 @@ object SettingPanel {
@Path("/user/{id}/control-panel")
class SettingsPanel {
- import SettingPanel.logger
+ import SettingPanel.logger
- /**
- * Mainpage
- *
- * @param id is the username as given in the URL
- * @return an array of installed {@link Bundle}s to be managed
- *
- */
- @GET
- def settingsPage(@PathParam(value = "id") idP: String,
- @QueryParam("changedPassword") changedPassword: String,
- @Context uriInfo: UriInfo): GraphNode = {
- TrailingSlash.enforceNotPresent(uriInfo)
- val id: String = idP
- var graphNode: GraphNode = null
- AccessController.checkPermission(new AccountControlPanelAppPermission(id, ""))
- try {
- AccessController.checkPermission(new UserBundlePermission(id, ""))
- graphNode = AccessController.doPrivileged(new PrivilegedAction[GraphNode] {
- def run: GraphNode = {
- var bundles: Array[Bundle] = userBundles(getAgent(id))
- return asGraphNode(id, bundles)
- }
- })
- }
- catch {
- case e: AccessControlException => {
- graphNode = new GraphNode(new BNode, new SimpleMGraph)
- graphNode.addProperty(CONTROLPANEL.userBundlePermission, LiteralFactory.getInstance.createTypedLiteral(false))
- }
- }
- try {
- AccessController.checkPermission(new ChangePasswordPermission(id, ""))
- graphNode.addProperty(CONTROLPANEL.changePasswordPermission, LiteralFactory.getInstance.createTypedLiteral(true))
- }
- catch {
- case e: AccessControlException => {
- graphNode.addProperty(CONTROLPANEL.changePasswordPermission, LiteralFactory.getInstance.createTypedLiteral(false))
- }
- }
- if (changedPassword != null && changedPassword.equals("false")) {
- graphNode.addProperty(CONTROLPANEL.changedPassword, new PlainLiteralImpl("false"))
- }
- graphNode.addProperty(RDF.`type`, CONTROLPANEL.SettingsPage)
- graphNode.addProperty(RDF.`type`, PLATFORM.HeadedPage)
- return graphNode
- }
+ /**
+ * Mainpage
+ *
+ * @param id is the username as given in the URL
+ * @return an array of installed {@link Bundle}s to be managed
+ *
+ */
+ @GET
+ def settingsPage(@PathParam(value = "id") idP: String,
+ @QueryParam("changedPassword") changedPassword: String,
+ @Context uriInfo: UriInfo): GraphNode = {
+ TrailingSlash.enforceNotPresent(uriInfo)
+ val id: String = idP
+ var graphNode: GraphNode = null
+ AccessController.checkPermission(new AccountControlPanelAppPermission(id, ""))
+ try {
+ AccessController.checkPermission(new UserBundlePermission(id, ""))
+ graphNode = AccessController.doPrivileged(new PrivilegedAction[GraphNode] {
+ def run: GraphNode = {
+ var bundles: Array[Bundle] = userBundles(getAgent(id))
+ return asGraphNode(id, bundles)
+ }
+ })
+ }
+ catch {
+ case e: AccessControlException => {
+ graphNode = new GraphNode(new BNode, new SimpleMGraph)
+ graphNode.addProperty(CONTROLPANEL.userBundlePermission, LiteralFactory.getInstance.createTypedLiteral(false))
+ }
+ }
+ try {
+ AccessController.checkPermission(new ChangePasswordPermission(id, ""))
+ graphNode.addProperty(CONTROLPANEL.changePasswordPermission, LiteralFactory.getInstance.createTypedLiteral(true))
+ }
+ catch {
+ case e: AccessControlException => {
+ graphNode.addProperty(CONTROLPANEL.changePasswordPermission, LiteralFactory.getInstance.createTypedLiteral(false))
+ }
+ }
+ if (changedPassword != null && changedPassword.equals("false")) {
+ graphNode.addProperty(CONTROLPANEL.changedPassword, new PlainLiteralImpl("false"))
+ }
+ graphNode.addProperty(RDF.`type`, CONTROLPANEL.SettingsPage)
+ graphNode.addProperty(RDF.`type`, PLATFORM.HeadedPage)
+ return graphNode
+ }
- private def addBundleDescriptionToGraph(responseGraph: MGraph, bundle: Bundle): Unit = {
- var status: TypedLiteral = LiteralFactory.getInstance.createTypedLiteral(bundle.getState)
- var bundleUri: UriRef = new UriRef(bundle.getLocation)
- var triple: Triple = new TripleImpl(bundleUri, OSGI.status, status)
- responseGraph.add(triple)
- var bundleId: TypedLiteral = LiteralFactory.getInstance.createTypedLiteral(bundle.getBundleId)
- triple = new TripleImpl(bundleUri, OSGI.bundle_id, bundleId)
- responseGraph.add(triple)
- }
+ private def addBundleDescriptionToGraph(responseGraph: MGraph, bundle: Bundle): Unit = {
+ var status: TypedLiteral = LiteralFactory.getInstance.createTypedLiteral(bundle.getState)
+ var bundleUri: UriRef = new UriRef(bundle.getLocation)
+ var triple: Triple = new TripleImpl(bundleUri, OSGI.status, status)
+ responseGraph.add(triple)
+ var bundleId: TypedLiteral = LiteralFactory.getInstance.createTypedLiteral(bundle.getBundleId)
+ triple = new TripleImpl(bundleUri, OSGI.bundle_id, bundleId)
+ responseGraph.add(triple)
+ }
- private def asGraphNode(userId: String, bundles: Array[Bundle]): GraphNode = {
- val responseGraph: MGraph = new SimpleMGraph
- for (bundle <- bundles) {
- addBundleDescriptionToGraph(responseGraph, bundle)
- }
- return AccessController.doPrivileged(new PrivilegedAction[GraphNode] {
- def run: GraphNode = {
- var userDescriptionGraph: Graph = new GraphNode(getAgent(userId), systemGraph).getNodeContext
- var unionGraph: UnionMGraph = new UnionMGraph(responseGraph, userDescriptionGraph)
- var graphNode: GraphNode = new GraphNode(getAgent(userId), unionGraph)
- graphNode.addProperty(CONTROLPANEL.userBundlePermission, LiteralFactory.getInstance.createTypedLiteral(true))
- return graphNode
- }
- })
- }
+ private def asGraphNode(userId: String, bundles: Array[Bundle]): GraphNode = {
+ val responseGraph: MGraph = new SimpleMGraph
+ for (bundle <- bundles) {
+ addBundleDescriptionToGraph(responseGraph, bundle)
+ }
+ return AccessController.doPrivileged(new PrivilegedAction[GraphNode] {
+ def run: GraphNode = {
+ var userDescriptionGraph: Graph = new GraphNode(getAgent(userId), systemGraph).getNodeContext
+ var unionGraph: UnionMGraph = new UnionMGraph(responseGraph, userDescriptionGraph)
+ var graphNode: GraphNode = new GraphNode(getAgent(userId), unionGraph)
+ graphNode.addProperty(CONTROLPANEL.userBundlePermission, LiteralFactory.getInstance.createTypedLiteral(true))
+ return graphNode
+ }
+ })
+ }
- /**
- * Retrieves all bundles owned by a user represented by agent
- *
- * @param agent represents the user who owns bundles to be returned
- * @return an array of {@link Bundle}s owned by the user
- *
- */
- private def userBundles(agent: NonLiteral): Array[Bundle] = {
- logger.debug("Retrieve all bundles from user: {}", agent)
- var installedBundles: Array[Bundle] = componentContext.getBundleContext.getBundles
- val locationMapper: Map[String, Long] = new HashMap[String, Long]
- for (b <- installedBundles) {
- locationMapper.put(b.getLocation, b.getBundleId)
- }
- return AccessController.doPrivileged(new PrivilegedAction[Array[Bundle]] {
- def run: Array[Bundle] = {
- var bundles: Set[Bundle] = new HashSet[Bundle]
- var agentBundles: Iterator[Triple] = systemGraph.filter(null, OSGI.owner, agent)
- while (agentBundles.hasNext) {
- val location: String = (agentBundles.next.getSubject.asInstanceOf[UriRef]).getUnicodeString
- try {
- val id: Long = locationMapper.get(location)
- bundles.add(componentContext.getBundleContext.getBundle(id))
- } catch {
- case _:NumberFormatException => None
- }
- }
- return bundles.toArray(new Array[Bundle](bundles.size))
- }
- })
- }
+ /**
+ * Retrieves all bundles owned by a user represented by agent
+ *
+ * @param agent represents the user who owns bundles to be returned
+ * @return an array of {@link Bundle}s owned by the user
+ *
+ */
+ private def userBundles(agent: NonLiteral): Array[Bundle] = {
+ logger.debug("Retrieve all bundles from user: {}", agent)
+ var installedBundles: Array[Bundle] = componentContext.getBundleContext.getBundles
+ val locationMapper: Map[String, Long] = new HashMap[String, Long]
+ for (b <- installedBundles) {
+ locationMapper.put(b.getLocation, b.getBundleId)
+ }
+ return AccessController.doPrivileged(new PrivilegedAction[Array[Bundle]] {
+ def run: Array[Bundle] = {
+ var bundles: Set[Bundle] = new HashSet[Bundle]
+ var agentBundles: Iterator[Triple] = systemGraph.filter(null, OSGI.owner, agent)
+ while (agentBundles.hasNext) {
+ val location: String = (agentBundles.next.getSubject.asInstanceOf[UriRef]).getUnicodeString
+ try {
+ val id: Long = locationMapper.get(location)
+ bundles.add(componentContext.getBundleContext.getBundle(id))
+ } catch {
+ case _:NumberFormatException => None
+ }
+ }
+ return bundles.toArray(new Array[Bundle](bundles.size))
+ }
+ })
+ }
- private def getAgent(id: String): NonLiteral = {
- logger.debug("Get agent with id {}", id)
- var agents: Iterator[Triple] = systemGraph.filter(null, PLATFORM.userName, new PlainLiteralImpl(id))
- if (agents.hasNext) {
- return agents.next.getSubject
- }
- else {
- logger.debug("System graph does not contain user: {}", id)
- var responseBuilder: Response.ResponseBuilder = Response.ok("<html><body>User does not exist</body></html>")
- throw new WebApplicationException(responseBuilder.build)
- }
- }
+ private def getAgent(id: String): NonLiteral = {
+ logger.debug("Get agent with id {}", id)
+ var agents: Iterator[Triple] = systemGraph.filter(null, PLATFORM.userName, new PlainLiteralImpl(id))
+ if (agents.hasNext) {
+ return agents.next.getSubject
+ }
+ else {
+ logger.debug("System graph does not contain user: {}", id)
+ var responseBuilder: Response.ResponseBuilder = Response.ok("<html><body>User does not exist</body></html>")
+ throw new WebApplicationException(responseBuilder.build)
+ }
+ }
- private def getAgentPathPrefix(agent: NonLiteral): PlainLiteralImpl = {
- return AccessController.doPrivileged(new PrivilegedAction[PlainLiteralImpl] {
- def run: PlainLiteralImpl = {
- var pathPrefixes: Iterator[Triple] = systemGraph.filter(agent, OSGI.agent_path_prefix, null)
- if (pathPrefixes.hasNext) {
- return pathPrefixes.next.getObject.asInstanceOf[PlainLiteralImpl]
- }
- return null
- }
- })
- }
+ private def getAgentPathPrefix(agent: NonLiteral): PlainLiteralImpl = {
+ return AccessController.doPrivileged(new PrivilegedAction[PlainLiteralImpl] {
+ def run: PlainLiteralImpl = {
+ var pathPrefixes: Iterator[Triple] = systemGraph.filter(agent, OSGI.agent_path_prefix, null)
+ if (pathPrefixes.hasNext) {
+ return pathPrefixes.next.getObject.asInstanceOf[PlainLiteralImpl]
+ }
+ return null
+ }
+ })
+ }
- /**
- * Installs a bundle from the specified location.
- *
- * @param id is the username as given in the URL
- * @param location specifies the URL of the bundle to be installed
- * @return an array of installed {@link Bundle}s to be managed
- *
- */
- @POST
- @Path("install-bundle")
- @Consumes def installBundle(@PathParam(value = "id") id: String, multiForm: MultiPartBody, @Context uriInfo: UriInfo): Response = {
- AccessController.checkPermission(new AccountControlPanelAppPermission(id, ""))
- AccessController.checkPermission(new UserBundlePermission(id, ""))
- var formFiles: Array[FormFile] = multiForm.getFormFileParameterValues("bundle")
- var filename: String = formFiles(0).getFileName
- var bundleBytes: Array[Byte] = formFiles(0).getContent
- if (bundleBytes.length == 0) {
- var message: String = null
- if (filename.equals("")) {
- message = "No bundle specified"
- }
- else {
- message = "Bundle has length 0"
- }
- var responseBuilder: Response.ResponseBuilder = Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(message)
- throw new WebApplicationException(responseBuilder.build)
- }
- val bundleInputStream: InputStream = new ByteArrayInputStream(bundleBytes)
- val location: String = "userbundle:" + id + "/" + filename
- logger.info("Install bundle {} to location {}", id, location)
- AccessController.doPrivileged(new PrivilegedAction[AnyRef] {
- def run: Array[Bundle] = {
- val agent: NonLiteral = getAgent(id)
- val triple: Triple = new TripleImpl(new UriRef(location), OSGI.owner, agent)
- try {
- systemGraph.add(triple)
- var bundle: Bundle = componentContext.getBundleContext.installBundle(location, bundleInputStream)
- var prefix: PlainLiteralImpl = getAgentPathPrefix(agent)
- if (prefix != null) {
- addBundlePrefix(bundle, prefix.getLexicalForm)
- }
- return null
- }
- catch {
- case ex: BundleException => {
- systemGraph.remove(triple)
- logger.debug("Failed to install a bundle from: {}", location)
- logger.error("Exception during install bundle: {}", ex)
- var responseBuilder: Response.ResponseBuilder = Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ex.getMessage)
- throw new WebApplicationException(responseBuilder.build)
- }
- }
- }
- })
- return RedirectUtil.createSeeOtherResponse("../control-panel", uriInfo)
- }
+ /**
+ * Installs a bundle from the specified location.
+ *
+ * @param id is the username as given in the URL
+ * @param location specifies the URL of the bundle to be installed
+ * @return an array of installed {@link Bundle}s to be managed
+ *
+ */
+ @POST
+ @Path("install-bundle")
+ @Consumes def installBundle(@PathParam(value = "id") id: String, multiForm: MultiPartBody, @Context uriInfo: UriInfo): Response = {
+ AccessController.checkPermission(new AccountControlPanelAppPermission(id, ""))
+ AccessController.checkPermission(new UserBundlePermission(id, ""))
+ var formFiles: Array[FormFile] = multiForm.getFormFileParameterValues("bundle")
+ var filename: String = formFiles(0).getFileName
+ var bundleBytes: Array[Byte] = formFiles(0).getContent
+ if (bundleBytes.length == 0) {
+ var message: String = null
+ if (filename.equals("")) {
+ message = "No bundle specified"
+ }
+ else {
+ message = "Bundle has length 0"
+ }
+ var responseBuilder: Response.ResponseBuilder = Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(message)
+ throw new WebApplicationException(responseBuilder.build)
+ }
+ val bundleInputStream: InputStream = new ByteArrayInputStream(bundleBytes)
+ val location: String = "userbundle:" + id + "/" + filename
+ logger.info("Install bundle {} to location {}", id, location)
+ AccessController.doPrivileged(new PrivilegedAction[AnyRef] {
+ def run: Array[Bundle] = {
+ val agent: NonLiteral = getAgent(id)
+ val triple: Triple = new TripleImpl(new UriRef(location), OSGI.owner, agent)
+ try {
+ systemGraph.add(triple)
+ var bundle: Bundle = componentContext.getBundleContext.installBundle(location, bundleInputStream)
+ var prefix: PlainLiteralImpl = getAgentPathPrefix(agent)
+ if (prefix != null) {
+ addBundlePrefix(bundle, prefix.getLexicalForm)
+ }
+ return null
+ }
+ catch {
+ case ex: BundleException => {
+ systemGraph.remove(triple)
+ logger.debug("Failed to install a bundle from: {}", location)
+ logger.error("Exception during install bundle: {}", ex)
+ var responseBuilder: Response.ResponseBuilder = Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ex.getMessage)
+ throw new WebApplicationException(responseBuilder.build)
+ }
+ }
+ }
+ })
+ return RedirectUtil.createSeeOtherResponse("../control-panel", uriInfo)
+ }
- private def addBundlePrefix(bundle: Bundle, prefix: String): Unit = {
- var symbolicName: String = bundle.getSymbolicName
- /*if (configAdmin != null) {
- try {
- var configuration: Configuration = configAdmin.getConfiguration(classOf[TriaxrsPrefixManager].getName)
- val properties = configuration.getProperties match {
- case null => new Hashtable[String, AnyRef]()
- case dict: Dictionary[String, AnyRef] => dict
- }
- var mappings = TriaxrsPrefixManager.parseMappings(properties.get(TriaxrsPrefixManager.TRIAXRS_MAPPINGS).asInstanceOf[Array[String]])
- logger.debug("Prefix {} added to bundle {}", prefix, symbolicName)
- mappings.put(symbolicName, prefix)
- var newMappings: Array[String] = TriaxrsPrefixManager.unparseMappings(mappings)
- properties.put(TriaxrsPrefixManager.TRIAXRS_MAPPINGS, newMappings)
- configuration.update(properties)
- }
- catch {
- case e: IOException => {
- logger.warn("Unable to update configuration: {}", e.toString)
- }
- }
- }
- else {
- logger.warn("Cannot add prefix mapping. Configuration Admin is missing")
- }*/
- }
+ private def addBundlePrefix(bundle: Bundle, prefix: String): Unit = {
+ var symbolicName: String = bundle.getSymbolicName
+ /*if (configAdmin != null) {
+ try {
+ var configuration: Configuration = configAdmin.getConfiguration(classOf[TriaxrsPrefixManager].getName)
+ val properties = configuration.getProperties match {
+ case null => new Hashtable[String, AnyRef]()
+ case dict: Dictionary[String, AnyRef] => dict
+ }
+ var mappings = TriaxrsPrefixManager.parseMappings(properties.get(TriaxrsPrefixManager.TRIAXRS_MAPPINGS).asInstanceOf[Array[String]])
+ logger.debug("Prefix {} added to bundle {}", prefix, symbolicName)
+ mappings.put(symbolicName, prefix)
+ var newMappings: Array[String] = TriaxrsPrefixManager.unparseMappings(mappings)
+ properties.put(TriaxrsPrefixManager.TRIAXRS_MAPPINGS, newMappings)
+ configuration.update(properties)
+ }
+ catch {
+ case e: IOException => {
+ logger.warn("Unable to update configuration: {}", e.toString)
+ }
+ }
+ }
+ else {
+ logger.warn("Cannot add prefix mapping. Configuration Admin is missing")
+ }*/
+ }
- private[accountcontrolpanel] def removeBundlePrefix(bundle: Bundle): Unit = {
- var symbolicName: String = bundle.getSymbolicName
- /*if ((this.configAdmin != null) && (symbolicName != null)) {
- try {
- val configuration: Configuration = configAdmin.getConfiguration(classOf[TriaxrsPrefixManager].getName)
- val properties = configuration.getProperties match {
- case null => new Hashtable[String, AnyRef]()
- case dict: Dictionary[String, AnyRef] => dict
- }
- val mappings = TriaxrsPrefixManager.parseMappings(properties.get(TriaxrsPrefixManager.TRIAXRS_MAPPINGS).asInstanceOf[Array[String]])
- mappings.remove(symbolicName)
- val newMappings: Array[String] = TriaxrsPrefixManager.unparseMappings(mappings)
- properties.put(TriaxrsPrefixManager.TRIAXRS_MAPPINGS, newMappings)
- configuration.update(properties)
- }
- catch {
- case e: IOException => {
- logger.warn("Unable to update configuration: {}", e.toString)
- }
- }
- }
- else {
- logger.warn("Cannot add prefix mapping. Configuration Admin is missing")
- }*/
- }
+ private[accountcontrolpanel] def removeBundlePrefix(bundle: Bundle): Unit = {
+ var symbolicName: String = bundle.getSymbolicName
+ /*if ((this.configAdmin != null) && (symbolicName != null)) {
+ try {
+ val configuration: Configuration = configAdmin.getConfiguration(classOf[TriaxrsPrefixManager].getName)
+ val properties = configuration.getProperties match {
+ case null => new Hashtable[String, AnyRef]()
+ case dict: Dictionary[String, AnyRef] => dict
+ }
+ val mappings = TriaxrsPrefixManager.parseMappings(properties.get(TriaxrsPrefixManager.TRIAXRS_MAPPINGS).asInstanceOf[Array[String]])
+ mappings.remove(symbolicName)
+ val newMappings: Array[String] = TriaxrsPrefixManager.unparseMappings(mappings)
+ properties.put(TriaxrsPrefixManager.TRIAXRS_MAPPINGS, newMappings)
+ configuration.update(properties)
+ }
+ catch {
+ case e: IOException => {
+ logger.warn("Unable to update configuration: {}", e.toString)
+ }
+ }
+ }
+ else {
+ logger.warn("Cannot add prefix mapping. Configuration Admin is missing")
+ }*/
+ }
- /**
- * Starts the bundle with the specified bundle id.
- *
- * @param id is the username as given in the URL
- * @param bundleIdString specifies the id of the bundle to be started
- * @return an array of installed {@link Bundle}s to be managed
- *
- */
- @POST
- @Path("start-bundle")
- def startBundle(@PathParam(value = "id") idP: String,
- @FormParam("bundleId") bundleIdStringP: String,
- @Context uriInfo: UriInfo): Response = {
- val id: String = idP
- val bundleIdString: String = bundleIdStringP
- AccessController.checkPermission(new AccountControlPanelAppPermission(id, ""))
- AccessController.checkPermission(new UserBundlePermission(id, ""))
- logger.info("Start bundle {} ", id)
- val bundleId: Long = bundleIdString.toLong
- AccessController.doPrivileged(new PrivilegedAction[AnyRef] {
- def run: Array[Bundle] = {
- try {
- val bundle: Bundle = componentContext.getBundleContext.getBundle(bundleId)
- bundle.start
- }
- catch {
- case e: BundleException => {
- logger.debug("Failed to start bundle {}", bundleIdString)
- logger.error("Exception during start bundle: {}", e)
- var responseBuilder: Response.ResponseBuilder = Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage)
- throw new WebApplicationException(responseBuilder.build)
- }
- }
- return null
- }
- })
- return RedirectUtil.createSeeOtherResponse("../control-panel", uriInfo)
- }
+ /**
+ * Starts the bundle with the specified bundle id.
+ *
+ * @param id is the username as given in the URL
+ * @param bundleIdString specifies the id of the bundle to be started
+ * @return an array of installed {@link Bundle}s to be managed
+ *
+ */
+ @POST
+ @Path("start-bundle")
+ def startBundle(@PathParam(value = "id") idP: String,
+ @FormParam("bundleId") bundleIdStringP: String,
+ @Context uriInfo: UriInfo): Response = {
+ val id: String = idP
+ val bundleIdString: String = bundleIdStringP
+ AccessController.checkPermission(new AccountControlPanelAppPermission(id, ""))
+ AccessController.checkPermission(new UserBundlePermission(id, ""))
+ logger.info("Start bundle {} ", id)
+ val bundleId: Long = bundleIdString.toLong
+ AccessController.doPrivileged(new PrivilegedAction[AnyRef] {
+ def run: Array[Bundle] = {
+ try {
+ val bundle: Bundle = componentContext.getBundleContext.getBundle(bundleId)
+ bundle.start
+ }
+ catch {
+ case e: BundleException => {
+ logger.debug("Failed to start bundle {}", bundleIdString)
+ logger.error("Exception during start bundle: {}", e)
+ var responseBuilder: Response.ResponseBuilder = Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage)
+ throw new WebApplicationException(responseBuilder.build)
+ }
+ }
+ return null
+ }
+ })
+ return RedirectUtil.createSeeOtherResponse("../control-panel", uriInfo)
+ }
- /**
- * Stops the bundle with the specified bundle id.
- *
- * @param id is the username as given in the URL
- * @param bundleIdString specifies the id of the bundle to be stopped
- * @return an array of installed {@link Bundle}s to be managed
- *
- */
- @POST
- @Path("stop-bundle") def stopBundle(@PathParam(value = "id") idP: String,
- @FormParam("bundleId") bundleIdStringP: String,
- @Context uriInfo: UriInfo): Response = {
- val id: String = idP
- val bundleIdString: String = bundleIdStringP
- AccessController.checkPermission(new AccountControlPanelAppPermission(id, ""))
- AccessController.checkPermission(new UserBundlePermission(id, ""))
- logger.info("Stop bundle {}", id)
- val bundleId: Long = bundleIdString.toLong
- AccessController.doPrivileged(new PrivilegedAction[AnyRef] {
- def run: Array[Bundle] = {
- try {
- var bundle: Bundle = componentContext.getBundleContext.getBundle(bundleId)
- bundle.stop
- }
- catch {
- case e: BundleException => {
- logger.debug("Failed to stop bundle ", bundleIdString)
- logger.error("Exception during stop bundle: {}", e)
- var responseBuilder: Response.ResponseBuilder = Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage)
- throw new WebApplicationException(responseBuilder.build)
- }
- }
- return null
- }
- })
- return RedirectUtil.createSeeOtherResponse("../control-panel", uriInfo)
- }
+ /**
+ * Stops the bundle with the specified bundle id.
+ *
+ * @param id is the username as given in the URL
+ * @param bundleIdString specifies the id of the bundle to be stopped
+ * @return an array of installed {@link Bundle}s to be managed
+ *
+ */
+ @POST
+ @Path("stop-bundle") def stopBundle(@PathParam(value = "id") idP: String,
+ @FormParam("bundleId") bundleIdStringP: String,
+ @Context uriInfo: UriInfo): Response = {
+ val id: String = idP
+ val bundleIdString: String = bundleIdStringP
+ AccessController.checkPermission(new AccountControlPanelAppPermission(id, ""))
+ AccessController.checkPermission(new UserBundlePermission(id, ""))
+ logger.info("Stop bundle {}", id)
+ val bundleId: Long = bundleIdString.toLong
+ AccessController.doPrivileged(new PrivilegedAction[AnyRef] {
+ def run: Array[Bundle] = {
+ try {
+ var bundle: Bundle = componentContext.getBundleContext.getBundle(bundleId)
+ bundle.stop
+ }
+ catch {
+ case e: BundleException => {
+ logger.debug("Failed to stop bundle ", bundleIdString)
+ logger.error("Exception during stop bundle: {}", e)
+ var responseBuilder: Response.ResponseBuilder = Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage)
+ throw new WebApplicationException(responseBuilder.build)
+ }
+ }
+ return null
+ }
+ })
+ return RedirectUtil.createSeeOtherResponse("../control-panel", uriInfo)
+ }
- /**
- * Uninstalls the bundle with the specified bundle id.
- *
- * @param id is the username as given in the URL
- * @param bundleIdString specifies the id of the bundle to be uninstalled
- * @return an array of installed {@link Bundle}s to be managed
- *
- */
- @POST
- @Path("uninstall-bundle")
- def uninstallBundle(@PathParam(value = "id") idP: String,
- @FormParam("bundleId") bundleIdStringP: String,
- @Context uriInfo: UriInfo): Response = {
- val id: String = idP
- val bundleIdString: String = bundleIdStringP
- AccessController.checkPermission(new AccountControlPanelAppPermission(id, ""))
- AccessController.checkPermission(new UserBundlePermission(id, ""))
- logger.info("Uninstall bundle {}", id)
- val bundleId: Long = bundleIdString.toLong
- AccessController.doPrivileged(new PrivilegedAction[AnyRef] {
- def run: Array[Bundle] = {
- val agent: NonLiteral = getAgent(id)
- try {
- var bundle: Bundle = componentContext.getBundleContext.getBundle(bundleId)
- bundle.uninstall
- val triple: Triple = new TripleImpl(new UriRef(bundle.getLocation), OSGI.owner, agent)
- systemGraph.remove(triple)
- removeBundlePrefix(bundle)
- }
- catch {
- case e: BundleException => {
- logger.debug("Failed to uninstall bundle {}", bundleIdString)
- logger.error("Exception during uninstall bundle: {}", e)
- var responseBuilder: Response.ResponseBuilder = Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage)
- throw new WebApplicationException(responseBuilder.build)
- }
- }
- return null
- }
- })
- return RedirectUtil.createSeeOtherResponse("../control-panel", uriInfo)
- }
+ /**
+ * Uninstalls the bundle with the specified bundle id.
+ *
+ * @param id is the username as given in the URL
+ * @param bundleIdString specifies the id of the bundle to be uninstalled
+ * @return an array of installed {@link Bundle}s to be managed
+ *
+ */
+ @POST
+ @Path("uninstall-bundle")
+ def uninstallBundle(@PathParam(value = "id") idP: String,
+ @FormParam("bundleId") bundleIdStringP: String,
+ @Context uriInfo: UriInfo): Response = {
+ val id: String = idP
+ val bundleIdString: String = bundleIdStringP
+ AccessController.checkPermission(new AccountControlPanelAppPermission(id, ""))
+ AccessController.checkPermission(new UserBundlePermission(id, ""))
+ logger.info("Uninstall bundle {}", id)
+ val bundleId: Long = bundleIdString.toLong
+ AccessController.doPrivileged(new PrivilegedAction[AnyRef] {
+ def run: Array[Bundle] = {
+ val agent: NonLiteral = getAgent(id)
+ try {
+ var bundle: Bundle = componentContext.getBundleContext.getBundle(bundleId)
+ bundle.uninstall
+ val triple: Triple = new TripleImpl(new UriRef(bundle.getLocation), OSGI.owner, agent)
+ systemGraph.remove(triple)
+ removeBundlePrefix(bundle)
+ }
+ catch {
+ case e: BundleException => {
+ logger.debug("Failed to uninstall bundle {}", bundleIdString)
+ logger.error("Exception during uninstall bundle: {}", e)
+ var responseBuilder: Response.ResponseBuilder = Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage)
+ throw new WebApplicationException(responseBuilder.build)
+ }
+ }
+ return null
+ }
+ })
+ return RedirectUtil.createSeeOtherResponse("../control-panel", uriInfo)
+ }
- /**
- * changes the password of an user
- *
- * @param idP id is the username as given in the URL
- * @param lang represents the user's new standard language.
- * @return
- */
- @POST
- @Path("change-language")
- def changeUserLanguage(@PathParam(value = "id") idP: String,
- @FormParam("availablelanguages") lang: String,
- @Context uriInfo: UriInfo): Response = {
- val id: String = idP
- AccessController.checkPermission(new AccountControlPanelAppPermission(id, ""))
- AccessController.doPrivileged(new PrivilegedAction[AnyRef] {
- def run: AnyRef = {
- var userNode: GraphNode = new GraphNode(getAgent(id), systemGraph)
- userNode.deleteProperties(PLATFORM.preferredLangInISOCode)
- userNode.addProperty(PLATFORM.preferredLangInISOCode, LiteralFactory.getInstance.createTypedLiteral(lang))
- return null
- }
- })
- return RedirectUtil.createSeeOtherResponse("../control-panel", uriInfo)
- }
+ /**
+ * changes the password of an user
+ *
+ * @param idP id is the username as given in the URL
+ * @param lang represents the user's new standard language.
+ * @return
+ */
+ @POST
+ @Path("change-language")
+ def changeUserLanguage(@PathParam(value = "id") idP: String,
+ @FormParam("availablelanguages") lang: String,
+ @Context uriInfo: UriInfo): Response = {
+ val id: String = idP
+ AccessController.checkPermission(new AccountControlPanelAppPermission(id, ""))
+ AccessController.doPrivileged(new PrivilegedAction[AnyRef] {
+ def run: AnyRef = {
+ var userNode: GraphNode = new GraphNode(getAgent(id), systemGraph)
+ userNode.deleteProperties(PLATFORM.preferredLangInISOCode)
+ userNode.addProperty(PLATFORM.preferredLangInISOCode, LiteralFactory.getInstance.createTypedLiteral(lang))
+ return null
+ }
+ })
+ return RedirectUtil.createSeeOtherResponse("../control-panel", uriInfo)
+ }
- /**
- * changes the password of an user
- *
- * @param idP id is the username as given in the URL
- * @param oldPW the current user password
- * @param newPW the new password
- * @param confirmNewPW the new password
- * @return
- */
- @POST
- @Path("change-password")
- def changePassword(@PathParam(value = "id") idP: String,
- @FormParam("oldPW") oldPW: String,
- @FormParam("newPW") newPW: String,
- @FormParam("confirmNewPW") confirmNewPW: String,
- @Context uriInfo: UriInfo): Response = {
- val id: String = idP
- AccessController.checkPermission(new AccountControlPanelAppPermission(id, ""))
- AccessController.checkPermission(new ChangePasswordPermission(id, ""))
- var changedPassword: Boolean = false
- if (newPW.trim.equals(confirmNewPW.trim) && checkPWStrings(oldPW, newPW)) {
- changedPassword = AccessController.doPrivileged(new PrivilegedAction[Boolean] {
- private def getCurrentPassword(agent: NonLiteral): String = {
- var currentPassword: String = null
- var oldPWTriple: Iterator[Triple] = systemGraph.filter(agent, PERMISSION.passwordSha1, null)
- if (oldPWTriple.hasNext) {
- var currentPWLiteral: Literal = oldPWTriple.next.getObject.asInstanceOf[Literal]
- currentPassword = currentPWLiteral.getLexicalForm
- }
- return currentPassword
- }
+ /**
+ * changes the password of an user
+ *
+ * @param idP id is the username as given in the URL
+ * @param oldPW the current user password
+ * @param newPW the new password
+ * @param confirmNewPW the new password
+ * @return
+ */
+ @POST
+ @Path("change-password")
+ def changePassword(@PathParam(value = "id") idP: String,
+ @FormParam("oldPW") oldPW: String,
+ @FormParam("newPW") newPW: String,
+ @FormParam("confirmNewPW") confirmNewPW: String,
+ @Context uriInfo: UriInfo): Response = {
+ val id: String = idP
+ AccessController.checkPermission(new AccountControlPanelAppPermission(id, ""))
+ AccessController.checkPermission(new ChangePasswordPermission(id, ""))
+ var changedPassword: Boolean = false
+ if (newPW.trim.equals(confirmNewPW.trim) && checkPWStrings(oldPW, newPW)) {
+ changedPassword = AccessController.doPrivileged(new PrivilegedAction[Boolean] {
+ private def getCurrentPassword(agent: NonLiteral): String = {
+ var currentPassword: String = null
+ var oldPWTriple: Iterator[Triple] = systemGraph.filter(agent, PERMISSION.passwordSha1, null)
+ if (oldPWTriple.hasNext) {
+ var currentPWLiteral: Literal = oldPWTriple.next.getObject.asInstanceOf[Literal]
+ currentPassword = currentPWLiteral.getLexicalForm
+ }
+ return currentPassword
+ }
- def run: Boolean = {
- val agent: NonLiteral = getAgent(id)
- var encodedOlpPW: String = getEncodedPW(oldPW)
- var currentPassword: String = getCurrentPassword(agent)
- if ((currentPassword != null) && !currentPassword.equals(encodedOlpPW)) {
- logger.info("Typed wrong current password!")
- return false
- }
- else {
- removeOldPwAndAddNewPW(agent, currentPassword, newPW)
- return true
- }
- }
+ def run: Boolean = {
+ val agent: NonLiteral = getAgent(id)
+ var encodedOlpPW: String = getEncodedPW(oldPW)
+ var currentPassword: String = getCurrentPassword(agent)
+ if ((currentPassword != null) && !currentPassword.equals(encodedOlpPW)) {
+ logger.info("Typed wrong current password!")
+ return false
+ }
+ else {
+ removeOldPwAndAddNewPW(agent, currentPassword, newPW)
+ return true
+ }
+ }
- private def removeOldPwAndAddNewPW(agent: NonLiteral, currentPassword: String, newPW: String): Unit = {
- var newPWTriple: Triple = new TripleImpl(agent, PERMISSION.passwordSha1, new PlainLiteralImpl(getEncodedPW(newPW)))
- if (currentPassword != null) {
- var oldPWTriple: Triple = new TripleImpl(agent, PERMISSION.passwordSha1, new PlainLiteralImpl(currentPassword))
- systemGraph.remove(oldPWTriple)
- logger.debug("removed old password from systemgraph")
- }
- systemGraph.add(newPWTriple)
- logger.debug("user " + id + " changed password")
- }
+ private def removeOldPwAndAddNewPW(agent: NonLiteral, currentPassword: String, newPW: String): Unit = {
+ var newPWTriple: Triple = new TripleImpl(agent, PERMISSION.passwordSha1, new PlainLiteralImpl(getEncodedPW(newPW)))
+ if (currentPassword != null) {
+ var oldPWTriple: Triple = new TripleImpl(agent, PERMISSION.passwordSha1, new PlainLiteralImpl(currentPassword))
+ systemGraph.remove(oldPWTriple)
+ logger.debug("removed old password from systemgraph")
+ }
+ systemGraph.add(newPWTriple)
+ logger.debug("user " + id + " changed password")
+ }
- private def getEncodedPW(password: String): String = {
- if (password == null) {
- return null
- }
- try {
- return bytes2HexString(MessageDigest.getInstance("SHA1").digest(password.getBytes("UTF-8")))
- }
- catch {
- case e: NoSuchAlgorithmException => {
- throw new RuntimeException(e)
- }
- case e: UnsupportedEncodingException => {
- throw new RuntimeException(e)
- }
- }
- }
+ private def getEncodedPW(password: String): String = {
+ if (password == null) {
+ return null
+ }
+ try {
+ return bytes2HexString(MessageDigest.getInstance("SHA1").digest(password.getBytes("UTF-8")))
+ }
+ catch {
+ case e: NoSuchAlgorithmException => {
+ throw new RuntimeException(e)
+ }
+ case e: UnsupportedEncodingException => {
+ throw new RuntimeException(e)
+ }
+ }
+ }
- private def bytes2HexString(bytes: Array[Byte]): String = {
- val HEXDIGITS: Array[Char] = "0123456789abcdef".toCharArray
- val result = new Array[Char](bytes.length << 1)
- var j: Int = 0
- for (i <- 0 to bytes.length - 1) {
- result(j) = HEXDIGITS(bytes(i) >> 4 & 0xF)
- result(j + 1) = HEXDIGITS(bytes(i) & 0xF)
- j += 2
- }
- return new String(result)
- }
- })
- }
- else {
- logger.info("Changing password failed!")
- changedPassword = false
- }
- if (changedPassword) {
- return RedirectUtil.createSeeOtherResponse("../control-panel", uriInfo)
- }
- else {
- return RedirectUtil.createSeeOtherResponse("../control-panel?changedPassword=false", uriInfo)
- }
- }
+ private def bytes2HexString(bytes: Array[Byte]): String = {
+ val HEXDIGITS: Array[Char] = "0123456789abcdef".toCharArray
+ val result = new Array[Char](bytes.length << 1)
+ var j: Int = 0
+ for (i <- 0 to bytes.length - 1) {
+ result(j) = HEXDIGITS(bytes(i) >> 4 & 0xF)
+ result(j + 1) = HEXDIGITS(bytes(i) & 0xF)
+ j += 2
+ }
+ return new String(result)
+ }
+ })
+ }
+ else {
+ logger.info("Changing password failed!")
+ changedPassword = false
+ }
+ if (changedPassword) {
+ return RedirectUtil.createSeeOtherResponse("../control-panel", uriInfo)
+ }
+ else {
+ return RedirectUtil.createSeeOtherResponse("../control-panel?changedPassword=false", uriInfo)
+ }
+ }
- /**
- * checks if the typed strings are valid
- */
- private def checkPWStrings(oldPW: String, newPW: String): Boolean = {
- if (newPW.length == 0) {
- return false
- }
- return true
- }
+ /**
+ * checks if the typed strings are valid
+ */
+ private def checkPWStrings(oldPW: String, newPW: String): Boolean = {
+ if (newPW.length == 0) {
+ return false
+ }
+ return true
+ }
- /**
- * The activate method is called when SCR activates the component configuration.
- *
- * @param componentContext
- */
- protected def activate(componentContext: ComponentContext): Unit = {
- this.componentContext = componentContext
- }
+ /**
+ * The activate method is called when SCR activates the component configuration.
+ *
+ * @param componentContext
+ */
+ protected def activate(componentContext: ComponentContext): Unit = {
+ this.componentContext = componentContext
+ }
- protected def bindConfigurationAdmin(configAdmin: ConfigurationAdmin): Unit = {
- logger.debug("Binding configuration admin")
- this.configAdmin = configAdmin
- }
+ protected def bindConfigurationAdmin(configAdmin: ConfigurationAdmin): Unit = {
+ logger.debug("Binding configuration admin")
+ this.configAdmin = configAdmin
+ }
- protected def unbindConfigurationAdmin(configAdmin: ConfigurationAdmin): Unit = {
- logger.debug("Unbinding configuration admin")
- this.configAdmin = null
- }
+ protected def unbindConfigurationAdmin(configAdmin: ConfigurationAdmin): Unit = {
+ logger.debug("Unbinding configuration admin")
+ this.configAdmin = null
+ }
- protected def bindSystemGraph(mgraph: MGraph): Unit = {
- systemGraph = mgraph
- }
+ protected def bindSystemGraph(mgraph: MGraph): Unit = {
+ systemGraph = mgraph
+ }
- protected def unbindSystemGraph(mgraph: MGraph): Unit = {
- if (systemGraph == mgraph) {
- systemGraph = null
- }
- }
+ protected def unbindSystemGraph(mgraph: MGraph): Unit = {
+ if (systemGraph == mgraph) {
+ systemGraph = null
+ }
+ }
- protected def bindCgProvider(contentgraphprovider: ContentGraphProvider): Unit = {
- cgProvider = contentgraphprovider
- }
+ protected def bindCgProvider(contentgraphprovider: ContentGraphProvider): Unit = {
+ cgProvider = contentgraphprovider
+ }
- protected def unbindCgProvider(contentgraphprovider: ContentGraphProvider): Unit = {
- if (cgProvider == contentgraphprovider) {
- cgProvider = null
- }
- }
+ protected def unbindCgProvider(contentgraphprovider: ContentGraphProvider): Unit = {
+ if (cgProvider == contentgraphprovider) {
+ cgProvider = null
+ }
+ }
- private var componentContext: ComponentContext = null
- private var systemGraph: MGraph = null
- private var cgProvider: ContentGraphProvider = null
- private var configAdmin: ConfigurationAdmin = null
+ private var componentContext: ComponentContext = null
+ private var systemGraph: MGraph = null
+ private var cgProvider: ContentGraphProvider = null
+ private var configAdmin: ConfigurationAdmin = null
}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/platform.accountcontrolpanel/platform.accountcontrolpanel.core/src/main/scala/org/apache/clerezza/platform/accountcontrolpanel/html/ContactConfirmRenderlet.scala
----------------------------------------------------------------------
diff --git a/platform.accountcontrolpanel/platform.accountcontrolpanel.core/src/main/scala/org/apache/clerezza/platform/accountcontrolpanel/html/ContactConfirmRenderlet.scala b/platform.accountcontrolpanel/platform.accountcontrolpanel.core/src/main/scala/org/apache/clerezza/platform/accountcontrolpanel/html/ContactConfirmRenderlet.scala
index 23e7dc3..bb306aa 100644
--- a/platform.accountcontrolpanel/platform.accountcontrolpanel.core/src/main/scala/org/apache/clerezza/platform/accountcontrolpanel/html/ContactConfirmRenderlet.scala
+++ b/platform.accountcontrolpanel/platform.accountcontrolpanel.core/src/main/scala/org/apache/clerezza/platform/accountcontrolpanel/html/ContactConfirmRenderlet.scala
@@ -32,78 +32,78 @@ import org.apache.clerezza.platform.typerendering.scala._
* Metadata class for the person panel
*/
class ContactConfirmRenderlet extends SRenderlet {
- def getRdfType() = CONTROLPANEL.ContactConfirmPage
+ def getRdfType() = CONTROLPANEL.ContactConfirmPage
- override def renderedPage(arguments: XmlResult.Arguments) = new XmlPerson(arguments)
+ override def renderedPage(arguments: XmlResult.Arguments) = new XmlPerson(arguments)
- /**
- * Content class for the Person Panel
- */
- class XmlPerson(args: XmlResult.Arguments) extends XmlResult(args) {
+ /**
+ * Content class for the Person Panel
+ */
+ class XmlPerson(args: XmlResult.Arguments) extends XmlResult(args) {
- import RenderingUtility._
-
- //
- // the content itself.
- // This is the piece that is closest to a pure ssp, though there is still too much code in it
- //
+ import RenderingUtility._
+
+ //
+ // the content itself.
+ // This is the piece that is closest to a pure ssp, though there is still too much code in it
+ //
- override def content = {
- val primarySubject = res/FOAF.primaryTopic
- <div id="tx-content">
- {
- if (primarySubject.hasProperty(RDF.`type`, FOAF.Person)) {
- <form action="addContact" method="post">
- {render(primarySubject, "box-naked")}
- <input type="hidden" name="webId" value={primarySubject*} />
- <input type="submit" value="Add this contact" />
- </form>
- } else {
- <div>
- <span>The resource {primarySubject!} of type {primarySubject/RDF.`type`} is not known to be a Person</span>
- {
- import collection.JavaConversions._
- val otherPersons = (for (t <- primarySubject.getNodeContext.filter(null, RDF.`type`, FOAF.Person))
- yield t.getSubject).toList
- val personsWithUri: List[UriRef] = for (otherPerson <- otherPersons;
- if otherPerson.isInstanceOf[UriRef]) yield otherPerson.asInstanceOf[UriRef]
- if (personsWithUri.isEmpty) {
- <span>No person could be found</span>
- } else {
- <div>
- Maybe you want to add {
- if (personsWithUri.size > 1) {
- "one of the following "+personsWithUri.size+" persons:"
- } else {
- "the person"
- }
- }
- {
- for (otherPerson <- personsWithUri) yield {
- <form action="addContact" method="post">
- <span>{otherPerson}</span>
- {render(otherPerson, "box-naked")}
- <input type="hidden" name="webId" value={otherPerson.getUnicodeString} />
- <input type="submit" value="Add this contact" />
- </form>
- }
- }
- </div>
- }
- }
- {
- <form action="addContact" method="post">
- You can add {primarySubject} as contact even though it does not seem to be a person.
- <input type="hidden" name="webId" value={primarySubject*} />
- <input type="submit" value="Add anyway" />
- </form>
- } </div>
- }
- }
- <a href="../profile" onclick="history.go(-1)">Cancel</a>
- </div>
- }
+ override def content = {
+ val primarySubject = res/FOAF.primaryTopic
+ <div id="tx-content">
+ {
+ if (primarySubject.hasProperty(RDF.`type`, FOAF.Person)) {
+ <form action="addContact" method="post">
+ {render(primarySubject, "box-naked")}
+ <input type="hidden" name="webId" value={primarySubject*} />
+ <input type="submit" value="Add this contact" />
+ </form>
+ } else {
+ <div>
+ <span>The resource {primarySubject!} of type {primarySubject/RDF.`type`} is not known to be a Person</span>
+ {
+ import collection.JavaConversions._
+ val otherPersons = (for (t <- primarySubject.getNodeContext.filter(null, RDF.`type`, FOAF.Person))
+ yield t.getSubject).toList
+ val personsWithUri: List[UriRef] = for (otherPerson <- otherPersons;
+ if otherPerson.isInstanceOf[UriRef]) yield otherPerson.asInstanceOf[UriRef]
+ if (personsWithUri.isEmpty) {
+ <span>No person could be found</span>
+ } else {
+ <div>
+ Maybe you want to add {
+ if (personsWithUri.size > 1) {
+ "one of the following "+personsWithUri.size+" persons:"
+ } else {
+ "the person"
+ }
+ }
+ {
+ for (otherPerson <- personsWithUri) yield {
+ <form action="addContact" method="post">
+ <span>{otherPerson}</span>
+ {render(otherPerson, "box-naked")}
+ <input type="hidden" name="webId" value={otherPerson.getUnicodeString} />
+ <input type="submit" value="Add this contact" />
+ </form>
+ }
+ }
+ </div>
+ }
+ }
+ {
+ <form action="addContact" method="post">
+ You can add {primarySubject} as contact even though it does not seem to be a person.
+ <input type="hidden" name="webId" value={primarySubject*} />
+ <input type="submit" value="Add anyway" />
+ </form>
+ } </div>
+ }
+ }
+ <a href="../profile" onclick="history.go(-1)">Cancel</a>
+ </div>
+ }
- }
+ }
}
[3/9] CLEREZZA-435: repaced tabs with spaces in scala files
Posted by re...@apache.org.
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/rdf.scala.utils/src/main/scala/org/apache/clerezza/rdf/scala/utils/RichGraphNode.scala
----------------------------------------------------------------------
diff --git a/rdf.scala.utils/src/main/scala/org/apache/clerezza/rdf/scala/utils/RichGraphNode.scala b/rdf.scala.utils/src/main/scala/org/apache/clerezza/rdf/scala/utils/RichGraphNode.scala
index 4b10708..95f6aab 100644
--- a/rdf.scala.utils/src/main/scala/org/apache/clerezza/rdf/scala/utils/RichGraphNode.scala
+++ b/rdf.scala.utils/src/main/scala/org/apache/clerezza/rdf/scala/utils/RichGraphNode.scala
@@ -39,202 +39,202 @@ import org.apache.clerezza.rdf.utils.UnionMGraph
*/
class RichGraphNode(resource: Resource, graph: TripleCollection ) extends GraphNode(resource, graph) {
- /**
- * Construct a RichGraphNode given an existing [[GraphNde]]
- *
- * @param node The GraphNode to be wrapped
- */
- def this(node: GraphNode) = this(node.getNode, node.getGraph)
-
- /**
- * Operator syntax shortcut to get all objects as <code>RichGraphNode</code>
- *
- * @return all objects of the specified property of the node wrapped by this object
- */
- def /(property: UriRef): CollectedIter[RichGraphNode] = {
- new CollectedIter[RichGraphNode](() => new GraphNodeIter(getObjects(property)), readLock)
- }
-
- /**
- * Operator syntax shortcut to get all subjects as <code>RichGraphNode</code>ref
- *
- * @param property the property for which the subjects pointing to this node by that property are requested
- * @return the matching resources
- */
- def /-(property: UriRef): CollectedIter[RichGraphNode] = {
- new CollectedIter[RichGraphNode](() => new GraphNodeIter(getSubjects(property)), readLock)
- }
-
- /**
- * Get the elements of the rdf:List represented by this node
- * @return a List with the elements of the rdf:List represented by this node
- */
- def !! = (for (listElem <- asList) yield {
- new RichGraphNode(new GraphNode(listElem, getGraph))
- }).toList
-
- /**
- * get a specified of the rdf:List represented by this node
- *
- * @return the specified index value
- */
- def %!!(index: Int) = new RichGraphNode(new GraphNode(asList.get(index),
- getGraph))
-
- /**
- * produces a default String representation for the node, this is the lexical form of literals,
- * the unicode-string for UriRef and for BNodes the value returned by toString
- *
- * @return the default string representation of the node
- */
- def * : String = {
- getNode() match {
- case lit: Literal => lit.getLexicalForm
- case uri: UriRef => uri.getUnicodeString
- case wrappedNode => wrappedNode.toString
- }
- }
-
- private def asClass[T](clazz : Class[T]) : T= {
- val typedLiteral = getNode().asInstanceOf[TypedLiteral]
- clazz match {
- case c if(c == classOf[Boolean]) => LiteralFactory.getInstance().createObject(
- classOf[java.lang.Boolean], typedLiteral).booleanValue.asInstanceOf[T]
- case _ => LiteralFactory.getInstance().createObject(clazz, typedLiteral)
- }
- }
-
- /**
- * Creates an instance of specified Class-Type representing the value of the literal wrapped by this
- * <code>GraphNode</code>
- *
- * @return the literal represented by this node as instance of the specified type
- */
- def as[T](implicit m: Manifest[T]): T = {
- asClass(m.erasure.asInstanceOf[Class[T]])
- }
-
- /**
- * Operator syntax shortcut to get the <code>Resource</code> wrapped by this
- * <code>GraphNode</code>
- *
- * @return the node represented by this GraphNode as Resource, same as <code>getNode</code>
- */
- def ! = {
- getNode()
- }
-
- private class GraphNodeIter[T <: Resource](base: Iterator[T]) extends Iterator[RichGraphNode] {
- override def hasNext() = {
- base.hasNext();
- }
-
- override def next() : RichGraphNode = {
- new RichGraphNode(new GraphNode(base.next(), getGraph));
- }
-
- override def remove() {
- base.remove()
- }
- }
-
- /**
- *Sets the RDF:type of the subject */
- def a(rdfclass: UriRef): RichGraphNode = {
- addProperty(RDF.`type`, rdfclass)
- return this
- }
-
- /*
- * create an RichGraphNode from this one where the backing graph is protected from writes by a new
- * SimpleGraph.
- */
- def protect(): RichGraphNode = new RichGraphNode(getNode, new UnionMGraph(new SimpleMGraph(), graph))
-
-
- /**
- * relate the subject via the given relation to....
- */
- def --(rel: Resource): DashTuple = new DashTuple(rel)
-
- def --(rel: RichGraphNode): DashTuple = new DashTuple(rel.getNode)
-
-
- /**
- * relate the subject via the inverse of the given relation to....
- */
- def <--(tuple: RichGraphNode#DashTuple): RichGraphNode = {
- val inversePropertyRes = tuple.first.getNode
- val inverseProperty: UriRef = inversePropertyRes match {
- case p: UriRef => p
- case _ => throw new RuntimeException("DashTuple must be a UriRef")
- }
- RichGraphNode.this.addInverseProperty(inverseProperty, tuple.second)
- RichGraphNode.this
- }
-
-
- /** class for Inverse relations with the current RichGraphNode.ref as object */
- //TODO add support for adding many for symmetry reasons
-// class InverseDashTuple(rel: DashTuple) {
+ /**
+ * Construct a RichGraphNode given an existing [[GraphNde]]
+ *
+ * @param node The GraphNode to be wrapped
+ */
+ def this(node: GraphNode) = this(node.getNode, node.getGraph)
+
+ /**
+ * Operator syntax shortcut to get all objects as <code>RichGraphNode</code>
+ *
+ * @return all objects of the specified property of the node wrapped by this object
+ */
+ def /(property: UriRef): CollectedIter[RichGraphNode] = {
+ new CollectedIter[RichGraphNode](() => new GraphNodeIter(getObjects(property)), readLock)
+ }
+
+ /**
+ * Operator syntax shortcut to get all subjects as <code>RichGraphNode</code>ref
+ *
+ * @param property the property for which the subjects pointing to this node by that property are requested
+ * @return the matching resources
+ */
+ def /-(property: UriRef): CollectedIter[RichGraphNode] = {
+ new CollectedIter[RichGraphNode](() => new GraphNodeIter(getSubjects(property)), readLock)
+ }
+
+ /**
+ * Get the elements of the rdf:List represented by this node
+ * @return a List with the elements of the rdf:List represented by this node
+ */
+ def !! = (for (listElem <- asList) yield {
+ new RichGraphNode(new GraphNode(listElem, getGraph))
+ }).toList
+
+ /**
+ * get a specified of the rdf:List represented by this node
+ *
+ * @return the specified index value
+ */
+ def %!!(index: Int) = new RichGraphNode(new GraphNode(asList.get(index),
+ getGraph))
+
+ /**
+ * produces a default String representation for the node, this is the lexical form of literals,
+ * the unicode-string for UriRef and for BNodes the value returned by toString
+ *
+ * @return the default string representation of the node
+ */
+ def * : String = {
+ getNode() match {
+ case lit: Literal => lit.getLexicalForm
+ case uri: UriRef => uri.getUnicodeString
+ case wrappedNode => wrappedNode.toString
+ }
+ }
+
+ private def asClass[T](clazz : Class[T]) : T= {
+ val typedLiteral = getNode().asInstanceOf[TypedLiteral]
+ clazz match {
+ case c if(c == classOf[Boolean]) => LiteralFactory.getInstance().createObject(
+ classOf[java.lang.Boolean], typedLiteral).booleanValue.asInstanceOf[T]
+ case _ => LiteralFactory.getInstance().createObject(clazz, typedLiteral)
+ }
+ }
+
+ /**
+ * Creates an instance of specified Class-Type representing the value of the literal wrapped by this
+ * <code>GraphNode</code>
+ *
+ * @return the literal represented by this node as instance of the specified type
+ */
+ def as[T](implicit m: Manifest[T]): T = {
+ asClass(m.erasure.asInstanceOf[Class[T]])
+ }
+
+ /**
+ * Operator syntax shortcut to get the <code>Resource</code> wrapped by this
+ * <code>GraphNode</code>
+ *
+ * @return the node represented by this GraphNode as Resource, same as <code>getNode</code>
+ */
+ def ! = {
+ getNode()
+ }
+
+ private class GraphNodeIter[T <: Resource](base: Iterator[T]) extends Iterator[RichGraphNode] {
+ override def hasNext() = {
+ base.hasNext();
+ }
+
+ override def next() : RichGraphNode = {
+ new RichGraphNode(new GraphNode(base.next(), getGraph));
+ }
+
+ override def remove() {
+ base.remove()
+ }
+ }
+
+ /**
+ *Sets the RDF:type of the subject */
+ def a(rdfclass: UriRef): RichGraphNode = {
+ addProperty(RDF.`type`, rdfclass)
+ return this
+ }
+
+ /*
+ * create an RichGraphNode from this one where the backing graph is protected from writes by a new
+ * SimpleGraph.
+ */
+ def protect(): RichGraphNode = new RichGraphNode(getNode, new UnionMGraph(new SimpleMGraph(), graph))
+
+
+ /**
+ * relate the subject via the given relation to....
+ */
+ def --(rel: Resource): DashTuple = new DashTuple(rel)
+
+ def --(rel: RichGraphNode): DashTuple = new DashTuple(rel.getNode)
+
+
+ /**
+ * relate the subject via the inverse of the given relation to....
+ */
+ def <--(tuple: RichGraphNode#DashTuple): RichGraphNode = {
+ val inversePropertyRes = tuple.first.getNode
+ val inverseProperty: UriRef = inversePropertyRes match {
+ case p: UriRef => p
+ case _ => throw new RuntimeException("DashTuple must be a UriRef")
+ }
+ RichGraphNode.this.addInverseProperty(inverseProperty, tuple.second)
+ RichGraphNode.this
+ }
+
+
+ /** class for Inverse relations with the current RichGraphNode.ref as object */
+ //TODO add support for adding many for symmetry reasons
+// class InverseDashTuple(rel: DashTuple) {
//
-// /**
-// * ...to the following non literal
-// */
-// def --(subj: NonLiteral): RichGraphNode = {
-// RichGraphNode.this.addInverseProperty(rel, subj)
-// RichGraphNode.this
-// }
+// /**
+// * ...to the following non literal
+// */
+// def --(subj: NonLiteral): RichGraphNode = {
+// RichGraphNode.this.addInverseProperty(rel, subj)
+// RichGraphNode.this
+// }
//
-// /**
-// * ...to the following resource (given as a string)
-// */
-// def --(subj: String): RichGraphNode = --(new UriRef(subj))
+// /**
+// * ...to the following resource (given as a string)
+// */
+// def --(subj: String): RichGraphNode = --(new UriRef(subj))
//
-// /**
-// * ...to the following EzGraphNode
-// * (useful for opening a new parenthesis and specifying other things in more detail
-// */
-// def --(subj: GraphNode): RichGraphNode = {
-// --(subj.getNode.asInstanceOf[NonLiteral])
-// }
-// // since we can only have inverses from non literals (howto deal with bndoes?)
-// }
-
- /**
- * class for relations with the current RichGraphNode.ref as subject
- */
- class DashTuple(val second: Resource) {
-
- val first = RichGraphNode.this
- /**
- * ...to the following non resource
- */
- def -->(obj: Resource): RichGraphNode = {
- val property = second match {
- case u: UriRef => u;
- case _ => throw new RuntimeException("Property must be a UriRef")
- }
- RichGraphNode.this.addProperty(property, obj)
- RichGraphNode.this
- }
-
-
- /**
- * ...to the EzGraphNode, which is useful for opening a parenthesis.
- */
- def -->(sub: GraphNode): RichGraphNode = {
- //RichGraphNode.this + sub
- -->(sub.getNode)
- }
- /**
- * Add one relation for each member of the iterable collection
- */
- def -->>[T <: Resource](uris: Iterable[T]): RichGraphNode = {
- for (u <- uris) -->(u)
- RichGraphNode.this
- }
- }
+// /**
+// * ...to the following EzGraphNode
+// * (useful for opening a new parenthesis and specifying other things in more detail
+// */
+// def --(subj: GraphNode): RichGraphNode = {
+// --(subj.getNode.asInstanceOf[NonLiteral])
+// }
+// // since we can only have inverses from non literals (howto deal with bndoes?)
+// }
+
+ /**
+ * class for relations with the current RichGraphNode.ref as subject
+ */
+ class DashTuple(val second: Resource) {
+
+ val first = RichGraphNode.this
+ /**
+ * ...to the following non resource
+ */
+ def -->(obj: Resource): RichGraphNode = {
+ val property = second match {
+ case u: UriRef => u;
+ case _ => throw new RuntimeException("Property must be a UriRef")
+ }
+ RichGraphNode.this.addProperty(property, obj)
+ RichGraphNode.this
+ }
+
+
+ /**
+ * ...to the EzGraphNode, which is useful for opening a parenthesis.
+ */
+ def -->(sub: GraphNode): RichGraphNode = {
+ //RichGraphNode.this + sub
+ -->(sub.getNode)
+ }
+ /**
+ * Add one relation for each member of the iterable collection
+ */
+ def -->>[T <: Resource](uris: Iterable[T]): RichGraphNode = {
+ for (u <- uris) -->(u)
+ RichGraphNode.this
+ }
+ }
}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/rdf.scala.utils/src/test/scala/org/apache/clerezza/rdf/scala/utils/EzMGraphTest.scala
----------------------------------------------------------------------
diff --git a/rdf.scala.utils/src/test/scala/org/apache/clerezza/rdf/scala/utils/EzMGraphTest.scala b/rdf.scala.utils/src/test/scala/org/apache/clerezza/rdf/scala/utils/EzMGraphTest.scala
index b4dbe6d..946d77e 100644
--- a/rdf.scala.utils/src/test/scala/org/apache/clerezza/rdf/scala/utils/EzMGraphTest.scala
+++ b/rdf.scala.utils/src/test/scala/org/apache/clerezza/rdf/scala/utils/EzMGraphTest.scala
@@ -29,7 +29,7 @@ import org.apache.clerezza.rdf.ontologies._
*/
class EzMGraphTest {
- val bblfishModulus = """
+ val bblfishModulus = """
9D ☮ 79 ☮ BF ☮ E2 ☮ F4 ☮ 98 ☮ BC ☮ 79 ☮ 6D ☮ AB ☮ 73 ☮ E2 ☮ 8B ☮ 39 ☮ 4D ☮ B5 26 ✜ 68 ✜ 49 ✜ EE ✜ 71 ✜ 87 ✜
06 ✜ 32 ✜ C9 ✜ 9F ✜ 3F ✜ 94 ✜ E5 ✜ CB ✜ 4D ✜ B5 12 ☮ 35 ☮ 13 ☮ 69 ☮ 60 ☮ 81 ☮ 58 ☮ 79 ☮ 66 ☮ F3 ☮ 79 ☮ 20 ☮
91 ☮ 6A ☮ 3F ☮ 42 5A ✜ F6 ✜ 54 ✜ 42 ✜ 88 ✜ B2 ✜ E9 ✜ 19 ✜ 4A ✜ 79 ✜ 87 ✜ 2E ✜ 62 ✜ 44 ✜ 2D ✜ 7C 06 ☽ 78 ☽ F8
@@ -38,116 +38,116 @@ class EzMGraphTest {
☾ 56 87 ☮ 8D ☮ B8 ☮ 7C ☮ C6 ☮ FE ☮ E9 ☮ 61 ☮ 88 ☮ 08 ☮ 61 ☮ DD ☮ E3 ☮ B8 ☮ B5 ☮ 47 ♥
"""
- /**import some references in order to reduce dependencies */
-
- final val hex: UriRef = new UriRef("http://www.w3.org/ns/auth/cert#hex")
- final val identity: UriRef = new UriRef("http://www.w3.org/ns/auth/cert#identity")
- final val RSAPublicKey: UriRef = new UriRef("http://www.w3.org/ns/auth/rsa#RSAPublicKey")
- final val modulus: UriRef = new UriRef("http://www.w3.org/ns/auth/rsa#modulus")
- final val public_exponent: UriRef = new UriRef("http://www.w3.org/ns/auth/rsa#public_exponent")
-
- val henryUri: String = "http://bblfish.net/#hjs"
- val retoUri: String = "http://farewellutopia.com/reto/#me"
- val danbriUri: String = "http://danbri.org/foaf.rdf#danbri"
-
-
- private val tinyGraph: Graph = {
- val gr = new SimpleMGraph
- val reto = new BNode()
- val danny = new BNode()
- val henry = new UriRef(henryUri)
-
- gr.add(new TripleImpl(reto, RDF.`type`, FOAF.Person))
- gr.add(new TripleImpl(reto, FOAF.name, new PlainLiteralImpl("Reto Bachman-Gmür", new Language("rm"))))
- //it is difficult to remember that one needs to put a string literal if one does not want to specify a language
- gr.add(new TripleImpl(reto, FOAF.title, new TypedLiteralImpl("Mr", XSD.string)))
- gr.add(new TripleImpl(reto, FOAF.currentProject, new UriRef("http://clerezza.org/")))
- gr.add(new TripleImpl(reto, FOAF.knows, henry))
- gr.add(new TripleImpl(reto, FOAF.knows, danny))
-
- gr.add(new TripleImpl(danny, FOAF.name, new PlainLiteralImpl("Danny Ayers", new Language("en"))))
- gr.add(new TripleImpl(danny, RDF.`type`, FOAF.Person))
- gr.add(new TripleImpl(danny, FOAF.knows, henry))
- gr.add(new TripleImpl(danny, FOAF.knows, reto))
-
- gr.add(new TripleImpl(henry, FOAF.name, new TypedLiteralImpl("Henry Story", XSD.string))) //It is tricky to remember that one needs this for pure strings
- gr.add(new TripleImpl(henry, FOAF.currentProject, new UriRef("http://webid.info/")))
- gr.add(new TripleImpl(henry, RDF.`type`, FOAF.Person))
- gr.add(new TripleImpl(henry, FOAF.knows, danny))
- gr.add(new TripleImpl(henry, FOAF.knows, reto))
-
- val pk = new BNode()
- gr.add(new TripleImpl(pk, RDF.`type`, RSAPublicKey))
- gr.add(new TripleImpl(pk, identity, henry))
- gr.add(new TripleImpl(pk, modulus, LiteralFactory.getInstance().createTypedLiteral(65537)))
- gr.add(new TripleImpl(pk, public_exponent, new TypedLiteralImpl(bblfishModulus, hex)))
- gr.getGraph
- }
-
-
- @Test
- def singleTriple {
- val expected = {
- val s = new SimpleMGraph
- s.add(new TripleImpl(henryUri.uri, FOAF.knows, retoUri.uri))
- s.getGraph
- }
- val ez = new EzMGraph() {
- henryUri.uri -- FOAF.knows --> retoUri.uri
- }
- Assert.assertEquals("The two graphs should be equals", expected, ez.getGraph)
- }
-
- @Test
- def inverseTriple {
- val expected = {
- val s = new SimpleMGraph
- s.add(new TripleImpl(retoUri.uri, FOAF.knows, henryUri.uri))
- s.getGraph
- }
- val ez = new EzMGraph() {
- henryUri.uri <-- FOAF.knows -- retoUri.uri
- }
- Assert.assertEquals("The two graphs should be equals", expected, ez.getGraph)
- }
-
- @Test
- def usingAsciiArrows {
- val ez = new EzMGraph() {(
- b_("reto").a(FOAF.Person) -- FOAF.name --> "Reto Bachman-Gmür".lang("rm")
- -- FOAF.title --> "Mr"
- -- FOAF.currentProject --> "http://clerezza.org/".uri
- -- FOAF.knows --> (
- "http://bblfish.net/#hjs".uri.a(FOAF.Person)
- -- FOAF.name --> "Henry Story"
- -- FOAF.currentProject --> "http://webid.info/".uri
- -- FOAF.knows -->> List(b_("reto"), b_("danny"))
- //one need to list properties before inverse properties, or use brackets
- <-- identity -- (
- bnode.a(RSAPublicKey) //. notation because of precedence of operators
- -- modulus --> 65537
- -- public_exponent --> (bblfishModulus^^hex) // brackets needed due to precedence
- )
- )
- -- FOAF.knows --> (
- b_("danny").a(FOAF.Person)
- -- FOAF.name --> "Danny Ayers".lang("en")
- -- FOAF.knows --> "http://bblfish.net/#hjs".uri //knows
- -- FOAF.knows --> b_("reto")
- )
- )}
- Assert.assertEquals("the two graphs should be of same size",tinyGraph.size,ez.size)
- Assert.assertEquals("Both graphs should contain exactly the same triples",tinyGraph,ez.getGraph)
- //We can add triples by creating a new anonymous instance
- new EzMGraph(ez) {(
- "http://bblfish.net/#hjs".uri -- FOAF.name --> "William"
- -- FOAF.name --> "Bill"
- )}
- Assert.assertEquals("the triple colletion has grown by one",tinyGraph.size()+2,ez.size)
- //or by just importing it
- import ez._
- ez.b_("danny") -- FOAF.name --> "George"
- Assert.assertEquals("the triple colletion has grown by one",tinyGraph.size()+3,ez.size)
- }
+ /**import some references in order to reduce dependencies */
+
+ final val hex: UriRef = new UriRef("http://www.w3.org/ns/auth/cert#hex")
+ final val identity: UriRef = new UriRef("http://www.w3.org/ns/auth/cert#identity")
+ final val RSAPublicKey: UriRef = new UriRef("http://www.w3.org/ns/auth/rsa#RSAPublicKey")
+ final val modulus: UriRef = new UriRef("http://www.w3.org/ns/auth/rsa#modulus")
+ final val public_exponent: UriRef = new UriRef("http://www.w3.org/ns/auth/rsa#public_exponent")
+
+ val henryUri: String = "http://bblfish.net/#hjs"
+ val retoUri: String = "http://farewellutopia.com/reto/#me"
+ val danbriUri: String = "http://danbri.org/foaf.rdf#danbri"
+
+
+ private val tinyGraph: Graph = {
+ val gr = new SimpleMGraph
+ val reto = new BNode()
+ val danny = new BNode()
+ val henry = new UriRef(henryUri)
+
+ gr.add(new TripleImpl(reto, RDF.`type`, FOAF.Person))
+ gr.add(new TripleImpl(reto, FOAF.name, new PlainLiteralImpl("Reto Bachman-Gmür", new Language("rm"))))
+ //it is difficult to remember that one needs to put a string literal if one does not want to specify a language
+ gr.add(new TripleImpl(reto, FOAF.title, new TypedLiteralImpl("Mr", XSD.string)))
+ gr.add(new TripleImpl(reto, FOAF.currentProject, new UriRef("http://clerezza.org/")))
+ gr.add(new TripleImpl(reto, FOAF.knows, henry))
+ gr.add(new TripleImpl(reto, FOAF.knows, danny))
+
+ gr.add(new TripleImpl(danny, FOAF.name, new PlainLiteralImpl("Danny Ayers", new Language("en"))))
+ gr.add(new TripleImpl(danny, RDF.`type`, FOAF.Person))
+ gr.add(new TripleImpl(danny, FOAF.knows, henry))
+ gr.add(new TripleImpl(danny, FOAF.knows, reto))
+
+ gr.add(new TripleImpl(henry, FOAF.name, new TypedLiteralImpl("Henry Story", XSD.string))) //It is tricky to remember that one needs this for pure strings
+ gr.add(new TripleImpl(henry, FOAF.currentProject, new UriRef("http://webid.info/")))
+ gr.add(new TripleImpl(henry, RDF.`type`, FOAF.Person))
+ gr.add(new TripleImpl(henry, FOAF.knows, danny))
+ gr.add(new TripleImpl(henry, FOAF.knows, reto))
+
+ val pk = new BNode()
+ gr.add(new TripleImpl(pk, RDF.`type`, RSAPublicKey))
+ gr.add(new TripleImpl(pk, identity, henry))
+ gr.add(new TripleImpl(pk, modulus, LiteralFactory.getInstance().createTypedLiteral(65537)))
+ gr.add(new TripleImpl(pk, public_exponent, new TypedLiteralImpl(bblfishModulus, hex)))
+ gr.getGraph
+ }
+
+
+ @Test
+ def singleTriple {
+ val expected = {
+ val s = new SimpleMGraph
+ s.add(new TripleImpl(henryUri.uri, FOAF.knows, retoUri.uri))
+ s.getGraph
+ }
+ val ez = new EzMGraph() {
+ henryUri.uri -- FOAF.knows --> retoUri.uri
+ }
+ Assert.assertEquals("The two graphs should be equals", expected, ez.getGraph)
+ }
+
+ @Test
+ def inverseTriple {
+ val expected = {
+ val s = new SimpleMGraph
+ s.add(new TripleImpl(retoUri.uri, FOAF.knows, henryUri.uri))
+ s.getGraph
+ }
+ val ez = new EzMGraph() {
+ henryUri.uri <-- FOAF.knows -- retoUri.uri
+ }
+ Assert.assertEquals("The two graphs should be equals", expected, ez.getGraph)
+ }
+
+ @Test
+ def usingAsciiArrows {
+ val ez = new EzMGraph() {(
+ b_("reto").a(FOAF.Person) -- FOAF.name --> "Reto Bachman-Gmür".lang("rm")
+ -- FOAF.title --> "Mr"
+ -- FOAF.currentProject --> "http://clerezza.org/".uri
+ -- FOAF.knows --> (
+ "http://bblfish.net/#hjs".uri.a(FOAF.Person)
+ -- FOAF.name --> "Henry Story"
+ -- FOAF.currentProject --> "http://webid.info/".uri
+ -- FOAF.knows -->> List(b_("reto"), b_("danny"))
+ //one need to list properties before inverse properties, or use brackets
+ <-- identity -- (
+ bnode.a(RSAPublicKey) //. notation because of precedence of operators
+ -- modulus --> 65537
+ -- public_exponent --> (bblfishModulus^^hex) // brackets needed due to precedence
+ )
+ )
+ -- FOAF.knows --> (
+ b_("danny").a(FOAF.Person)
+ -- FOAF.name --> "Danny Ayers".lang("en")
+ -- FOAF.knows --> "http://bblfish.net/#hjs".uri //knows
+ -- FOAF.knows --> b_("reto")
+ )
+ )}
+ Assert.assertEquals("the two graphs should be of same size",tinyGraph.size,ez.size)
+ Assert.assertEquals("Both graphs should contain exactly the same triples",tinyGraph,ez.getGraph)
+ //We can add triples by creating a new anonymous instance
+ new EzMGraph(ez) {(
+ "http://bblfish.net/#hjs".uri -- FOAF.name --> "William"
+ -- FOAF.name --> "Bill"
+ )}
+ Assert.assertEquals("the triple colletion has grown by one",tinyGraph.size()+2,ez.size)
+ //or by just importing it
+ import ez._
+ ez.b_("danny") -- FOAF.name --> "George"
+ Assert.assertEquals("the triple colletion has grown by one",tinyGraph.size()+3,ez.size)
+ }
}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/rdf.scala.utils/src/test/scala/org/apache/clerezza/rdf/scala/utils/RichGraphNodeTest.scala
----------------------------------------------------------------------
diff --git a/rdf.scala.utils/src/test/scala/org/apache/clerezza/rdf/scala/utils/RichGraphNodeTest.scala b/rdf.scala.utils/src/test/scala/org/apache/clerezza/rdf/scala/utils/RichGraphNodeTest.scala
index 0f507ed..0131691 100644
--- a/rdf.scala.utils/src/test/scala/org/apache/clerezza/rdf/scala/utils/RichGraphNodeTest.scala
+++ b/rdf.scala.utils/src/test/scala/org/apache/clerezza/rdf/scala/utils/RichGraphNodeTest.scala
@@ -27,139 +27,139 @@ import Preamble._
class RichGraphNodeTest {
- private val johnUri = new UriRef("http://example.org/john")
- private val susanneUri = new UriRef("http://example.org/susanne")
- private val listUri = new UriRef("http://example.org/list")
- private val greetingsUri = new UriRef("http://example.org/greetings")
- private val billBNode = new BNode()
- private var node : RichGraphNode = null;
- private var mGraph = new SimpleMGraph()
-
- @Before
- def prepare() = {
- mGraph.add(new TripleImpl(johnUri, FOAF.name, new PlainLiteralImpl("John")));
- mGraph.add(new TripleImpl(johnUri, FOAF.nick, new PlainLiteralImpl("johny")));
- mGraph.add(new TripleImpl(johnUri, FOAF.name, new PlainLiteralImpl("Johnathan Guller")));
- mGraph.add(new TripleImpl(johnUri, FOAF.knows, billBNode))
- mGraph.add(new TripleImpl(johnUri, RDF.`type`, FOAF.Person));
- mGraph.add(new TripleImpl(billBNode, FOAF.nick, new PlainLiteralImpl("Bill")));
- mGraph.add(new TripleImpl(billBNode, FOAF.name, new PlainLiteralImpl("William")));
- mGraph.add(new TripleImpl(billBNode, RDF.`type`, FOAF.Person));
- mGraph.add(new TripleImpl(susanneUri, FOAF.knows, johnUri));
- mGraph.add(new TripleImpl(susanneUri, FOAF.name, new PlainLiteralImpl("Susanne")));
- mGraph.add(new TripleImpl(susanneUri, RDF.`type`, FOAF.Person));
- val rdfList = new RdfList(listUri, mGraph);
- rdfList.add(johnUri)
- rdfList.add(new PlainLiteralImpl("foo"))
- rdfList.add(new PlainLiteralImpl("bar"))
- mGraph.add(new TripleImpl(johnUri, SKOS.related, listUri))
- val litEn = new PlainLiteralImpl("hello",
- new Language("en"))
- val litFr = new PlainLiteralImpl("satul",
- new Language("fr"))
- mGraph.add(new TripleImpl(greetingsUri, RDF.value, litEn))
- mGraph.add(new TripleImpl(greetingsUri, RDF.value, litFr))
- node = new GraphNode(johnUri, mGraph)
- }
-
- @Test
- def testBaseGraph {
- val preamble = new Preamble(mGraph)
- import preamble._
- def asGn(gn: GraphNode) = gn
- val johnUriNode = asGn(johnUri)
- Assert.assertEquals(johnUriNode, node)
- }
-
- @Test
- def testSlash = {
- val rNode = new RichGraphNode(node)
- Assert.assertEquals(new PlainLiteralImpl("johny"), (rNode/FOAF.nick)(0).getNode)
- Assert.assertEquals(2, (rNode/FOAF.name).length(20))
- val stringNames = (for(name <- (rNode/FOAF.name).iterator) yield {
- name.toString
- }).toList
- Assert.assertTrue(stringNames.contains("\"Johnathan Guller\""))
- Assert.assertTrue(stringNames.contains("\"John\""))
- }
-
- @Test
- def testIterate = {
- val simple: MGraph = new SimpleMGraph();
- val node = new GraphNode(new BNode(), simple);
- node.addProperty(DCTERMS.provenance, new UriRef("http://example.org/foo"));
- node.addProperty(DCTERMS.language, new UriRef("http://www.bluewin.ch/"));
- simple.add(new TripleImpl(new UriRef("http://www.bluewin.ch/"),RDF.`type`, RDFS.Container));
- node.addProperty(RDF.`type`, PLATFORM.HeadedPage);
- node.addProperty(RDF.`type`, RDFS.Class);
- val test: CollectedIter[RichGraphNode] = node/DCTERMS.language/RDF.`type`;
- Assert.assertEquals(1, test.length)
- var counter = 0;
- for(k <- test) { counter = counter + 1 }
- Assert.assertEquals(1, counter)
- }
-
- @Test
- def testInverse = {
- val rNode = new RichGraphNode(node)
- Assert.assertEquals(1, (rNode/-FOAF.knows).length)
- }
-
- @Test
- def testMissingProperty = {
- val rNode = new RichGraphNode(node)
- Assert.assertEquals(0, (rNode/FOAF.thumbnail).length)
- Assert.assertEquals("", rNode/FOAF.thumbnail*)
-
- }
-
- @Test
- def testInverseImplicit = {
- Assert.assertEquals(1, (node/-FOAF.knows).length)
- }
-
- @Test
- def testPath = {
- Assert.assertEquals(1, (node/-FOAF.knows).length)
- Assert.assertEquals(new PlainLiteralImpl("Susanne"), node/-FOAF.knows%0/FOAF.name%0!)
- Assert.assertEquals(new PlainLiteralImpl("Susanne"), ((node/-FOAF.knows)(0)/FOAF.name)(0)!)
- Assert.assertEquals(new PlainLiteralImpl("Susanne"), node/-FOAF.knows/FOAF.name!)
- Assert.assertEquals(new PlainLiteralImpl("Bill"), node/FOAF.knows/FOAF.nick!)
- Assert.assertEquals("Bill", (node/FOAF.knows/FOAF.nick)(0)*)
- Assert.assertEquals("Bill", node/FOAF.knows/FOAF.nick*)
- }
-
- @Test
- def testLists = {
- Assert.assertEquals(new PlainLiteralImpl("foo"),(node/SKOS.related).asList().get(1))
- Assert.assertEquals(new PlainLiteralImpl("foo"), (node/SKOS.related%0!!)(1)!)
- Assert.assertEquals(new PlainLiteralImpl("foo"),
- (for (value <- node/SKOS.related%0!!) yield value!).toList(1))
- Assert.assertEquals(new PlainLiteralImpl("bar"),
- (for (value <- node/SKOS.related%0!!) yield value!).toList(2))
- Assert.assertEquals(new PlainLiteralImpl("foo"), node/SKOS.related%0%!!1!)
- }
-
- @Test
- def sortProperties = {
- Assert.assertEquals(new PlainLiteralImpl("bar"), (node/SKOS.related%0!!).sortWith((a,b) => ((a*) < (b*)))(0)!)
- Assert.assertEquals(johnUri, (node/SKOS.related%0!!).sortWith((a,b) => ((a*) > (b*)))(0)!)
- }
-
- @Test
- def literalAsObject = {
- val dateLiteral = new TypedLiteralImpl("2009-01-01T01:33:58Z",
- new UriRef("http://www.w3.org/2001/XMLSchema#dateTime"))
- val node = new GraphNode(dateLiteral, new SimpleMGraph())
- Assert.assertNotNull(node.as[java.util.Date])
- }
-
- @Test
- def literalLanguage = {
- node = new GraphNode(greetingsUri, mGraph)
- val lang = new Language("en")
- val enValue = (node/RDF.value).find(l=>(l!).asInstanceOf[PlainLiteral].getLanguage == lang).get
- Assert.assertEquals("hello", enValue*)
- }
+ private val johnUri = new UriRef("http://example.org/john")
+ private val susanneUri = new UriRef("http://example.org/susanne")
+ private val listUri = new UriRef("http://example.org/list")
+ private val greetingsUri = new UriRef("http://example.org/greetings")
+ private val billBNode = new BNode()
+ private var node : RichGraphNode = null;
+ private var mGraph = new SimpleMGraph()
+
+ @Before
+ def prepare() = {
+ mGraph.add(new TripleImpl(johnUri, FOAF.name, new PlainLiteralImpl("John")));
+ mGraph.add(new TripleImpl(johnUri, FOAF.nick, new PlainLiteralImpl("johny")));
+ mGraph.add(new TripleImpl(johnUri, FOAF.name, new PlainLiteralImpl("Johnathan Guller")));
+ mGraph.add(new TripleImpl(johnUri, FOAF.knows, billBNode))
+ mGraph.add(new TripleImpl(johnUri, RDF.`type`, FOAF.Person));
+ mGraph.add(new TripleImpl(billBNode, FOAF.nick, new PlainLiteralImpl("Bill")));
+ mGraph.add(new TripleImpl(billBNode, FOAF.name, new PlainLiteralImpl("William")));
+ mGraph.add(new TripleImpl(billBNode, RDF.`type`, FOAF.Person));
+ mGraph.add(new TripleImpl(susanneUri, FOAF.knows, johnUri));
+ mGraph.add(new TripleImpl(susanneUri, FOAF.name, new PlainLiteralImpl("Susanne")));
+ mGraph.add(new TripleImpl(susanneUri, RDF.`type`, FOAF.Person));
+ val rdfList = new RdfList(listUri, mGraph);
+ rdfList.add(johnUri)
+ rdfList.add(new PlainLiteralImpl("foo"))
+ rdfList.add(new PlainLiteralImpl("bar"))
+ mGraph.add(new TripleImpl(johnUri, SKOS.related, listUri))
+ val litEn = new PlainLiteralImpl("hello",
+ new Language("en"))
+ val litFr = new PlainLiteralImpl("satul",
+ new Language("fr"))
+ mGraph.add(new TripleImpl(greetingsUri, RDF.value, litEn))
+ mGraph.add(new TripleImpl(greetingsUri, RDF.value, litFr))
+ node = new GraphNode(johnUri, mGraph)
+ }
+
+ @Test
+ def testBaseGraph {
+ val preamble = new Preamble(mGraph)
+ import preamble._
+ def asGn(gn: GraphNode) = gn
+ val johnUriNode = asGn(johnUri)
+ Assert.assertEquals(johnUriNode, node)
+ }
+
+ @Test
+ def testSlash = {
+ val rNode = new RichGraphNode(node)
+ Assert.assertEquals(new PlainLiteralImpl("johny"), (rNode/FOAF.nick)(0).getNode)
+ Assert.assertEquals(2, (rNode/FOAF.name).length(20))
+ val stringNames = (for(name <- (rNode/FOAF.name).iterator) yield {
+ name.toString
+ }).toList
+ Assert.assertTrue(stringNames.contains("\"Johnathan Guller\""))
+ Assert.assertTrue(stringNames.contains("\"John\""))
+ }
+
+ @Test
+ def testIterate = {
+ val simple: MGraph = new SimpleMGraph();
+ val node = new GraphNode(new BNode(), simple);
+ node.addProperty(DCTERMS.provenance, new UriRef("http://example.org/foo"));
+ node.addProperty(DCTERMS.language, new UriRef("http://www.bluewin.ch/"));
+ simple.add(new TripleImpl(new UriRef("http://www.bluewin.ch/"),RDF.`type`, RDFS.Container));
+ node.addProperty(RDF.`type`, PLATFORM.HeadedPage);
+ node.addProperty(RDF.`type`, RDFS.Class);
+ val test: CollectedIter[RichGraphNode] = node/DCTERMS.language/RDF.`type`;
+ Assert.assertEquals(1, test.length)
+ var counter = 0;
+ for(k <- test) { counter = counter + 1 }
+ Assert.assertEquals(1, counter)
+ }
+
+ @Test
+ def testInverse = {
+ val rNode = new RichGraphNode(node)
+ Assert.assertEquals(1, (rNode/-FOAF.knows).length)
+ }
+
+ @Test
+ def testMissingProperty = {
+ val rNode = new RichGraphNode(node)
+ Assert.assertEquals(0, (rNode/FOAF.thumbnail).length)
+ Assert.assertEquals("", rNode/FOAF.thumbnail*)
+
+ }
+
+ @Test
+ def testInverseImplicit = {
+ Assert.assertEquals(1, (node/-FOAF.knows).length)
+ }
+
+ @Test
+ def testPath = {
+ Assert.assertEquals(1, (node/-FOAF.knows).length)
+ Assert.assertEquals(new PlainLiteralImpl("Susanne"), node/-FOAF.knows%0/FOAF.name%0!)
+ Assert.assertEquals(new PlainLiteralImpl("Susanne"), ((node/-FOAF.knows)(0)/FOAF.name)(0)!)
+ Assert.assertEquals(new PlainLiteralImpl("Susanne"), node/-FOAF.knows/FOAF.name!)
+ Assert.assertEquals(new PlainLiteralImpl("Bill"), node/FOAF.knows/FOAF.nick!)
+ Assert.assertEquals("Bill", (node/FOAF.knows/FOAF.nick)(0)*)
+ Assert.assertEquals("Bill", node/FOAF.knows/FOAF.nick*)
+ }
+
+ @Test
+ def testLists = {
+ Assert.assertEquals(new PlainLiteralImpl("foo"),(node/SKOS.related).asList().get(1))
+ Assert.assertEquals(new PlainLiteralImpl("foo"), (node/SKOS.related%0!!)(1)!)
+ Assert.assertEquals(new PlainLiteralImpl("foo"),
+ (for (value <- node/SKOS.related%0!!) yield value!).toList(1))
+ Assert.assertEquals(new PlainLiteralImpl("bar"),
+ (for (value <- node/SKOS.related%0!!) yield value!).toList(2))
+ Assert.assertEquals(new PlainLiteralImpl("foo"), node/SKOS.related%0%!!1!)
+ }
+
+ @Test
+ def sortProperties = {
+ Assert.assertEquals(new PlainLiteralImpl("bar"), (node/SKOS.related%0!!).sortWith((a,b) => ((a*) < (b*)))(0)!)
+ Assert.assertEquals(johnUri, (node/SKOS.related%0!!).sortWith((a,b) => ((a*) > (b*)))(0)!)
+ }
+
+ @Test
+ def literalAsObject = {
+ val dateLiteral = new TypedLiteralImpl("2009-01-01T01:33:58Z",
+ new UriRef("http://www.w3.org/2001/XMLSchema#dateTime"))
+ val node = new GraphNode(dateLiteral, new SimpleMGraph())
+ Assert.assertNotNull(node.as[java.util.Date])
+ }
+
+ @Test
+ def literalLanguage = {
+ node = new GraphNode(greetingsUri, mGraph)
+ val lang = new Language("en")
+ val enValue = (node/RDF.value).find(l=>(l!).asInstanceOf[PlainLiteral].getLanguage == lang).get
+ Assert.assertEquals("hello", enValue*)
+ }
}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/rdf.scala.utils/src/test/scala/org/apache/clerezza/rdf/scala/utils/TypeConversionTest.scala
----------------------------------------------------------------------
diff --git a/rdf.scala.utils/src/test/scala/org/apache/clerezza/rdf/scala/utils/TypeConversionTest.scala b/rdf.scala.utils/src/test/scala/org/apache/clerezza/rdf/scala/utils/TypeConversionTest.scala
index aa86c35..6190d4e 100644
--- a/rdf.scala.utils/src/test/scala/org/apache/clerezza/rdf/scala/utils/TypeConversionTest.scala
+++ b/rdf.scala.utils/src/test/scala/org/apache/clerezza/rdf/scala/utils/TypeConversionTest.scala
@@ -25,47 +25,47 @@ import com.sun.xml.internal.ws.developer.MemberSubmissionAddressing.Validation
class TypeConversionTest {
- private val literalFactory = LiteralFactory.getInstance()
+ private val literalFactory = LiteralFactory.getInstance()
- import Preamble._
+ import Preamble._
- @Test
- def useStringAsObject {
- val t = new TripleImpl(new UriRef(("http://example.org/subject")), new UriRef(("http://example.org/predicate")), "a value")
- Assert.assertEquals(literalFactory.createTypedLiteral("a value"), t.getObject)
- }
+ @Test
+ def useStringAsObject {
+ val t = new TripleImpl(new UriRef(("http://example.org/subject")), new UriRef(("http://example.org/predicate")), "a value")
+ Assert.assertEquals(literalFactory.createTypedLiteral("a value"), t.getObject)
+ }
- /*@Test
- def useStringWithLanguageTag {
- val t = new TripleImpl(new UriRef(("http://example.org/subject")), new UriRef(("http://example.org/predicate")), "a value"("en"))
- Assert.assertEquals(new PlainLiteralImpl("a value", new Language("en")), t.getObject)
- }*/
+ /*@Test
+ def useStringWithLanguageTag {
+ val t = new TripleImpl(new UriRef(("http://example.org/subject")), new UriRef(("http://example.org/predicate")), "a value"("en"))
+ Assert.assertEquals(new PlainLiteralImpl("a value", new Language("en")), t.getObject)
+ }*/
- @Test
- def useStringWithLanguageTag {
- val lit = new PlainLiteralImpl("a value", new Language("en"))
- val t = new TripleImpl(new UriRef(("http://example.org/subject")), new UriRef(("http://example.org/predicate")), "a value" lang "en")
- Assert.assertEquals(lit, t.getObject)
- }
+ @Test
+ def useStringWithLanguageTag {
+ val lit = new PlainLiteralImpl("a value", new Language("en"))
+ val t = new TripleImpl(new UriRef(("http://example.org/subject")), new UriRef(("http://example.org/predicate")), "a value" lang "en")
+ Assert.assertEquals(lit, t.getObject)
+ }
- @Test
- def useStringWithType {
- val typeUri = new UriRef("http://example.org/dt")
- val t = new TripleImpl(new UriRef(("http://example.org/subject")), new UriRef(("http://example.org/predicate")), "a value"^^typeUri)
- Assert.assertEquals(new TypedLiteralImpl("a value", typeUri), t.getObject)
- }
+ @Test
+ def useStringWithType {
+ val typeUri = new UriRef("http://example.org/dt")
+ val t = new TripleImpl(new UriRef(("http://example.org/subject")), new UriRef(("http://example.org/predicate")), "a value"^^typeUri)
+ Assert.assertEquals(new TypedLiteralImpl("a value", typeUri), t.getObject)
+ }
- @Test
- def literaToString {
- val lit = literalFactory.createTypedLiteral("a value")
- val s: String = lit
- Assert.assertEquals("a value", s)
- }
+ @Test
+ def literaToString {
+ val lit = literalFactory.createTypedLiteral("a value")
+ val s: String = lit
+ Assert.assertEquals("a value", s)
+ }
- @Test
- def dotUri {
- val t = new TripleImpl(new UriRef(("http://example.org/subject")), new UriRef(("http://example.org/predicate")), "http://example.org".uri)
- Assert.assertEquals(new UriRef("http://example.org"), t.getObject)
- }
+ @Test
+ def dotUri {
+ val t = new TripleImpl(new UriRef(("http://example.org/subject")), new UriRef(("http://example.org/predicate")), "http://example.org".uri)
+ Assert.assertEquals(new UriRef("http://example.org"), t.getObject)
+ }
}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/rdf.storage.web/src/main/scala/WebProxy.scala
----------------------------------------------------------------------
diff --git a/rdf.storage.web/src/main/scala/WebProxy.scala b/rdf.storage.web/src/main/scala/WebProxy.scala
index 08ac5a9..c482dd2 100644
--- a/rdf.storage.web/src/main/scala/WebProxy.scala
+++ b/rdf.storage.web/src/main/scala/WebProxy.scala
@@ -40,229 +40,229 @@ import java.sql.Time
*/
class WebProxy extends WeightedTcProvider with Logging {
- val networkTimeoutKey = "network-timeout"
-
- private var networkTimeout: Int = _
-
- private var tcProvider: TcProviderMultiplexer = new TcProviderMultiplexer
-
- /**
- * Register a provider
- *
- * @param provider
- * the provider to be registered
- */
- protected def bindWeightedTcProvider(provider: WeightedTcProvider): Unit = {
- tcProvider.addWeightedTcProvider(provider)
- }
-
- /**
- * Deregister a provider
- *
- * @param provider
- * the provider to be deregistered
- */
- protected def unbindWeightedTcProvider(provider: WeightedTcProvider): Unit = {
- tcProvider.removeWeightedTcProvider(provider)
- }
-
- /**OSGI method, called on activation */
- protected def activate(context: ComponentContext) = {
- networkTimeout = Integer.parseInt(context.getProperties.get(networkTimeoutKey).toString)
- }
-
-
- private var parser: Parser = null
-
- protected def bindParser(p: Parser) = {
- parser = p
- }
-
- protected def unbindParser(p: Parser) = {
- parser = null
- }
-
- def getWeight: Int = {
- return 0
- }
-
- /**
- * Any TripleCollection is available as Graph as well as immutable MGraph
- *
- * @param name
- * @return
- * @throws NoSuchEntityException
- */
- def getMGraph(name: UriRef): MGraph = {
- val graph = getGraph(name)
- return new AbstractMGraph() {
- protected def performFilter(subject: NonLiteral, predicate: UriRef, `object` : Resource): java.util.Iterator[Triple] = {
- graph.filter(subject, predicate, `object`)
- }
-
- def size = graph.size
- }
- }
-
- def getGraph(name: UriRef): Graph = {
- try {
- getGraph(name, Cache.Fetch)
- } catch {
- case e: IOException => {
- logger.debug("could not get graph by dereferencing uri", e)
- throw new NoSuchEntityException(name)
- }
-
- }
- }
-
- def getTriples(name: UriRef): TripleCollection = {
- return getMGraph(name)
- }
-
- def createMGraph(name: UriRef): MGraph = {
- throw new UnsupportedOperationException
- }
-
- def createGraph(name: UriRef, triples: TripleCollection): Graph = {
- throw new UnsupportedOperationException
- }
-
- def deleteTripleCollection(name: UriRef): Unit = {
- throw new UnsupportedOperationException
- }
-
- def getNames(graph: Graph): java.util.Set[UriRef] = {
- var result: java.util.Set[UriRef] = new java.util.HashSet[UriRef]
- import collection.JavaConversions._
- for (name <- listGraphs) {
- if (getGraph(name).equals(graph)) {
- result.add(name)
- }
- }
- return result
- }
-
- def listTripleCollections: java.util.Set[UriRef] = {
- var result: java.util.Set[UriRef] = new java.util.HashSet[UriRef]
- result.addAll(listGraphs)
- result.addAll(listMGraphs)
- return result
- }
-
- def listGraphs: java.util.Set[UriRef] = {
- //or should we list graphs for which we have a cached version?
- return java.util.Collections.emptySet[UriRef]
- }
-
- def listMGraphs: java.util.Set[UriRef] = {
- return java.util.Collections.emptySet[UriRef]
- }
-
- /**
- * The semantics of this resource
- * @param update if a remote URI, update information on the resource first
- */
- def getGraph(name: UriRef, updatePolicy: Cache.Value): Graph = {
- logger.debug("getting graph " + name)
- if (name.getUnicodeString.indexOf('#') != -1) {
- logger.debug("not dereferencing URI with hash sign. Please see CLEREZZA-533 for debate.")
- throw new NoSuchEntityException(name)
- }
- if (name.getUnicodeString.startsWith("urn")) {
- //these are not dereferenceable
- throw new NoSuchEntityException(name)
- }
- val cacheGraphName = new UriRef("urn:x-localinstance:/cache/" + name.getUnicodeString)
- //todo: follow redirects and keep track of them
- //todo: keep track of headers especially date and etag. test for etag similarity
- //todo: for https connection allow user to specify his webid and send his key: ie allow web server to be an agent
- //todo: add GRDDL functionality, so that other return types can be processed too
- //todo: enable ftp and other formats (though content negotiation won't work there)
- def updateGraph() {
- val url = new URL(name.getUnicodeString)
- val connection = url.openConnection()
- connection match {
- case hc: HttpURLConnection => {
- hc.addRequestProperty("Accept", acceptHeader)
- hc.setReadTimeout(networkTimeout)
- hc.setConnectTimeout(networkTimeout)
- };
- }
- connection.connect()
- val in = connection.getInputStream()
- val mediaType = connection.getContentType()
- val remoteTriples = parser.parse(in, mediaType, name)
- tcProvider.synchronized {
- try {
- tcProvider.deleteTripleCollection(cacheGraphName)
- } catch {
- case e: NoSuchEntityException =>;
- }
- tcProvider.createGraph(cacheGraphName, remoteTriples)
- }
- }
- try {
- //the logic here is not quite right, as we don't look at time of previous fetch.
- updatePolicy match {
- case Cache.Fetch => try {
- tcProvider.getGraph(cacheGraphName)
- } catch {
- case e: NoSuchEntityException => updateGraph(); tcProvider.getGraph(cacheGraphName)
- }
- case Cache.ForceUpdate => updateGraph(); tcProvider.getGraph(cacheGraphName)
- case Cache.CacheOnly => tcProvider.getGraph(cacheGraphName)
- }
- } catch {
- case ex: PrivilegedActionException => {
- var cause: Throwable = ex.getCause
- if (cause.isInstanceOf[UnsupportedOperationException]) {
- throw cause.asInstanceOf[UnsupportedOperationException]
- }
- if (cause.isInstanceOf[EntityAlreadyExistsException]) {
- throw cause.asInstanceOf[EntityAlreadyExistsException]
- }
- if (cause.isInstanceOf[RuntimeException]) {
- throw cause.asInstanceOf[RuntimeException]
- }
- throw new RuntimeException(cause)
- }
- }
- }
-
-
- private lazy val acceptHeader = {
-
- import scala.collection.JavaConversions._
-
- (for (f <- parser.getSupportedFormats) yield {
- val qualityOfFormat = {
- f match {
- //the default, well established format
- case SupportedFormat.RDF_XML => "1.0";
- //n3 is a bit less well defined and/or many parsers supports only subsets
- case SupportedFormat.N3 => "0.6";
- //we prefer most dedicated formats to (X)HTML, not because those are "better",
- //but just because it is quite likely that the pure RDF format will be
- //lighter (contain less presentation markup), and it is also possible that HTML does not
- //contain any RDFa, but just points to another format.
- case SupportedFormat.XHTML => "0.5";
- //we prefer XHTML over html, because parsing (should) be easier
- case SupportedFormat.HTML => "0.4";
- //all other formats known currently are structured formats
- case _ => "0.8"
- }
- }
- f + "; q=" + qualityOfFormat + ","
- }).mkString + " *; q=.1" //is that for GRDDL?
- }
+ val networkTimeoutKey = "network-timeout"
+
+ private var networkTimeout: Int = _
+
+ private var tcProvider: TcProviderMultiplexer = new TcProviderMultiplexer
+
+ /**
+ * Register a provider
+ *
+ * @param provider
+ * the provider to be registered
+ */
+ protected def bindWeightedTcProvider(provider: WeightedTcProvider): Unit = {
+ tcProvider.addWeightedTcProvider(provider)
+ }
+
+ /**
+ * Deregister a provider
+ *
+ * @param provider
+ * the provider to be deregistered
+ */
+ protected def unbindWeightedTcProvider(provider: WeightedTcProvider): Unit = {
+ tcProvider.removeWeightedTcProvider(provider)
+ }
+
+ /**OSGI method, called on activation */
+ protected def activate(context: ComponentContext) = {
+ networkTimeout = Integer.parseInt(context.getProperties.get(networkTimeoutKey).toString)
+ }
+
+
+ private var parser: Parser = null
+
+ protected def bindParser(p: Parser) = {
+ parser = p
+ }
+
+ protected def unbindParser(p: Parser) = {
+ parser = null
+ }
+
+ def getWeight: Int = {
+ return 0
+ }
+
+ /**
+ * Any TripleCollection is available as Graph as well as immutable MGraph
+ *
+ * @param name
+ * @return
+ * @throws NoSuchEntityException
+ */
+ def getMGraph(name: UriRef): MGraph = {
+ val graph = getGraph(name)
+ return new AbstractMGraph() {
+ protected def performFilter(subject: NonLiteral, predicate: UriRef, `object` : Resource): java.util.Iterator[Triple] = {
+ graph.filter(subject, predicate, `object`)
+ }
+
+ def size = graph.size
+ }
+ }
+
+ def getGraph(name: UriRef): Graph = {
+ try {
+ getGraph(name, Cache.Fetch)
+ } catch {
+ case e: IOException => {
+ logger.debug("could not get graph by dereferencing uri", e)
+ throw new NoSuchEntityException(name)
+ }
+
+ }
+ }
+
+ def getTriples(name: UriRef): TripleCollection = {
+ return getMGraph(name)
+ }
+
+ def createMGraph(name: UriRef): MGraph = {
+ throw new UnsupportedOperationException
+ }
+
+ def createGraph(name: UriRef, triples: TripleCollection): Graph = {
+ throw new UnsupportedOperationException
+ }
+
+ def deleteTripleCollection(name: UriRef): Unit = {
+ throw new UnsupportedOperationException
+ }
+
+ def getNames(graph: Graph): java.util.Set[UriRef] = {
+ var result: java.util.Set[UriRef] = new java.util.HashSet[UriRef]
+ import collection.JavaConversions._
+ for (name <- listGraphs) {
+ if (getGraph(name).equals(graph)) {
+ result.add(name)
+ }
+ }
+ return result
+ }
+
+ def listTripleCollections: java.util.Set[UriRef] = {
+ var result: java.util.Set[UriRef] = new java.util.HashSet[UriRef]
+ result.addAll(listGraphs)
+ result.addAll(listMGraphs)
+ return result
+ }
+
+ def listGraphs: java.util.Set[UriRef] = {
+ //or should we list graphs for which we have a cached version?
+ return java.util.Collections.emptySet[UriRef]
+ }
+
+ def listMGraphs: java.util.Set[UriRef] = {
+ return java.util.Collections.emptySet[UriRef]
+ }
+
+ /**
+ * The semantics of this resource
+ * @param update if a remote URI, update information on the resource first
+ */
+ def getGraph(name: UriRef, updatePolicy: Cache.Value): Graph = {
+ logger.debug("getting graph " + name)
+ if (name.getUnicodeString.indexOf('#') != -1) {
+ logger.debug("not dereferencing URI with hash sign. Please see CLEREZZA-533 for debate.")
+ throw new NoSuchEntityException(name)
+ }
+ if (name.getUnicodeString.startsWith("urn")) {
+ //these are not dereferenceable
+ throw new NoSuchEntityException(name)
+ }
+ val cacheGraphName = new UriRef("urn:x-localinstance:/cache/" + name.getUnicodeString)
+ //todo: follow redirects and keep track of them
+ //todo: keep track of headers especially date and etag. test for etag similarity
+ //todo: for https connection allow user to specify his webid and send his key: ie allow web server to be an agent
+ //todo: add GRDDL functionality, so that other return types can be processed too
+ //todo: enable ftp and other formats (though content negotiation won't work there)
+ def updateGraph() {
+ val url = new URL(name.getUnicodeString)
+ val connection = url.openConnection()
+ connection match {
+ case hc: HttpURLConnection => {
+ hc.addRequestProperty("Accept", acceptHeader)
+ hc.setReadTimeout(networkTimeout)
+ hc.setConnectTimeout(networkTimeout)
+ };
+ }
+ connection.connect()
+ val in = connection.getInputStream()
+ val mediaType = connection.getContentType()
+ val remoteTriples = parser.parse(in, mediaType, name)
+ tcProvider.synchronized {
+ try {
+ tcProvider.deleteTripleCollection(cacheGraphName)
+ } catch {
+ case e: NoSuchEntityException =>;
+ }
+ tcProvider.createGraph(cacheGraphName, remoteTriples)
+ }
+ }
+ try {
+ //the logic here is not quite right, as we don't look at time of previous fetch.
+ updatePolicy match {
+ case Cache.Fetch => try {
+ tcProvider.getGraph(cacheGraphName)
+ } catch {
+ case e: NoSuchEntityException => updateGraph(); tcProvider.getGraph(cacheGraphName)
+ }
+ case Cache.ForceUpdate => updateGraph(); tcProvider.getGraph(cacheGraphName)
+ case Cache.CacheOnly => tcProvider.getGraph(cacheGraphName)
+ }
+ } catch {
+ case ex: PrivilegedActionException => {
+ var cause: Throwable = ex.getCause
+ if (cause.isInstanceOf[UnsupportedOperationException]) {
+ throw cause.asInstanceOf[UnsupportedOperationException]
+ }
+ if (cause.isInstanceOf[EntityAlreadyExistsException]) {
+ throw cause.asInstanceOf[EntityAlreadyExistsException]
+ }
+ if (cause.isInstanceOf[RuntimeException]) {
+ throw cause.asInstanceOf[RuntimeException]
+ }
+ throw new RuntimeException(cause)
+ }
+ }
+ }
+
+
+ private lazy val acceptHeader = {
+
+ import scala.collection.JavaConversions._
+
+ (for (f <- parser.getSupportedFormats) yield {
+ val qualityOfFormat = {
+ f match {
+ //the default, well established format
+ case SupportedFormat.RDF_XML => "1.0";
+ //n3 is a bit less well defined and/or many parsers supports only subsets
+ case SupportedFormat.N3 => "0.6";
+ //we prefer most dedicated formats to (X)HTML, not because those are "better",
+ //but just because it is quite likely that the pure RDF format will be
+ //lighter (contain less presentation markup), and it is also possible that HTML does not
+ //contain any RDFa, but just points to another format.
+ case SupportedFormat.XHTML => "0.5";
+ //we prefer XHTML over html, because parsing (should) be easier
+ case SupportedFormat.HTML => "0.4";
+ //all other formats known currently are structured formats
+ case _ => "0.8"
+ }
+ }
+ f + "; q=" + qualityOfFormat + ","
+ }).mkString + " *; q=.1" //is that for GRDDL?
+ }
}
object Cache extends Enumeration {
- /**fetch if not in cache, if version in cache is out of date, or return cache */
- val Fetch = Value
- /**fetch from source whatever is in cache */
- val ForceUpdate = Value
- /**only get cached version. If none exists return empty graph */
- val CacheOnly = Value
+ /**fetch if not in cache, if version in cache is out of date, or return cache */
+ val Fetch = Value
+ /**fetch from source whatever is in cache */
+ val ForceUpdate = Value
+ /**only get cached version. If none exists return empty graph */
+ val CacheOnly = Value
}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/scala-scripting/script-engine/src/main/scala/org/apache/clerezza/scala/scripting/BundleContextScalaCompiler.scala
----------------------------------------------------------------------
diff --git a/scala-scripting/script-engine/src/main/scala/org/apache/clerezza/scala/scripting/BundleContextScalaCompiler.scala b/scala-scripting/script-engine/src/main/scala/org/apache/clerezza/scala/scripting/BundleContextScalaCompiler.scala
index 1221212..bdce763 100644
--- a/scala-scripting/script-engine/src/main/scala/org/apache/clerezza/scala/scripting/BundleContextScalaCompiler.scala
+++ b/scala-scripting/script-engine/src/main/scala/org/apache/clerezza/scala/scripting/BundleContextScalaCompiler.scala
@@ -54,8 +54,8 @@ import scala.collection.mutable.ListBuffer
* TODO: check if this is still true with Scala 2.20
*/
class BundleContextScalaCompiler(bundleContext : BundleContext,
- settings: Settings, reporter: Reporter)
- extends Global(settings, reporter) with ReplGlobal with Logging { self =>
+ settings: Settings, reporter: Reporter)
+ extends Global(settings, reporter) with ReplGlobal with Logging { self =>
override lazy val platform: ThisPlatform = {
@@ -85,33 +85,33 @@ class BundleContextScalaCompiler(bundleContext : BundleContext,
}
new MergedClassPath(result.toList.reverse, original.context)
}
- /*override lazy val classPath: ClassPath[AbstractFile] = {
+ /*override lazy val classPath: ClassPath[AbstractFile] = {
- val classPathOrig: ClassPath[AbstractFile] = new PathResolver(settings).result
- var bundles: Array[Bundle] = bundleContext.getBundles
- val classPathAbstractFiles = for (bundle <- bundles;
- val url = bundle.getResource("/");
- if url != null) yield {
- if ("file".equals(url.getProtocol())) {
- new PlainFile(new File(url.toURI()))
- }
- else {
- BundleFS.create(bundle);
- }
- }
- val classPaths: List[ClassPath[AbstractFile]] = (for (abstractFile <- classPathAbstractFiles)
- yield {
- new DirectoryClassPath(abstractFile, classPathOrig.context)
- }) toList
+ val classPathOrig: ClassPath[AbstractFile] = new PathResolver(settings).result
+ var bundles: Array[Bundle] = bundleContext.getBundles
+ val classPathAbstractFiles = for (bundle <- bundles;
+ val url = bundle.getResource("/");
+ if url != null) yield {
+ if ("file".equals(url.getProtocol())) {
+ new PlainFile(new File(url.toURI()))
+ }
+ else {
+ BundleFS.create(bundle);
+ }
+ }
+ val classPaths: List[ClassPath[AbstractFile]] = (for (abstractFile <- classPathAbstractFiles)
+ yield {
+ new DirectoryClassPath(abstractFile, classPathOrig.context)
+ }) toList
- new MergedClassPath[AbstractFile](classPathOrig :: classPaths,
- classPathOrig.context)
+ new MergedClassPath[AbstractFile](classPathOrig :: classPaths,
+ classPathOrig.context)
- }*/
+ }*/
- /*override def rootLoader: LazyType = {
- new loaders.JavaPackageLoader(classPath)
- }*/
+ /*override def rootLoader: LazyType = {
+ new loaders.JavaPackageLoader(classPath)
+ }*/
}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/scala-scripting/script-engine/src/main/scala/org/apache/clerezza/scala/scripting/BundleContextScalaInterpreter.scala
----------------------------------------------------------------------
diff --git a/scala-scripting/script-engine/src/main/scala/org/apache/clerezza/scala/scripting/BundleContextScalaInterpreter.scala b/scala-scripting/script-engine/src/main/scala/org/apache/clerezza/scala/scripting/BundleContextScalaInterpreter.scala
index f713e30..0f174ba 100644
--- a/scala-scripting/script-engine/src/main/scala/org/apache/clerezza/scala/scripting/BundleContextScalaInterpreter.scala
+++ b/scala-scripting/script-engine/src/main/scala/org/apache/clerezza/scala/scripting/BundleContextScalaInterpreter.scala
@@ -29,18 +29,18 @@ import scala.tools.nsc.reporters.Reporter
class BundleContextScalaInterpreter(bundleContext : BundleContext, out: PrintWriter)
- extends IMain(new Settings, out) {
+ extends IMain(new Settings, out) {
- def this(bundleContext : BundleContext) = {
- this(bundleContext, new PrintWriter(System.out))
- }
+ def this(bundleContext : BundleContext) = {
+ this(bundleContext, new PrintWriter(System.out))
+ }
- override lazy val classLoader: AbstractFileClassLoader = {
- new AbstractFileClassLoader(virtualDirectory, this.getClass.getClassLoader())
- }
- override protected def newCompiler(settings: Settings, reporter: Reporter) = {
- settings.outputDirs setSingleOutput virtualDirectory
- new BundleContextScalaCompiler(bundleContext, settings, reporter)
- }
+ override lazy val classLoader: AbstractFileClassLoader = {
+ new AbstractFileClassLoader(virtualDirectory, this.getClass.getClassLoader())
+ }
+ override protected def newCompiler(settings: Settings, reporter: Reporter) = {
+ settings.outputDirs setSingleOutput virtualDirectory
+ new BundleContextScalaCompiler(bundleContext, settings, reporter)
+ }
}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/scala-scripting/script-engine/src/main/scala/org/apache/clerezza/scala/scripting/BundleFS.scala
----------------------------------------------------------------------
diff --git a/scala-scripting/script-engine/src/main/scala/org/apache/clerezza/scala/scripting/BundleFS.scala b/scala-scripting/script-engine/src/main/scala/org/apache/clerezza/scala/scripting/BundleFS.scala
index c66a9e3..32de7a6 100644
--- a/scala-scripting/script-engine/src/main/scala/org/apache/clerezza/scala/scripting/BundleFS.scala
+++ b/scala-scripting/script-engine/src/main/scala/org/apache/clerezza/scala/scripting/BundleFS.scala
@@ -27,161 +27,161 @@ package org.apache.clerezza.scala.scripting {
- /**
- * Implementation of {@link AbstractFile} on top of a {@link org.osgi.framework.Bundle}
- */
- object BundleFS {
-
- /**
- * Create a new {@link AbstractFile} instance representing an
- * {@link org.osgi.framework.Bundle}
- * @param bundle
- */
- def create(bundle: Bundle): AbstractFile = {
- require(bundle != null, "bundle must not be null")
-
- /**
- * The superclass of FileEntry and DirEntry
- */
- abstract class BundleEntry(url: URL, parent: DirEntry) extends AbstractFile {
- require(url != null, "url must not be null")
- lazy val (path: String, name: String) = getPathAndName(url)
- lazy val fullName: String = (path::name::Nil).filter(!_.isEmpty).mkString("/")
-
- /**
- * @return null
- */
- def file: File = null
-
- //what if this is not a relative file?
- def absolute = null
-
- /**
- * @return last modification time or 0 if not known
- */
- def lastModified: Long =
- try { url.openConnection.getLastModified }
- catch { case _: Exception => 0 }
-
- @throws(classOf[IOException])
- def container: AbstractFile =
- valueOrElse(parent) {
- throw new IOException("No container")
- }
-
- @throws(classOf[IOException])
- def input: InputStream = url.openStream()
-
- /**
- * Not supported. Always throws an IOException.
- * @throws IOException
- */
- @throws(classOf[IOException])
- def output = throw new IOException("not supported: output")
-
- def delete = throw new IOException("not supported: delete")
- def create = throw new IOException("not supported: create")
-
- private def getPathAndName(url: URL): (String, String) = {
- val u = url.getPath
- var k = u.length
- while( (k > 0) && (u(k - 1) == '/') )
- k = k - 1
-
- var j = k
- while( (j > 0) && (u(j - 1) != '/') )
- j = j - 1
-
- (u.substring(if (j > 0) 1 else 0, if (j > 1) j - 1 else j), u.substring(j, k))
- }
-
- override def toString = fullName
- }
-
- class DirEntry(url: URL, parent: DirEntry) extends BundleEntry(url, parent) {
-
- /**
- * @return true
- */
- def isDirectory: Boolean = true
-
- override def iterator: Iterator[AbstractFile] = {
- new Iterator[AbstractFile]() {
- val dirs = bundle.getEntryPaths(fullName)
- def hasNext = if (dirs != null) { dirs.hasMoreElements} else {false}
- def next = {
- val entry = dirs.nextElement.asInstanceOf[String]
- var entryUrl = bundle.getResource("/" + entry)
-
- // Bundle.getResource seems to be inconsistent with respect to requiring
- // a trailing slash
- if (entryUrl == null)
- entryUrl = bundle.getResource("/" + removeTralingSlash(entry))
-
- if (entryUrl == null) {
- entryUrl = new URL(bundle.getResource("/"), entry)
- if (entryUrl == null) {
- throw new RuntimeException("Could not locate entry: "+entry+" in bundle: "+bundle)
- }
- }
+ /**
+ * Implementation of {@link AbstractFile} on top of a {@link org.osgi.framework.Bundle}
+ */
+ object BundleFS {
+
+ /**
+ * Create a new {@link AbstractFile} instance representing an
+ * {@link org.osgi.framework.Bundle}
+ * @param bundle
+ */
+ def create(bundle: Bundle): AbstractFile = {
+ require(bundle != null, "bundle must not be null")
+
+ /**
+ * The superclass of FileEntry and DirEntry
+ */
+ abstract class BundleEntry(url: URL, parent: DirEntry) extends AbstractFile {
+ require(url != null, "url must not be null")
+ lazy val (path: String, name: String) = getPathAndName(url)
+ lazy val fullName: String = (path::name::Nil).filter(!_.isEmpty).mkString("/")
+
+ /**
+ * @return null
+ */
+ def file: File = null
+
+ //what if this is not a relative file?
+ def absolute = null
+
+ /**
+ * @return last modification time or 0 if not known
+ */
+ def lastModified: Long =
+ try { url.openConnection.getLastModified }
+ catch { case _: Exception => 0 }
+
+ @throws(classOf[IOException])
+ def container: AbstractFile =
+ valueOrElse(parent) {
+ throw new IOException("No container")
+ }
+
+ @throws(classOf[IOException])
+ def input: InputStream = url.openStream()
+
+ /**
+ * Not supported. Always throws an IOException.
+ * @throws IOException
+ */
+ @throws(classOf[IOException])
+ def output = throw new IOException("not supported: output")
+
+ def delete = throw new IOException("not supported: delete")
+ def create = throw new IOException("not supported: create")
+
+ private def getPathAndName(url: URL): (String, String) = {
+ val u = url.getPath
+ var k = u.length
+ while( (k > 0) && (u(k - 1) == '/') )
+ k = k - 1
+
+ var j = k
+ while( (j > 0) && (u(j - 1) != '/') )
+ j = j - 1
+
+ (u.substring(if (j > 0) 1 else 0, if (j > 1) j - 1 else j), u.substring(j, k))
+ }
+
+ override def toString = fullName
+ }
+
+ class DirEntry(url: URL, parent: DirEntry) extends BundleEntry(url, parent) {
+
+ /**
+ * @return true
+ */
+ def isDirectory: Boolean = true
+
+ override def iterator: Iterator[AbstractFile] = {
+ new Iterator[AbstractFile]() {
+ val dirs = bundle.getEntryPaths(fullName)
+ def hasNext = if (dirs != null) { dirs.hasMoreElements} else {false}
+ def next = {
+ val entry = dirs.nextElement.asInstanceOf[String]
+ var entryUrl = bundle.getResource("/" + entry)
+
+ // Bundle.getResource seems to be inconsistent with respect to requiring
+ // a trailing slash
+ if (entryUrl == null)
+ entryUrl = bundle.getResource("/" + removeTralingSlash(entry))
+
+ if (entryUrl == null) {
+ entryUrl = new URL(bundle.getResource("/"), entry)
+ if (entryUrl == null) {
+ throw new RuntimeException("Could not locate entry: "+entry+" in bundle: "+bundle)
+ }
+ }
- if (entry.endsWith(".class"))
- new FileEntry(entryUrl, DirEntry.this)
- else
- new DirEntry(entryUrl, DirEntry.this)
- }
+ if (entry.endsWith(".class"))
+ new FileEntry(entryUrl, DirEntry.this)
+ else
+ new DirEntry(entryUrl, DirEntry.this)
+ }
- private def removeTralingSlash(s: String): String = {
- if (s == null || s.length == 0) {
- s
- }else if (s.last == '/') {
- removeTralingSlash(s.substring(0, s.length - 1))
- } else {
- s
- }
- }
- }
- }
-
- def lookupName(name: String, directory: Boolean): AbstractFile = {
- val entry = bundle.getEntry(fullName + "/" + name)
- nullOrElse(entry) { entry =>
- if (directory)
- new DirEntry(entry, DirEntry.this)
- else
- new FileEntry(entry, DirEntry.this)
- }
- }
-
- def lookupNameUnchecked(name: String, directory: Boolean): AbstractFile = {
- val entry = bundle.getEntry(fullName + "/" + name)
- if (entry == null) {
- throw new RuntimeException("Not yet implemented: inexistendt file")
- } else {
- if (directory)
- new DirEntry(entry, DirEntry.this)
- else
- new FileEntry(entry, DirEntry.this)
- }
- }
-
- }
-
- class FileEntry(url: URL, parent: DirEntry) extends BundleEntry(url, parent) {
-
- /**
- * @return false
- */
- def isDirectory: Boolean = false
- override def sizeOption: Option[Int] = Some(bundle.getEntry(fullName).openConnection().getContentLength())
- override def iterator: Iterator[AbstractFile] = Iterator.empty
- def lookupName(name: String, directory: Boolean): AbstractFile = null
- def lookupNameUnchecked(name: String, directory: Boolean): AbstractFile = null
- }
-
- new DirEntry(bundle.getResource("/"), null)
- }
-
- }
+ private def removeTralingSlash(s: String): String = {
+ if (s == null || s.length == 0) {
+ s
+ }else if (s.last == '/') {
+ removeTralingSlash(s.substring(0, s.length - 1))
+ } else {
+ s
+ }
+ }
+ }
+ }
+
+ def lookupName(name: String, directory: Boolean): AbstractFile = {
+ val entry = bundle.getEntry(fullName + "/" + name)
+ nullOrElse(entry) { entry =>
+ if (directory)
+ new DirEntry(entry, DirEntry.this)
+ else
+ new FileEntry(entry, DirEntry.this)
+ }
+ }
+
+ def lookupNameUnchecked(name: String, directory: Boolean): AbstractFile = {
+ val entry = bundle.getEntry(fullName + "/" + name)
+ if (entry == null) {
+ throw new RuntimeException("Not yet implemented: inexistendt file")
+ } else {
+ if (directory)
+ new DirEntry(entry, DirEntry.this)
+ else
+ new FileEntry(entry, DirEntry.this)
+ }
+ }
+
+ }
+
+ class FileEntry(url: URL, parent: DirEntry) extends BundleEntry(url, parent) {
+
+ /**
+ * @return false
+ */
+ def isDirectory: Boolean = false
+ override def sizeOption: Option[Int] = Some(bundle.getEntry(fullName).openConnection().getContentLength())
+ override def iterator: Iterator[AbstractFile] = Iterator.empty
+ def lookupName(name: String, directory: Boolean): AbstractFile = null
+ def lookupNameUnchecked(name: String, directory: Boolean): AbstractFile = null
+ }
+
+ new DirEntry(bundle.getResource("/"), null)
+ }
+
+ }
}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/scala-scripting/script-engine/src/main/scala/org/apache/clerezza/scala/scripting/CompilerService.scala
----------------------------------------------------------------------
diff --git a/scala-scripting/script-engine/src/main/scala/org/apache/clerezza/scala/scripting/CompilerService.scala b/scala-scripting/script-engine/src/main/scala/org/apache/clerezza/scala/scripting/CompilerService.scala
index d21f7ec..56205b1 100644
--- a/scala-scripting/script-engine/src/main/scala/org/apache/clerezza/scala/scripting/CompilerService.scala
+++ b/scala-scripting/script-engine/src/main/scala/org/apache/clerezza/scala/scripting/CompilerService.scala
@@ -184,5 +184,5 @@ class CompilerService() extends BundleListener {
}
}
-
+
}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/scala-scripting/script-engine/src/main/scala/org/apache/clerezza/scala/scripting/InterpreterFactory.scala
----------------------------------------------------------------------
diff --git a/scala-scripting/script-engine/src/main/scala/org/apache/clerezza/scala/scripting/InterpreterFactory.scala b/scala-scripting/script-engine/src/main/scala/org/apache/clerezza/scala/scripting/InterpreterFactory.scala
index dda2595..fa1f5ba 100644
--- a/scala-scripting/script-engine/src/main/scala/org/apache/clerezza/scala/scripting/InterpreterFactory.scala
+++ b/scala-scripting/script-engine/src/main/scala/org/apache/clerezza/scala/scripting/InterpreterFactory.scala
@@ -30,22 +30,22 @@ import java.net._
class InterpreterFactory() {
-
- protected var bundles: Array[Bundle] = null
- protected var bundleContext : BundleContext = null;
+
+ protected var bundles: Array[Bundle] = null
+ protected var bundleContext : BundleContext = null;
- def activate(componentContext: ComponentContext)= {
- bundleContext = componentContext.getBundleContext
- }
+ def activate(componentContext: ComponentContext)= {
+ bundleContext = componentContext.getBundleContext
+ }
- def deactivate(componentContext: ComponentContext) = {
- bundleContext = null
- }
+ def deactivate(componentContext: ComponentContext) = {
+ bundleContext = null
+ }
- def createInterpreter(out: PrintWriter) : IMain = {
- val i = new BundleContextScalaInterpreter(bundleContext, out)
- i
- }
+ def createInterpreter(out: PrintWriter) : IMain = {
+ val i = new BundleContextScalaInterpreter(bundleContext, out)
+ i
+ }
-
+
}
[5/9] CLEREZZA-435: repaced tabs with spaces in scala files
Posted by re...@apache.org.
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/platform.logging/initializer/src/main/scala/org/apache/clerezza/platform/logging/initializer/Activator.scala
----------------------------------------------------------------------
diff --git a/platform.logging/initializer/src/main/scala/org/apache/clerezza/platform/logging/initializer/Activator.scala b/platform.logging/initializer/src/main/scala/org/apache/clerezza/platform/logging/initializer/Activator.scala
index cfdc270..c8220db 100644
--- a/platform.logging/initializer/src/main/scala/org/apache/clerezza/platform/logging/initializer/Activator.scala
+++ b/platform.logging/initializer/src/main/scala/org/apache/clerezza/platform/logging/initializer/Activator.scala
@@ -35,54 +35,54 @@ import org.osgi.framework.BundleActivator
class Activator extends BundleActivator {
- private val configurationAdminClassName = classOf[ConfigurationAdmin].getName
+ private val configurationAdminClassName = classOf[ConfigurationAdmin].getName
- def start(context: BundleContext) {
- import scala.collection.JavaConversions._
- val paxLoggingLocation: String = context.getBundles().
- find(bundle => bundle.getSymbolicName().equals("org.ops4j.pax.logging.pax-logging-service")) match {
- case Some(b) => b.getLocation();
- case _ => throw new RuntimeException("org.ops4j.pax.logging.pax-logging-service not found")
- }
- val serviceReference = context.getServiceReference(configurationAdminClassName);
- def configureIfUnconfigured(serviceReference: ServiceReference[_]) {
- val configurationAdmin = context.getService(serviceReference).asInstanceOf[ConfigurationAdmin]
- val config: Configuration = configurationAdmin.getConfiguration(
- "org.ops4j.pax.logging", paxLoggingLocation);
- if (config.getProperties() == null) {
- val props: Dictionary[String, String] = new Hashtable[String, String]();
- props.put("log4j.rootLogger", "INFO, R, stdout");
- props.put("log4j.logger.org.apache.clerezza","DEBUG")
- props.put("log4j.appender.stdout", "org.apache.log4j.ConsoleAppender");
- props.put("log4j.appender.stdout.layout", "org.apache.log4j.PatternLayout");
- props.put("log4j.appender.stdout.Threshold", "WARN");
- // Pattern to output the caller's file name and line number.
- props.put("log4j.appender.stdout.layout.ConversionPattern", "%d [%t] %5p [%t] (%F\\:%L) - %m%n");
- props.put("log4j.appender.R", "org.apache.log4j.FileAppender");
- props.put("log4j.appender.R.File", "clerezza.log");
- props.put("log4j.appender.R.layout", "org.apache.log4j.PatternLayout");
- props.put("log4j.appender.R.layout.ConversionPattern", "%d [%t] %p %t %c - %m%n");
+ def start(context: BundleContext) {
+ import scala.collection.JavaConversions._
+ val paxLoggingLocation: String = context.getBundles().
+ find(bundle => bundle.getSymbolicName().equals("org.ops4j.pax.logging.pax-logging-service")) match {
+ case Some(b) => b.getLocation();
+ case _ => throw new RuntimeException("org.ops4j.pax.logging.pax-logging-service not found")
+ }
+ val serviceReference = context.getServiceReference(configurationAdminClassName);
+ def configureIfUnconfigured(serviceReference: ServiceReference[_]) {
+ val configurationAdmin = context.getService(serviceReference).asInstanceOf[ConfigurationAdmin]
+ val config: Configuration = configurationAdmin.getConfiguration(
+ "org.ops4j.pax.logging", paxLoggingLocation);
+ if (config.getProperties() == null) {
+ val props: Dictionary[String, String] = new Hashtable[String, String]();
+ props.put("log4j.rootLogger", "INFO, R, stdout");
+ props.put("log4j.logger.org.apache.clerezza","DEBUG")
+ props.put("log4j.appender.stdout", "org.apache.log4j.ConsoleAppender");
+ props.put("log4j.appender.stdout.layout", "org.apache.log4j.PatternLayout");
+ props.put("log4j.appender.stdout.Threshold", "WARN");
+ // Pattern to output the caller's file name and line number.
+ props.put("log4j.appender.stdout.layout.ConversionPattern", "%d [%t] %5p [%t] (%F\\:%L) - %m%n");
+ props.put("log4j.appender.R", "org.apache.log4j.FileAppender");
+ props.put("log4j.appender.R.File", "clerezza.log");
+ props.put("log4j.appender.R.layout", "org.apache.log4j.PatternLayout");
+ props.put("log4j.appender.R.layout.ConversionPattern", "%d [%t] %p %t %c - %m%n");
- config.update(props);
- }
- }
- if (serviceReference != null) {
- configureIfUnconfigured(serviceReference);
- } else {
- val filter: String = "(objectclass=" + configurationAdminClassName + ")";
- context.addServiceListener(new ServiceListener{
- def serviceChanged(e: ServiceEvent) {
- if (e.getType == ServiceEvent.REGISTERED) {
- configureIfUnconfigured(e.getServiceReference)
- }
- }
- },filter)
- }
-
- }
+ config.update(props);
+ }
+ }
+ if (serviceReference != null) {
+ configureIfUnconfigured(serviceReference);
+ } else {
+ val filter: String = "(objectclass=" + configurationAdminClassName + ")";
+ context.addServiceListener(new ServiceListener{
+ def serviceChanged(e: ServiceEvent) {
+ if (e.getType == ServiceEvent.REGISTERED) {
+ configureIfUnconfigured(e.getServiceReference)
+ }
+ }
+ },filter)
+ }
+
+ }
- def stop(context: BundleContext) {
+ def stop(context: BundleContext) {
- }
+ }
}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/platform.security.foafssl/core/src/main/scala/org/apache/clerezza/foafssl/auth/FoafSslAuthentication.scala
----------------------------------------------------------------------
diff --git a/platform.security.foafssl/core/src/main/scala/org/apache/clerezza/foafssl/auth/FoafSslAuthentication.scala b/platform.security.foafssl/core/src/main/scala/org/apache/clerezza/foafssl/auth/FoafSslAuthentication.scala
index 45a274a..670c28a 100644
--- a/platform.security.foafssl/core/src/main/scala/org/apache/clerezza/foafssl/auth/FoafSslAuthentication.scala
+++ b/platform.security.foafssl/core/src/main/scala/org/apache/clerezza/foafssl/auth/FoafSslAuthentication.scala
@@ -78,14 +78,14 @@ class FoafSslAuthentication extends WeightedAuthenticationMethod {
claim.principal
}
- subject.getPublicCredentials.add(x509c)
- if (verified.size > 0) {
- subject.getPrincipals().remove(UserUtil.ANONYMOUS)
- subject.getPrincipals().addAll(verified)
- return true
- } else {
- return false
- }
+ subject.getPublicCredentials.add(x509c)
+ if (verified.size > 0) {
+ subject.getPrincipals().remove(UserUtil.ANONYMOUS)
+ subject.getPrincipals().addAll(verified)
+ return true
+ } else {
+ return false
+ }
}
def addAgentToSystem(id: WebIDClaim) {
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/platform.security.foafssl/core/src/main/scala/org/apache/clerezza/foafssl/auth/WebIDClaim.scala
----------------------------------------------------------------------
diff --git a/platform.security.foafssl/core/src/main/scala/org/apache/clerezza/foafssl/auth/WebIDClaim.scala b/platform.security.foafssl/core/src/main/scala/org/apache/clerezza/foafssl/auth/WebIDClaim.scala
index 8ae8429..468b350 100644
--- a/platform.security.foafssl/core/src/main/scala/org/apache/clerezza/foafssl/auth/WebIDClaim.scala
+++ b/platform.security.foafssl/core/src/main/scala/org/apache/clerezza/foafssl/auth/WebIDClaim.scala
@@ -44,129 +44,129 @@ import scala.None
*/
class WebIDClaim(val webId: UriRef, val key: PublicKey) {
- import X509Claim._
-
- val errors = new LinkedList[java.lang.Throwable]()
-
- lazy val principal = new WebIdPrincipal(webId)
- var verified = Verification.Unverified
-
- /*private lazy val selectQuery = {
- val query = """PREFIX cert: <http://www.w3.org/ns/auth/cert#>
- PREFIX rsa: <http://www.w3.org/ns/auth/rsa#>
- SELECT ?m ?e ?mod ?exp
- WHERE {
- [] cert:identity ?webid ;
- rsa:modulus ?m ;
- rsa:public_exponent ?e .
- OPTIONAL { ?m cert:hex ?mod . }
- OPTIONAL { ?e cert:decimal ?exp . }
- }"""
- queryParser.parse(query).asInstanceOf[SelectQuery]
- }*/
-
-
-
- /**
- * verify this claim
- * @param authSrvc: the authentication service contains information about where to get graphs
- */
- //todo: make this asynchronous
- def verify(authSrvc: FoafSslAuthentication) {
- if (!webId.getUnicodeString.startsWith("http:") && !webId.getUnicodeString.startsWith("https:")) {
- //todo: ftp, and ftps should also be doable, though content negoations is then lacking
- verified = Verification.Unsupported
- return
- }
- verified = try {
- var webIdInfo = authSrvc.webIdSrvc.getWebIdInfo(webId)
- verify(webIdInfo.localPublicUserData) match {
- case None => Verification.Verified
- case Some(err) => {
- webIdInfo.forceCacheUpdate()
- webIdInfo = authSrvc.webIdSrvc.getWebIdInfo(webId)
- verify(webIdInfo.localPublicUserData) match {
- case None => Verification.Verified
- case Some(err) => {
- errors.add(err)
- Verification.Failed
- }
- }
- }
- }
- } catch {
- case e => {
- errors.add(e)
- Verification.Failed
- }
- }
- }
-
- def verify(tc: TripleCollection): Option[WebIDVerificationError] = {
- key match {
- case k: RSAPublicKey => verify(k, tc);
- case x => Some(new WebIDVerificationError("Unsupported key format "+x.getClass) )
- }
- }
-
- private def verify(publicKey: RSAPublicKey, tc: TripleCollection): Option[WebIDVerificationError] = {
- val publicKeysInGraph = getPublicKeysInGraph(tc)
- if (publicKeysInGraph.size==0) return Some(new WebIDVerificationError("No public keys found in WebID Profile for "+webId.getUnicodeString))
- val publicKeyTuple = (new BigInt(publicKey.getModulus), new BigInt(publicKey.getPublicExponent))
- val result = publicKeysInGraph.contains(publicKeyTuple)
- if (logger.isDebugEnabled) {
- if (!result) {
- val baos = new ByteArrayOutputStream
- Serializer.getInstance.serialize(baos, tc, SupportedFormat.TURTLE);
- logger.debug("no matching key in: \n{}", new String(baos.toByteArray));
- logger.debug("the public key is not among the " +
- publicKeysInGraph.size + " keys in the profile graph of size " +
- tc.size)
- logger.debug("PublicKey: " + publicKeyTuple)
- publicKeysInGraph.foreach(k => logger.debug("PublikKey in graph: " + k))
- }
- }
- if (result) return None
- else return Some(new WebIDVerificationError("No matching keys found in WebID Profile"))
- }
-
- private def getPublicKeysInGraph(tc: TripleCollection): Array[(BigInt, BigInt)] = {
- import scala.collection.JavaConversions._
- val publicKeys = for (t <- tc.filter(null, CERT.identity, webId)) yield {
- t.getSubject
- }
- (for (p <- publicKeys) yield {
- val node = new GraphNode(p, tc)
- val modulusRes = node / RSA.modulus
- val modulus = intValueOfResource(modulusRes) match {
- case Some(x) => x
- case _ => BigInt(0)
- }
- val exponentRes = node / RSA.public_exponent
- val exponent = intValueOfResource(exponentRes) match {
- case Some(x) => x
- case _ => BigInt(0)
- }
- (modulus, exponent)
- }).toArray
- }
-
-
- def canEqual(other: Any) = other.isInstanceOf[WebIDClaim]
-
- override
- def equals(other: Any): Boolean =
- other match {
- case that: WebIDClaim => (that eq this) || (that.canEqual(this) && webId == that.webId && key == that.key)
- case _ => false
- }
-
- override
- lazy val hashCode: Int = 41 * (
- 41 * (
- 41 + (if (webId != null) webId.hashCode else 0)
- ) + (if (key != null) key.hashCode else 0)
- )
+ import X509Claim._
+
+ val errors = new LinkedList[java.lang.Throwable]()
+
+ lazy val principal = new WebIdPrincipal(webId)
+ var verified = Verification.Unverified
+
+ /*private lazy val selectQuery = {
+ val query = """PREFIX cert: <http://www.w3.org/ns/auth/cert#>
+ PREFIX rsa: <http://www.w3.org/ns/auth/rsa#>
+ SELECT ?m ?e ?mod ?exp
+ WHERE {
+ [] cert:identity ?webid ;
+ rsa:modulus ?m ;
+ rsa:public_exponent ?e .
+ OPTIONAL { ?m cert:hex ?mod . }
+ OPTIONAL { ?e cert:decimal ?exp . }
+ }"""
+ queryParser.parse(query).asInstanceOf[SelectQuery]
+ }*/
+
+
+
+ /**
+ * verify this claim
+ * @param authSrvc: the authentication service contains information about where to get graphs
+ */
+ //todo: make this asynchronous
+ def verify(authSrvc: FoafSslAuthentication) {
+ if (!webId.getUnicodeString.startsWith("http:") && !webId.getUnicodeString.startsWith("https:")) {
+ //todo: ftp, and ftps should also be doable, though content negoations is then lacking
+ verified = Verification.Unsupported
+ return
+ }
+ verified = try {
+ var webIdInfo = authSrvc.webIdSrvc.getWebIdInfo(webId)
+ verify(webIdInfo.localPublicUserData) match {
+ case None => Verification.Verified
+ case Some(err) => {
+ webIdInfo.forceCacheUpdate()
+ webIdInfo = authSrvc.webIdSrvc.getWebIdInfo(webId)
+ verify(webIdInfo.localPublicUserData) match {
+ case None => Verification.Verified
+ case Some(err) => {
+ errors.add(err)
+ Verification.Failed
+ }
+ }
+ }
+ }
+ } catch {
+ case e => {
+ errors.add(e)
+ Verification.Failed
+ }
+ }
+ }
+
+ def verify(tc: TripleCollection): Option[WebIDVerificationError] = {
+ key match {
+ case k: RSAPublicKey => verify(k, tc);
+ case x => Some(new WebIDVerificationError("Unsupported key format "+x.getClass) )
+ }
+ }
+
+ private def verify(publicKey: RSAPublicKey, tc: TripleCollection): Option[WebIDVerificationError] = {
+ val publicKeysInGraph = getPublicKeysInGraph(tc)
+ if (publicKeysInGraph.size==0) return Some(new WebIDVerificationError("No public keys found in WebID Profile for "+webId.getUnicodeString))
+ val publicKeyTuple = (new BigInt(publicKey.getModulus), new BigInt(publicKey.getPublicExponent))
+ val result = publicKeysInGraph.contains(publicKeyTuple)
+ if (logger.isDebugEnabled) {
+ if (!result) {
+ val baos = new ByteArrayOutputStream
+ Serializer.getInstance.serialize(baos, tc, SupportedFormat.TURTLE);
+ logger.debug("no matching key in: \n{}", new String(baos.toByteArray));
+ logger.debug("the public key is not among the " +
+ publicKeysInGraph.size + " keys in the profile graph of size " +
+ tc.size)
+ logger.debug("PublicKey: " + publicKeyTuple)
+ publicKeysInGraph.foreach(k => logger.debug("PublikKey in graph: " + k))
+ }
+ }
+ if (result) return None
+ else return Some(new WebIDVerificationError("No matching keys found in WebID Profile"))
+ }
+
+ private def getPublicKeysInGraph(tc: TripleCollection): Array[(BigInt, BigInt)] = {
+ import scala.collection.JavaConversions._
+ val publicKeys = for (t <- tc.filter(null, CERT.identity, webId)) yield {
+ t.getSubject
+ }
+ (for (p <- publicKeys) yield {
+ val node = new GraphNode(p, tc)
+ val modulusRes = node / RSA.modulus
+ val modulus = intValueOfResource(modulusRes) match {
+ case Some(x) => x
+ case _ => BigInt(0)
+ }
+ val exponentRes = node / RSA.public_exponent
+ val exponent = intValueOfResource(exponentRes) match {
+ case Some(x) => x
+ case _ => BigInt(0)
+ }
+ (modulus, exponent)
+ }).toArray
+ }
+
+
+ def canEqual(other: Any) = other.isInstanceOf[WebIDClaim]
+
+ override
+ def equals(other: Any): Boolean =
+ other match {
+ case that: WebIDClaim => (that eq this) || (that.canEqual(this) && webId == that.webId && key == that.key)
+ case _ => false
+ }
+
+ override
+ lazy val hashCode: Int = 41 * (
+ 41 * (
+ 41 + (if (webId != null) webId.hashCode else 0)
+ ) + (if (key != null) key.hashCode else 0)
+ )
}
class WebIDVerificationError(msg: String) extends Error(msg) {
@@ -174,14 +174,14 @@ class WebIDVerificationError(msg: String) extends Error(msg) {
}
object WebIdPrincipal {
- //todo: not at all a satisfactory username method. Find something better.
- def userName(webId: UriRef) = for (c <- webId.getUnicodeString) yield
- c match {
- case ':' => '_';
- case '#' => '_';
- case '/' => '_';
- case _ => c
- }
+ //todo: not at all a satisfactory username method. Find something better.
+ def userName(webId: UriRef) = for (c <- webId.getUnicodeString) yield
+ c match {
+ case ':' => '_';
+ case '#' => '_';
+ case '/' => '_';
+ case _ => c
+ }
}
class WebIdPrincipal(val webId: UriRef) extends PrincipalImpl(WebIdPrincipal.userName(webId)) {
@@ -191,26 +191,26 @@ class WebIdPrincipal(val webId: UriRef) extends PrincipalImpl(WebIdPrincipal.use
object Verification extends Enumeration {
- /**
- * the claim has not yet been verified
- */
- val Unverified = Value
+ /**
+ * the claim has not yet been verified
+ */
+ val Unverified = Value
- /**
- * The claim was verified and succeeded
- */
- val Verified = Value
+ /**
+ * The claim was verified and succeeded
+ */
+ val Verified = Value
- /**
- * The claim was verified and failed
- */
- val Failed = Value
+ /**
+ * The claim was verified and failed
+ */
+ val Failed = Value
- /**
- * The claim cannot be verified by this agent
- */
- val Unsupported = Value
+ /**
+ * The claim cannot be verified by this agent
+ */
+ val Unsupported = Value
}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/platform.security.foafssl/core/src/main/scala/org/apache/clerezza/foafssl/auth/X509Claim.scala
----------------------------------------------------------------------
diff --git a/platform.security.foafssl/core/src/main/scala/org/apache/clerezza/foafssl/auth/X509Claim.scala b/platform.security.foafssl/core/src/main/scala/org/apache/clerezza/foafssl/auth/X509Claim.scala
index 96ef674..72004de 100644
--- a/platform.security.foafssl/core/src/main/scala/org/apache/clerezza/foafssl/auth/X509Claim.scala
+++ b/platform.security.foafssl/core/src/main/scala/org/apache/clerezza/foafssl/auth/X509Claim.scala
@@ -163,13 +163,13 @@ object X509Claim {
}
/*
- * This method helps us deal with the old style notation
- * of key rsa:modulus [ cert:hex "a342342bde..." ]
- * rsa:public_exponent [ cert:int "256" ]
- *
- * where the numbers are representated by blank nodes identified by their relation to a string
- *
- */
+ * This method helps us deal with the old style notation
+ * of key rsa:modulus [ cert:hex "a342342bde..." ]
+ * rsa:public_exponent [ cert:int "256" ]
+ *
+ * where the numbers are representated by blank nodes identified by their relation to a string
+ *
+ */
def intValueOfResourceByProperty(n: GraphNode): Option[BigInt] = {
val hexValues = n / CERT.hex
if (hexValues.length > 0) {
@@ -186,10 +186,10 @@ object X509Claim {
return None
}
- /**
- * @prefix a typed literal of some some numeric type
- * @return the BigInteger it represents
- */
+ /**
+ * @prefix a typed literal of some some numeric type
+ * @return the BigInteger it represents
+ */
def intValueOfTypedLiteral(l: TypedLiteral): Option[BigInt] = {
try {
(l.getLexicalForm, l.getDataType) match {
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/platform.security.foafssl/core/src/main/scala/org/apache/clerezza/foafssl/ssl/Activator.scala
----------------------------------------------------------------------
diff --git a/platform.security.foafssl/core/src/main/scala/org/apache/clerezza/foafssl/ssl/Activator.scala b/platform.security.foafssl/core/src/main/scala/org/apache/clerezza/foafssl/ssl/Activator.scala
index ee30378..21e43ee 100644
--- a/platform.security.foafssl/core/src/main/scala/org/apache/clerezza/foafssl/ssl/Activator.scala
+++ b/platform.security.foafssl/core/src/main/scala/org/apache/clerezza/foafssl/ssl/Activator.scala
@@ -33,16 +33,16 @@ import org.wymiwyg.jetty.httpservice.{Activator => ServiceActivator}
*/
class Activator() {
-
- var x509TrustManagerWrapperService: X509TrustManagerWrapperService = null;
- protected def bindX509TrustManagerWrapperService(s: X509TrustManagerWrapperService) = {
- x509TrustManagerWrapperService = s
- }
- protected def unbindX509TrustManagerWrapperService(s: X509TrustManagerWrapperService) = {
- x509TrustManagerWrapperService = null
- }
-
- protected def activate(context: ComponentContext) = {
+
+ var x509TrustManagerWrapperService: X509TrustManagerWrapperService = null;
+ protected def bindX509TrustManagerWrapperService(s: X509TrustManagerWrapperService) = {
+ x509TrustManagerWrapperService = s
+ }
+ protected def unbindX509TrustManagerWrapperService(s: X509TrustManagerWrapperService) = {
+ x509TrustManagerWrapperService = null
+ }
+
+ protected def activate(context: ComponentContext) = {
try{
val bundleContext = context.getBundleContext
//TODO set jvm default ca-store
@@ -50,7 +50,7 @@ class Activator() {
if (http!=null && "true".equals(http)) {
val sslContextFactory = new X509SSLContextFactory(
getServerCertKeyStore(context),
- getKeyStorePassword(bundleContext),
+ getKeyStorePassword(bundleContext),
getServerCertKeyStore(context));//getCaKeyStore());
sslContextFactory
.setTrustManagerWrapper(x509TrustManagerWrapperService);
@@ -64,44 +64,44 @@ class Activator() {
catch{
case e : Exception => println("unable to activate FOAF+SSL")
}
- }
-
-
- def getServerCertKeyStore(context: ComponentContext): KeyStore = {
- val bundleContext = context.getBundleContext
- val keyStoreLoader = new KeyStoreLoader
- keyStoreLoader.setKeyStoreType(getKeyStoreType(bundleContext))
- keyStoreLoader.setKeyStorePath(getKeyStorePath(bundleContext))
- keyStoreLoader.setKeyStorePassword(getKeyStorePassword(bundleContext))
+ }
+
+
+ def getServerCertKeyStore(context: ComponentContext): KeyStore = {
+ val bundleContext = context.getBundleContext
+ val keyStoreLoader = new KeyStoreLoader
+ keyStoreLoader.setKeyStoreType(getKeyStoreType(bundleContext))
+ keyStoreLoader.setKeyStorePath(getKeyStorePath(bundleContext))
+ keyStoreLoader.setKeyStorePassword(getKeyStorePassword(bundleContext))
return keyStoreLoader.loadKeyStore();
}
-
- protected def getKeyStoreType(context: BundleContext) = {
- val property = context.getProperty(ServiceActivator.CONTEXT_PROPERTY_KEYSTORE_TYPE);
- if (property != null) {
- property;
- } else {
- "JKS"
- }
- }
+
+ protected def getKeyStoreType(context: BundleContext) = {
+ val property = context.getProperty(ServiceActivator.CONTEXT_PROPERTY_KEYSTORE_TYPE);
+ if (property != null) {
+ property;
+ } else {
+ "JKS"
+ }
+ }
- protected def getKeyStorePath(context: BundleContext) = {
- val property = context.getProperty(ServiceActivator.CONTEXT_PROPERTY_KEYSTORE_PATH);
- if (property != null) {
- property;
- } else {
- new File(new File(System.getProperty("user.home")), ".keystore").getAbsolutePath
- }
- }
+ protected def getKeyStorePath(context: BundleContext) = {
+ val property = context.getProperty(ServiceActivator.CONTEXT_PROPERTY_KEYSTORE_PATH);
+ if (property != null) {
+ property;
+ } else {
+ new File(new File(System.getProperty("user.home")), ".keystore").getAbsolutePath
+ }
+ }
- protected def getKeyStorePassword(context: BundleContext) = {
- val property = context.getProperty(ServiceActivator.CONTEXT_PROPERTY_KEYSTORE_PASSWORD);
- if (property != null) {
- property;
- } else {
- "password";
- }
- }
+ protected def getKeyStorePassword(context: BundleContext) = {
+ val property = context.getProperty(ServiceActivator.CONTEXT_PROPERTY_KEYSTORE_PASSWORD);
+ if (property != null) {
+ property;
+ } else {
+ "password";
+ }
+ }
}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/platform.security.foafssl/core/src/main/scala/org/apache/clerezza/foafssl/ssl/X509TrustManagerWrapperService.scala
----------------------------------------------------------------------
diff --git a/platform.security.foafssl/core/src/main/scala/org/apache/clerezza/foafssl/ssl/X509TrustManagerWrapperService.scala b/platform.security.foafssl/core/src/main/scala/org/apache/clerezza/foafssl/ssl/X509TrustManagerWrapperService.scala
index e418ed4..ad039b1 100644
--- a/platform.security.foafssl/core/src/main/scala/org/apache/clerezza/foafssl/ssl/X509TrustManagerWrapperService.scala
+++ b/platform.security.foafssl/core/src/main/scala/org/apache/clerezza/foafssl/ssl/X509TrustManagerWrapperService.scala
@@ -30,41 +30,41 @@ import org.apache.clerezza.foafssl.auth.X509Claim
object X509TrustManagerWrapperService {
- private val logger = LoggerFactory.getLogger(classOf[X509TrustManagerWrapperService])
+ private val logger = LoggerFactory.getLogger(classOf[X509TrustManagerWrapperService])
}
class X509TrustManagerWrapperService() extends X509TrustManagerWrapper {
- import X509TrustManagerWrapperService._
+ import X509TrustManagerWrapperService._
- override def wrapTrustManager(trustManager: X509TrustManager): X509TrustManager = {
+ override def wrapTrustManager(trustManager: X509TrustManager): X509TrustManager = {
- new TrustAllClientsWrappingTrustManager(trustManager) {
+ new TrustAllClientsWrappingTrustManager(trustManager) {
- //At this level we just check if there are webids
- override def checkClientTrusted(chain: Array[X509Certificate], authType: String): Unit = {
- try {
- val webIdUriRefs = X509Claim.getClaimedWebIds(chain(0))
- if (webIdUriRefs.isEmpty) {
- trustManager.checkClientTrusted(chain, authType)
- }
- return
+ //At this level we just check if there are webids
+ override def checkClientTrusted(chain: Array[X509Certificate], authType: String): Unit = {
+ try {
+ val webIdUriRefs = X509Claim.getClaimedWebIds(chain(0))
+ if (webIdUriRefs.isEmpty) {
+ trustManager.checkClientTrusted(chain, authType)
+ }
+ return
- } catch {
- //todo: this should be more clever, only displaying full stack trace if requested
- //todo: currently could be a denial of service attack - by filling up your hard drive
- case ex: Throwable => {
- logger.info("can't check client", ex)
- throw new CertificateException("cannot check client" + ex.getMessage);
- }
- }
- }
- }
- }
+ } catch {
+ //todo: this should be more clever, only displaying full stack trace if requested
+ //todo: currently could be a denial of service attack - by filling up your hard drive
+ case ex: Throwable => {
+ logger.info("can't check client", ex)
+ throw new CertificateException("cannot check client" + ex.getMessage);
+ }
+ }
+ }
+ }
+ }
- protected def activate(context: ComponentContext) = { }
+ protected def activate(context: ComponentContext) = { }
}
-
\ No newline at end of file
+
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/platform.security.foafssl/test/src/main/scala/org/apache/clerezza/foafssl/test/WebIDTester.scala
----------------------------------------------------------------------
diff --git a/platform.security.foafssl/test/src/main/scala/org/apache/clerezza/foafssl/test/WebIDTester.scala b/platform.security.foafssl/test/src/main/scala/org/apache/clerezza/foafssl/test/WebIDTester.scala
index 42fdda0..1868112 100644
--- a/platform.security.foafssl/test/src/main/scala/org/apache/clerezza/foafssl/test/WebIDTester.scala
+++ b/platform.security.foafssl/test/src/main/scala/org/apache/clerezza/foafssl/test/WebIDTester.scala
@@ -65,606 +65,606 @@ class WebIDTester {
protected def activate(componentContext: ComponentContext) = {
- // configure(componentContext.getBundleContext(), "profile-staticweb");
+ // configure(componentContext.getBundleContext(), "profile-staticweb");
}
- /**
- * don't bother converting to rdf here for the moment.
- */
+ /**
+ * don't bother converting to rdf here for the moment.
+ */
@GET
@Produces(Array("application/xhtml","text/html"))
def getTestMe(): GraphNode = {
val resultNode: GraphNode = new GraphNode(new BNode(),new SimpleMGraph())
resultNode.addProperty(RDF.`type`, testCls)
- resultNode.addProperty(RDF.`type`,PLATFORM.HeadedPage)
+ resultNode.addProperty(RDF.`type`,PLATFORM.HeadedPage)
return resultNode
}
- @GET
- @Produces(Array("text/n3","text/rdf+n3","text/turtle"))
- @Path("n3")
- def getTestMe_N3(): TripleCollection = getTestMeRDF()
-
- @GET
- def getTestMeRDF(): TripleCollection = {
- val certTester = new CertTester(UserUtil.getCurrentSubject(), webIdGraphsService)
- certTester.runTests()
- return certTester.toRdf()
- }
-
- @GET
- @Path("x509")
- @Produces(Array("text/plain"))
- def getTestX509(): String = {
- val subject = UserUtil.getCurrentSubject();
- val creds = subject.getPublicCredentials
+ @GET
+ @Produces(Array("text/n3","text/rdf+n3","text/turtle"))
+ @Path("n3")
+ def getTestMe_N3(): TripleCollection = getTestMeRDF()
+
+ @GET
+ def getTestMeRDF(): TripleCollection = {
+ val certTester = new CertTester(UserUtil.getCurrentSubject(), webIdGraphsService)
+ certTester.runTests()
+ return certTester.toRdf()
+ }
+
+ @GET
+ @Path("x509")
+ @Produces(Array("text/plain"))
+ def getTestX509(): String = {
+ val subject = UserUtil.getCurrentSubject();
+ val creds = subject.getPublicCredentials
if (creds.size == 0) return "No public keys found"
- return creds.iterator.next match {
- case x509: X509Claim => "X509 Certificate found. " + x509.cert.toString
- case other: Any => "no X509 certificate found: found " + other.getClass()
- }
+ return creds.iterator.next match {
+ case x509: X509Claim => "X509 Certificate found. " + x509.cert.toString
+ case other: Any => "no X509 certificate found: found " + other.getClass()
+ }
- }
+ }
- private var webIdGraphsService: WebIdGraphsService = null
- protected def bindWebIdGraphsService(webIdGraphsService: WebIdGraphsService): Unit = {
- this.webIdGraphsService = webIdGraphsService
- }
+ private var webIdGraphsService: WebIdGraphsService = null
+ protected def bindWebIdGraphsService(webIdGraphsService: WebIdGraphsService): Unit = {
+ this.webIdGraphsService = webIdGraphsService
+ }
- protected def unbindWebIdGraphsService(webIdGraphsService: WebIdGraphsService): Unit = {
- this.webIdGraphsService = null
- }
+ protected def unbindWebIdGraphsService(webIdGraphsService: WebIdGraphsService): Unit = {
+ this.webIdGraphsService = null
+ }
}
/** All the cert tests are placed here */
class CertTester(subj: Subject, webIdGraphsService: WebIdGraphsService) extends Assertor {
- import EARL.{passed, failed, cantTell, untested, inapplicable}
-
- val creds: scala.collection.mutable.Set[X509Claim] = subj.getPublicCredentials(classOf[X509Claim]);
- val now = new Date()
-
-
- def runTests() {
-
- import g._
- val thisDoc = (g.bnode.a(FOAF.Document) //there really has to be a way to get THIS doc url, to add relative urls to the graph
- -- DCTERMS.created --> now
- )
- //
- // Description of certificates and their public profileKeys
- //
- val x509claimRefs = for (claim <- creds) yield {
- val cert = g.bnode
- (
- cert.a(CERT.Certificate)
- -- CERT.base64der --> Base64.encode(claim.cert.getEncoded())
- )
-
- //
- // Assertion public key
- //
- val pubkey = claim.cert.getPublicKey
- val testCertKey = create(TEST.certificatePubkeyRecognised, cert)
-
- pubkey match {
- case rsa: RSAPublicKey => {
- val pk = (g.bnode.a(RSA.RSAPublicKey)
- -- RSA.modulus --> new TypedLiteralImpl(rsa.getModulus.toString(16), CERT.hex)
- -- RSA.public_exponent --> new TypedLiteralImpl(rsa.getPublicExponent.toString(10), CERT.int_)
- )
- cert -- CERT.principal_key --> pk
- val res = testCertKey.result;
- res.description = "Certificate contains RSA key which is recognised"
- res.outcome = EARL.passed
- res.pointer(pk.getNode.asInstanceOf[NonLiteral])
- }
- case _ => {
- testCertKey.result.description = "Certificate contains key that is not understood by WebID layer " +
- "Pubkey algorith is " + pubkey.getAlgorithm
- testCertKey.result.outcome = EARL.failed
- }
- }
-
- //
- // Assertion time stamp of certificate
- //
- val dateOkAss = create(TEST.certificateDateOk, cert)
- val notBefore = claim.cert.getNotBefore
- val notAfter = claim.cert.getNotAfter
-
- if (now.before(notBefore)) {
- dateOkAss.result("Certificate time is too early. Watch out this is often due to time " +
- "synchronisation issues accross servers", failed)
- } else if (now.after(notAfter)) {
- dateOkAss.result("Certificate validity time has expired. ", failed, thisDoc.getNode)
- } else {
- dateOkAss.result("Certificate time is valid", passed, thisDoc.getNode)
- }
-
- cert -> claim
- }
-
- //
- // certificate was provided
- //
- val eC = x509claimRefs.size > 0
- val ass = (
- g.bnode.a(EARL.Assertion)
- -- EARL.test --> TEST.certificateProvided
- -- EARL.result --> (g.bnode.a(EARL.TestResult)
- -- DC.description --> {if (eC) "Certificate available" else "No Certificate Found"}
- -- EARL.outcome --> {if (eC) EARL.passed else EARL.failed})
- )
- if (eC) ass -- EARL.subject -->> x509claimRefs.map(p => p._1)
- else return g
-
-
- //
- // WebID authentication succeeded
- //
- val principals = for (p <- subj.getPrincipals
- if p.isInstanceOf[WebIdPrincipal]) yield p.asInstanceOf[WebIdPrincipal]
- (g.bnode.a(EARL.Assertion)
- -- EARL.test --> TEST.webidAuthentication
- -- EARL.result --> (g.bnode.a(EARL.TestResult)
- -- DC.description --> {"found " + principals.size + " valid principals"}
- -- EARL.outcome --> {if (principals.size > 0) EARL.passed else EARL.failed}
- -- EARL.pointer -->> principals.map(p => p.webId)
- )
- -- EARL.subject -->> x509claimRefs.map(p => p._1)
- )
- import collection.JavaConversions._
-
- for ((certRef, claim) <- x509claimRefs) {
- for (widc <- claim.webidclaims) {
- import Verification._
- val webidAss = create(TEST.webidClaim,
- Seq(widc.webId, certRef)) //todo, we need to add a description of the profileKeys as found in the remote file
- val result = webidAss.result
- result.pointer(widc.webId)
- result.exceptions = widc.errors
- widc.verified match {
- case Verified => {
- result("claim for WebId " + widc.webId + " was verified", passed)
- claimTests(widc)
- }
- case Failed => {
- result("claim for WebID " + widc.webId + " failed", failed)
- claimTests(widc)
- }
- case Unverified => {
- result("claim for WebId " + widc.webId + " was not verified",untested)
- }
- case Unsupported => {
- result("this webid is unsupported ",cantTell)
- }
- }
- }
- }
- }
-
- // more detailed tester for claims that passed or failed
- // even tester that succeed could be just succeeding by chance (if public profileKeys are badly written out for eg)
- def claimTests(claim: WebIDClaim) {
- val sem: Option[GraphNode] = try {
- Some(new GraphNode(claim.webId, webIdGraphsService.getWebIdInfo(claim.webId).publicProfile)) //webProxy.fetchSemantics(claim.webId, Cache.CacheOnly)
- } catch {
- case e: NoSuchEntityException => None
- }
- val profileXst = create(TEST.profileGet, claim.webId)
-
- sem match {
- case Some(profile) => {
- if (profile.getGraph.size() > 0) {
- profileXst.result("Profile was fetched. The information about this is not yet very detailed" +
- " in Clerezza. Later will be able to give more details.", passed)
- testKeys(profile /- CERT.identity)
-
- } else {
- profileXst.result("Profile seems to have been fetched but it contains very little" +
- " information. There may be other issues too", cantTell)
- }
-
- }
- case None => {
- profileXst.result("No profile was found or is in store", failed)
- }
- }
-
- }
-
- /**
- * @param exponentNode the node in the remote profile descrbing the modulus - can be a literal or a resource
- * @param litRef a resource to the literal as described in the test graph
- * @return true, if the modulus is recognised as parsing
- */
- def testRSAModulus(modulusNode: RichGraphNode, litRef: Resource):Boolean = {
- val asrtKeyModulusLit = create(TEST.pubkeyRSAModulusLiteral, litRef)
- val asrtKeyMod = create(TEST.pubkeyRSAModulus, litRef)
- val asrtKeyModulusOldFunc = create(TEST.pubkeyRSAModulusOldFunctional,litRef)
- var result = false
-
- modulusNode! match {
- case ref: NonLiteral => {
- asrtKeyModulusLit.result("the modulus of this key is not described directly as" +
- " a literal. It is currently the preferred practice.", failed)
- val hex = modulusNode / CERT.hex
- if (hex.size == 0) {
- asrtKeyModulusOldFunc.result("no hexadecimal value for the modulus found", failed)
- } else if (hex.size > 1) {
- asrtKeyModulusOldFunc.result((hex.size - 1) + " too many hexadecimal values for " +
- "the modulus found. 1 is enough. If the numbers don't end up matching this is very likely" +
- " to cause random behavior ", failed)
- } else {
- asrtKeyModulusOldFunc.result("one hex value for modulus", EARL.passed)
- val kmres = asrtKeyMod.result
- hex(0) ! match {
- case refh: NonLiteral => {
- asrtKeyMod.result("The modulus is using old notation and it's hex is not " +
- "a literal. Going further would require reasoning engines which it is currently unlikely" +
- "many sites have access to.", failed)
- }
- case lith: Literal => {
- lith match {
- case plainLit: PlainLiteral => {
- if (plainLit.getLanguage != null)
- kmres("keymodulus exists and is parseable", passed)
- else
- kmres("keymodulus exists and is parseable, but has a language tag", passed)
- result = true
- }
- case typedLit: TypedLiteral => {
- if (typedLit.getDataType == null ||
- XSD.string == typedLit.getDataType) {
- kmres("keymodulus exists and is parseable", passed)
- result = true
- } else {
- kmres("keymodulus exists but does not have a string type", failed)
- }
- }
- case lit => {
- // cert:hex cannot be mistyped, since anything that is odd in the string is
- //removed
- kmres("keymodulus exists and is parseable", passed)
- result = true
- }
- }
- }
- }
- }
-
- }
- case numLit: Literal => {
- val reskeyModLit = asrtKeyModulusLit.result
- numLit match {
- case tl: TypedLiteral => tl.getDataType match {
- case CERT.int_ => {
- try {
- BigInt(tl.getLexicalForm)
- reskeyModLit("Modulus is of type cert:int. It parsed ok.", passed, tl)
- result = true
- } catch {
- case e: NumberFormatException => {
- reskeyModLit("Modulus cert:int failed to parse as one", failed, tl)
- }
- }
- }
- case CERT.decimal => {
- //todo: need to add cert:decimal parsing flexibility to ontology
- reskeyModLit("Modulus is of type cert:decimal. It always parses ok", passed, tl)
- result = true
- }
- case CERT.hex => {
- result = true
- reskeyModLit("Modulus is of type cert:hex. It will always parse to a positive number.", passed, tl)
- }
- case XSD.int_ => {
- try {
- BigInt(tl.getLexicalForm)
- reskeyModLit("Modulus is of type xsd:int. It parsed but it is certainly too small for " +
- "a modulus", failed)
- } catch {
- case e: NumberFormatException => {
- reskeyModLit("Modulus cert:decimal is failed to parse", failed, tl)
- }
- }
- }
- case XSD.base64Binary => reskeyModLit("Base 64 binaries are not numbers. If you wish to have " +
- "a base64 integer notation let the WebId Group know. We can define one easily.", failed, tl)
- case XSD.hexBinary => reskeyModLit("Base hex binary literals are not a numbers. If you wish to have a hex " +
- " integer notation use the " + CERT.hex +
- " relation. It is easier for people to write out.", failed, tl)
- case XSD.nonNegativeInteger => {
- try {
- val bi = BigInt(tl.getLexicalForm)
- if (bi >= 0) {
- reskeyModLit("Modulus is declared to be of type non-negative integer and it is", passed, tl)
- result = true
- } else {
- reskeyModLit("Modulus is declared to be of type non-negative integer but it is negative", failed, tl)
- }
- } catch {
- case e: NumberFormatException => {
- reskeyModLit("Modulus xsd:int is very likely too short a number for a modulus. It also " +
- "failed to parse as one", failed, tl)
- }
- }
-
- }
- case XSD.integer => {
- try {
- BigInt(tl.getLexicalForm)
- reskeyModLit("Modulus is of type xsd:integer. It parsed.", passed, tl)
- result = true
- } catch {
- case e: NumberFormatException => {
- reskeyModLit("Modulus xsd:integer is failed to parse", failed, tl)
- }
- }
-
- }
- case XSD.positiveInteger => {
- try {
- val bi = BigInt(tl.getLexicalForm)
- if (bi > 0) {
- reskeyModLit("Modulus is declared to be of type positive integer and it is", passed, tl)
- result = true
- } else if (bi == 0) {
- reskeyModLit("Modulus is 0 which is certainly too small", failed, tl)
- } else {
- reskeyModLit("Modulus is declared to be of type positive integer but it is not", failed, tl)
- }
- } catch {
- case e: NumberFormatException => {
- reskeyModLit("Modulus xsd:positiveInteger failed to parse", failed, tl)
- }
- }
-
- }
- case littype => reskeyModLit("We don't know how to interpret numbers of type " + littype +
- "It would be better to use either cert:hex or cert:int", cantTell, tl)
- }
- case lit: Literal => reskeyModLit("The literal needs to be of a number type, not a string", failed, lit)
- }
- }
-
-
- //its ok, and do other modulus verification
- }
- return result
- }
-
-
- /**
- * @param exponentNode the node in the remote profile describing the expontent - can be a literal or a resource
- * @param litRef a reference to the literal as described in the test graph
- * @return true if the exponent parses correctly
- */
- def testRSAExp(exponentNode: RichGraphNode, litRef: Resource) : Boolean = {
- val asrtKeyExpLit = create(TEST.pubkeyRSAExponentLiteral, litRef)
- val asrtKeyExp = create(TEST.pubkeyRSAExponent, litRef)
- val asrtKeyExpOldFunc = create(TEST.pubkeyRSAExponentOldFunctional,litRef)
- var result = false
-
- exponentNode! match {
- case ref: NonLiteral => {
- asrtKeyExpLit.result("the exponent of this key is not described directly as" +
- " a literal. It is currently the preferred practice.", failed)
- val decml = exponentNode / CERT.decimal
- if (decml.size == 0) {
- asrtKeyExpOldFunc.result("no decimal value for the exponent found", failed)
- } else if (decml.size > 1) {
- asrtKeyExpOldFunc.result((decml.size - 1) + " too many decimal values for " +
- "the exponent found. 1 is enough. If the numbers don't end up matching this is very likely" +
- " to cause random behavior ", failed)
- } else {
- asrtKeyExpOldFunc.result("one hex value for modulus", EARL.passed)
- val kExpres = asrtKeyExp.result
- decml(0) ! match {
- case refh: NonLiteral => {
- asrtKeyExp.result("The exponent is using old notation and it's cert:decimal relation is not " +
- "to a literal. Going further would require reasoning engines which it is currently unlikely" +
- "many sites have access to.", failed)
- }
- case lith: Literal => {
- lith match {
- case plainLit: PlainLiteral => {
- if (plainLit.getLanguage != null)
- kExpres("key exponent exists and is parseable", passed)
- else
- kExpres("key exponent exists and is parseable, but has a language tag", passed)
- result = true
- }
- case typedLit: TypedLiteral => {
- if (typedLit.getDataType == null ||
- XSD.string == typedLit.getDataType) {
- kExpres("keymodulus exists and is parseable", passed)
- result = true
- } else {
- kExpres("keymodulus exists but does not have a string type", failed)
- }
- }
- case lit => {
- //todo: can cert:int not be mistyped?
- kExpres("keymodulus exists and is parseable", passed)
- }
- }
- }
- }
- }
-
- }
- case numLit: Literal => {
- val reskeyExpLit = asrtKeyExpLit.result
- numLit match {
- case tl: TypedLiteral => tl.getDataType match {
- case CERT.int_ => {
- try {
- BigInt(tl.getLexicalForm)
- reskeyExpLit("Exponent is of type cert:int. It parsed ok.", passed, tl)
- result = true
- } catch {
- case e: NumberFormatException => {
- reskeyExpLit("Exponent cert:int failed to parse as one", failed, tl)
- }
- }
- }
- case CERT.hex => {
- reskeyExpLit("Exponent is of type cert:hex. It will always parse to a positive number.", passed, tl)
- result = true
- }
- case CERT.decimal => {
- try {
- BigInt(tl.getLexicalForm)
- reskeyExpLit("Exponent is of type xsd:int. It parsed ok.", passed)
- result = true
- } catch {
- case e: NumberFormatException => {
- reskeyExpLit("Exeponent of type cert:decimal failed to parse", failed, tl)
- }
- }
- }
- case XSD.base64Binary => reskeyExpLit("Base 64 binaries are not numbers. If you wish to have " +
- "a base64 integer notation let the WebId Group know. We can define one easily.", failed, tl)
- case XSD.hexBinary => reskeyExpLit("Base hex binary literals are not a numbers. If you wish to have a hex " +
- " integer notation use the " + CERT.hex +
- " relation. It is easier for people to write out.", failed, tl)
- case XSD.nonNegativeInteger => {
- try {
- val bi = BigInt(tl.getLexicalForm)
- if (bi >= 0) {
- reskeyExpLit("Exponent is declared to be of type non-negative integer and it is", passed, tl)
- result = true
- } else {
- reskeyExpLit("Exponent is declared to be of type non-negative integer but it is negative", failed, tl)
- }
- } catch {
- case e: NumberFormatException => {
- reskeyExpLit("Exponent xsd:nonNegativeInteger failed to parse as one", failed, tl)
- }
- }
-
- }
- case XSD.integer => {
- try {
- BigInt(tl.getLexicalForm)
- reskeyExpLit("Exponent is of type xsd:integer. It parsed.", passed, tl)
- result = true
- } catch {
- case e: NumberFormatException => {
- reskeyExpLit("Exponent xsd:integer is failed to parse", failed, tl)
- }
- }
-
- }
- case XSD.positiveInteger => {
- try {
- val bi = BigInt(tl.getLexicalForm)
- if (bi > 0) {
- reskeyExpLit("Exponent is declared to be of type positive integer and it is", passed, tl)
- result = true
- } else if (bi == 0) {
- reskeyExpLit("Exponent is 0 which is certainly too small", failed, tl)
- } else {
- reskeyExpLit("Exponent is declared to be of type positive integer but it is not", failed, tl)
- }
- } catch {
- case e: NumberFormatException => {
- reskeyExpLit("Exponent xsd:positiveInteger failed to parse", failed, tl)
- }
- }
-
- }
- case littype => reskeyExpLit("We don't know how to interpret numbers of type " + littype +
- "It would be better to use either cert:hex or cert:int", cantTell, tl)
- }
- case lit: Literal => reskeyExpLit("The literal needs to be of a number type, not a string", failed, lit)
- }
- }
- }
- return result
- }
-
-
- def testKeys(profileKeys: CollectedIter[RichGraphNode]) {
-
- for (pkey <- profileKeys) yield {
- //
- //create a pointer to this key, so that future tester can refer to it
- //
- val graph: Graph = pkey.getNodeContext
- val sout = Serializer.getInstance()
- val out = new ByteArrayOutputStream(512)
- sout.serialize(out, graph, "text/rdf+n3")
- val n3String = out.toString("UTF-8")
- //todo: turtle mime type literal?
- import g._
- val keylit: GraphNode = g.bnode -- OWL.sameAs --> (n3String^^"http://example.com/turtle".uri)
-
-
- //
- // some of the tester we will complete here
- //
- val asrtKeyModulusFunc = create(TEST.pubkeyRSAModulusFunctional, keylit.getNode)
- val asrtKeyExpoFunc = create(TEST.pubkeyRSAExponentFunctional, keylit.getNode)
- val asrtWffkey = create(TEST.profileWellFormedKey, keylit.getNode)
-
-
- var claimsTobeRsaKey = pkey.hasProperty(RDF.`type`, RSA.RSAPublicKey)
-
- val mods = pkey / RSA.modulus
- val exps = pkey / RSA.public_exponent
-
- claimsTobeRsaKey = claimsTobeRsaKey || mods.size > 0 || exps.size > 0
-
- if (!claimsTobeRsaKey) {
- asrtWffkey.result("Do not recognise the type of this key", cantTell)
- }
-
- var rsaExpOk, rsaModOk: Boolean = false
-
- if (mods.size == 0) {
- if (claimsTobeRsaKey) {
- asrtKeyModulusFunc.result("Missing modulus in RSA key", failed)
- }
- else {
- asrtKeyModulusFunc.result("Can't tell if this is an RSA key", cantTell)
- }
- } else if (mods.size > 1) {
- asrtKeyModulusFunc.result("Found more than one modulus. Careful, unless the numbers are" +
- " exactly the same, there is a danger of erratic behavior", failed)
- } else {
- asrtKeyModulusFunc.result("Found one Modulus", passed)
-
- rsaModOk = testRSAModulus(mods, keylit.getNode)
- }
-
- if (exps.size == 0) {
- if (claimsTobeRsaKey) {
- asrtKeyExpoFunc.result("Missing exponent in RSA key", failed)
- }
- else {
- asrtKeyExpoFunc.result("Can't tell if this is an RSA key", cantTell)
- }
- } else if (exps.size > 1) {
- asrtKeyExpoFunc.result("Found more than one exponents. Careful, unless the numbers are" +
- " exactly the same, there is a danger of erratic behavior", failed)
- //we could have a problem
- } else {
- asrtKeyExpoFunc.result("Found one Modulus", passed)
- rsaExpOk = testRSAExp(mods, keylit.getNode)
- }
-
- if (rsaExpOk && rsaModOk) {
- asrtWffkey.result("Modulus and Exponent of key good", passed)
- }
-
- }
- }
+ import EARL.{passed, failed, cantTell, untested, inapplicable}
+
+ val creds: scala.collection.mutable.Set[X509Claim] = subj.getPublicCredentials(classOf[X509Claim]);
+ val now = new Date()
+
+
+ def runTests() {
+
+ import g._
+ val thisDoc = (g.bnode.a(FOAF.Document) //there really has to be a way to get THIS doc url, to add relative urls to the graph
+ -- DCTERMS.created --> now
+ )
+ //
+ // Description of certificates and their public profileKeys
+ //
+ val x509claimRefs = for (claim <- creds) yield {
+ val cert = g.bnode
+ (
+ cert.a(CERT.Certificate)
+ -- CERT.base64der --> Base64.encode(claim.cert.getEncoded())
+ )
+
+ //
+ // Assertion public key
+ //
+ val pubkey = claim.cert.getPublicKey
+ val testCertKey = create(TEST.certificatePubkeyRecognised, cert)
+
+ pubkey match {
+ case rsa: RSAPublicKey => {
+ val pk = (g.bnode.a(RSA.RSAPublicKey)
+ -- RSA.modulus --> new TypedLiteralImpl(rsa.getModulus.toString(16), CERT.hex)
+ -- RSA.public_exponent --> new TypedLiteralImpl(rsa.getPublicExponent.toString(10), CERT.int_)
+ )
+ cert -- CERT.principal_key --> pk
+ val res = testCertKey.result;
+ res.description = "Certificate contains RSA key which is recognised"
+ res.outcome = EARL.passed
+ res.pointer(pk.getNode.asInstanceOf[NonLiteral])
+ }
+ case _ => {
+ testCertKey.result.description = "Certificate contains key that is not understood by WebID layer " +
+ "Pubkey algorith is " + pubkey.getAlgorithm
+ testCertKey.result.outcome = EARL.failed
+ }
+ }
+
+ //
+ // Assertion time stamp of certificate
+ //
+ val dateOkAss = create(TEST.certificateDateOk, cert)
+ val notBefore = claim.cert.getNotBefore
+ val notAfter = claim.cert.getNotAfter
+
+ if (now.before(notBefore)) {
+ dateOkAss.result("Certificate time is too early. Watch out this is often due to time " +
+ "synchronisation issues accross servers", failed)
+ } else if (now.after(notAfter)) {
+ dateOkAss.result("Certificate validity time has expired. ", failed, thisDoc.getNode)
+ } else {
+ dateOkAss.result("Certificate time is valid", passed, thisDoc.getNode)
+ }
+
+ cert -> claim
+ }
+
+ //
+ // certificate was provided
+ //
+ val eC = x509claimRefs.size > 0
+ val ass = (
+ g.bnode.a(EARL.Assertion)
+ -- EARL.test --> TEST.certificateProvided
+ -- EARL.result --> (g.bnode.a(EARL.TestResult)
+ -- DC.description --> {if (eC) "Certificate available" else "No Certificate Found"}
+ -- EARL.outcome --> {if (eC) EARL.passed else EARL.failed})
+ )
+ if (eC) ass -- EARL.subject -->> x509claimRefs.map(p => p._1)
+ else return g
+
+
+ //
+ // WebID authentication succeeded
+ //
+ val principals = for (p <- subj.getPrincipals
+ if p.isInstanceOf[WebIdPrincipal]) yield p.asInstanceOf[WebIdPrincipal]
+ (g.bnode.a(EARL.Assertion)
+ -- EARL.test --> TEST.webidAuthentication
+ -- EARL.result --> (g.bnode.a(EARL.TestResult)
+ -- DC.description --> {"found " + principals.size + " valid principals"}
+ -- EARL.outcome --> {if (principals.size > 0) EARL.passed else EARL.failed}
+ -- EARL.pointer -->> principals.map(p => p.webId)
+ )
+ -- EARL.subject -->> x509claimRefs.map(p => p._1)
+ )
+ import collection.JavaConversions._
+
+ for ((certRef, claim) <- x509claimRefs) {
+ for (widc <- claim.webidclaims) {
+ import Verification._
+ val webidAss = create(TEST.webidClaim,
+ Seq(widc.webId, certRef)) //todo, we need to add a description of the profileKeys as found in the remote file
+ val result = webidAss.result
+ result.pointer(widc.webId)
+ result.exceptions = widc.errors
+ widc.verified match {
+ case Verified => {
+ result("claim for WebId " + widc.webId + " was verified", passed)
+ claimTests(widc)
+ }
+ case Failed => {
+ result("claim for WebID " + widc.webId + " failed", failed)
+ claimTests(widc)
+ }
+ case Unverified => {
+ result("claim for WebId " + widc.webId + " was not verified",untested)
+ }
+ case Unsupported => {
+ result("this webid is unsupported ",cantTell)
+ }
+ }
+ }
+ }
+ }
+
+ // more detailed tester for claims that passed or failed
+ // even tester that succeed could be just succeeding by chance (if public profileKeys are badly written out for eg)
+ def claimTests(claim: WebIDClaim) {
+ val sem: Option[GraphNode] = try {
+ Some(new GraphNode(claim.webId, webIdGraphsService.getWebIdInfo(claim.webId).publicProfile)) //webProxy.fetchSemantics(claim.webId, Cache.CacheOnly)
+ } catch {
+ case e: NoSuchEntityException => None
+ }
+ val profileXst = create(TEST.profileGet, claim.webId)
+
+ sem match {
+ case Some(profile) => {
+ if (profile.getGraph.size() > 0) {
+ profileXst.result("Profile was fetched. The information about this is not yet very detailed" +
+ " in Clerezza. Later will be able to give more details.", passed)
+ testKeys(profile /- CERT.identity)
+
+ } else {
+ profileXst.result("Profile seems to have been fetched but it contains very little" +
+ " information. There may be other issues too", cantTell)
+ }
+
+ }
+ case None => {
+ profileXst.result("No profile was found or is in store", failed)
+ }
+ }
+
+ }
+
+ /**
+ * @param exponentNode the node in the remote profile descrbing the modulus - can be a literal or a resource
+ * @param litRef a resource to the literal as described in the test graph
+ * @return true, if the modulus is recognised as parsing
+ */
+ def testRSAModulus(modulusNode: RichGraphNode, litRef: Resource):Boolean = {
+ val asrtKeyModulusLit = create(TEST.pubkeyRSAModulusLiteral, litRef)
+ val asrtKeyMod = create(TEST.pubkeyRSAModulus, litRef)
+ val asrtKeyModulusOldFunc = create(TEST.pubkeyRSAModulusOldFunctional,litRef)
+ var result = false
+
+ modulusNode! match {
+ case ref: NonLiteral => {
+ asrtKeyModulusLit.result("the modulus of this key is not described directly as" +
+ " a literal. It is currently the preferred practice.", failed)
+ val hex = modulusNode / CERT.hex
+ if (hex.size == 0) {
+ asrtKeyModulusOldFunc.result("no hexadecimal value for the modulus found", failed)
+ } else if (hex.size > 1) {
+ asrtKeyModulusOldFunc.result((hex.size - 1) + " too many hexadecimal values for " +
+ "the modulus found. 1 is enough. If the numbers don't end up matching this is very likely" +
+ " to cause random behavior ", failed)
+ } else {
+ asrtKeyModulusOldFunc.result("one hex value for modulus", EARL.passed)
+ val kmres = asrtKeyMod.result
+ hex(0) ! match {
+ case refh: NonLiteral => {
+ asrtKeyMod.result("The modulus is using old notation and it's hex is not " +
+ "a literal. Going further would require reasoning engines which it is currently unlikely" +
+ "many sites have access to.", failed)
+ }
+ case lith: Literal => {
+ lith match {
+ case plainLit: PlainLiteral => {
+ if (plainLit.getLanguage != null)
+ kmres("keymodulus exists and is parseable", passed)
+ else
+ kmres("keymodulus exists and is parseable, but has a language tag", passed)
+ result = true
+ }
+ case typedLit: TypedLiteral => {
+ if (typedLit.getDataType == null ||
+ XSD.string == typedLit.getDataType) {
+ kmres("keymodulus exists and is parseable", passed)
+ result = true
+ } else {
+ kmres("keymodulus exists but does not have a string type", failed)
+ }
+ }
+ case lit => {
+ // cert:hex cannot be mistyped, since anything that is odd in the string is
+ //removed
+ kmres("keymodulus exists and is parseable", passed)
+ result = true
+ }
+ }
+ }
+ }
+ }
+
+ }
+ case numLit: Literal => {
+ val reskeyModLit = asrtKeyModulusLit.result
+ numLit match {
+ case tl: TypedLiteral => tl.getDataType match {
+ case CERT.int_ => {
+ try {
+ BigInt(tl.getLexicalForm)
+ reskeyModLit("Modulus is of type cert:int. It parsed ok.", passed, tl)
+ result = true
+ } catch {
+ case e: NumberFormatException => {
+ reskeyModLit("Modulus cert:int failed to parse as one", failed, tl)
+ }
+ }
+ }
+ case CERT.decimal => {
+ //todo: need to add cert:decimal parsing flexibility to ontology
+ reskeyModLit("Modulus is of type cert:decimal. It always parses ok", passed, tl)
+ result = true
+ }
+ case CERT.hex => {
+ result = true
+ reskeyModLit("Modulus is of type cert:hex. It will always parse to a positive number.", passed, tl)
+ }
+ case XSD.int_ => {
+ try {
+ BigInt(tl.getLexicalForm)
+ reskeyModLit("Modulus is of type xsd:int. It parsed but it is certainly too small for " +
+ "a modulus", failed)
+ } catch {
+ case e: NumberFormatException => {
+ reskeyModLit("Modulus cert:decimal is failed to parse", failed, tl)
+ }
+ }
+ }
+ case XSD.base64Binary => reskeyModLit("Base 64 binaries are not numbers. If you wish to have " +
+ "a base64 integer notation let the WebId Group know. We can define one easily.", failed, tl)
+ case XSD.hexBinary => reskeyModLit("Base hex binary literals are not a numbers. If you wish to have a hex " +
+ " integer notation use the " + CERT.hex +
+ " relation. It is easier for people to write out.", failed, tl)
+ case XSD.nonNegativeInteger => {
+ try {
+ val bi = BigInt(tl.getLexicalForm)
+ if (bi >= 0) {
+ reskeyModLit("Modulus is declared to be of type non-negative integer and it is", passed, tl)
+ result = true
+ } else {
+ reskeyModLit("Modulus is declared to be of type non-negative integer but it is negative", failed, tl)
+ }
+ } catch {
+ case e: NumberFormatException => {
+ reskeyModLit("Modulus xsd:int is very likely too short a number for a modulus. It also " +
+ "failed to parse as one", failed, tl)
+ }
+ }
+
+ }
+ case XSD.integer => {
+ try {
+ BigInt(tl.getLexicalForm)
+ reskeyModLit("Modulus is of type xsd:integer. It parsed.", passed, tl)
+ result = true
+ } catch {
+ case e: NumberFormatException => {
+ reskeyModLit("Modulus xsd:integer is failed to parse", failed, tl)
+ }
+ }
+
+ }
+ case XSD.positiveInteger => {
+ try {
+ val bi = BigInt(tl.getLexicalForm)
+ if (bi > 0) {
+ reskeyModLit("Modulus is declared to be of type positive integer and it is", passed, tl)
+ result = true
+ } else if (bi == 0) {
+ reskeyModLit("Modulus is 0 which is certainly too small", failed, tl)
+ } else {
+ reskeyModLit("Modulus is declared to be of type positive integer but it is not", failed, tl)
+ }
+ } catch {
+ case e: NumberFormatException => {
+ reskeyModLit("Modulus xsd:positiveInteger failed to parse", failed, tl)
+ }
+ }
+
+ }
+ case littype => reskeyModLit("We don't know how to interpret numbers of type " + littype +
+ "It would be better to use either cert:hex or cert:int", cantTell, tl)
+ }
+ case lit: Literal => reskeyModLit("The literal needs to be of a number type, not a string", failed, lit)
+ }
+ }
+
+
+ //its ok, and do other modulus verification
+ }
+ return result
+ }
+
+
+ /**
+ * @param exponentNode the node in the remote profile describing the expontent - can be a literal or a resource
+ * @param litRef a reference to the literal as described in the test graph
+ * @return true if the exponent parses correctly
+ */
+ def testRSAExp(exponentNode: RichGraphNode, litRef: Resource) : Boolean = {
+ val asrtKeyExpLit = create(TEST.pubkeyRSAExponentLiteral, litRef)
+ val asrtKeyExp = create(TEST.pubkeyRSAExponent, litRef)
+ val asrtKeyExpOldFunc = create(TEST.pubkeyRSAExponentOldFunctional,litRef)
+ var result = false
+
+ exponentNode! match {
+ case ref: NonLiteral => {
+ asrtKeyExpLit.result("the exponent of this key is not described directly as" +
+ " a literal. It is currently the preferred practice.", failed)
+ val decml = exponentNode / CERT.decimal
+ if (decml.size == 0) {
+ asrtKeyExpOldFunc.result("no decimal value for the exponent found", failed)
+ } else if (decml.size > 1) {
+ asrtKeyExpOldFunc.result((decml.size - 1) + " too many decimal values for " +
+ "the exponent found. 1 is enough. If the numbers don't end up matching this is very likely" +
+ " to cause random behavior ", failed)
+ } else {
+ asrtKeyExpOldFunc.result("one hex value for modulus", EARL.passed)
+ val kExpres = asrtKeyExp.result
+ decml(0) ! match {
+ case refh: NonLiteral => {
+ asrtKeyExp.result("The exponent is using old notation and it's cert:decimal relation is not " +
+ "to a literal. Going further would require reasoning engines which it is currently unlikely" +
+ "many sites have access to.", failed)
+ }
+ case lith: Literal => {
+ lith match {
+ case plainLit: PlainLiteral => {
+ if (plainLit.getLanguage != null)
+ kExpres("key exponent exists and is parseable", passed)
+ else
+ kExpres("key exponent exists and is parseable, but has a language tag", passed)
+ result = true
+ }
+ case typedLit: TypedLiteral => {
+ if (typedLit.getDataType == null ||
+ XSD.string == typedLit.getDataType) {
+ kExpres("keymodulus exists and is parseable", passed)
+ result = true
+ } else {
+ kExpres("keymodulus exists but does not have a string type", failed)
+ }
+ }
+ case lit => {
+ //todo: can cert:int not be mistyped?
+ kExpres("keymodulus exists and is parseable", passed)
+ }
+ }
+ }
+ }
+ }
+
+ }
+ case numLit: Literal => {
+ val reskeyExpLit = asrtKeyExpLit.result
+ numLit match {
+ case tl: TypedLiteral => tl.getDataType match {
+ case CERT.int_ => {
+ try {
+ BigInt(tl.getLexicalForm)
+ reskeyExpLit("Exponent is of type cert:int. It parsed ok.", passed, tl)
+ result = true
+ } catch {
+ case e: NumberFormatException => {
+ reskeyExpLit("Exponent cert:int failed to parse as one", failed, tl)
+ }
+ }
+ }
+ case CERT.hex => {
+ reskeyExpLit("Exponent is of type cert:hex. It will always parse to a positive number.", passed, tl)
+ result = true
+ }
+ case CERT.decimal => {
+ try {
+ BigInt(tl.getLexicalForm)
+ reskeyExpLit("Exponent is of type xsd:int. It parsed ok.", passed)
+ result = true
+ } catch {
+ case e: NumberFormatException => {
+ reskeyExpLit("Exeponent of type cert:decimal failed to parse", failed, tl)
+ }
+ }
+ }
+ case XSD.base64Binary => reskeyExpLit("Base 64 binaries are not numbers. If you wish to have " +
+ "a base64 integer notation let the WebId Group know. We can define one easily.", failed, tl)
+ case XSD.hexBinary => reskeyExpLit("Base hex binary literals are not a numbers. If you wish to have a hex " +
+ " integer notation use the " + CERT.hex +
+ " relation. It is easier for people to write out.", failed, tl)
+ case XSD.nonNegativeInteger => {
+ try {
+ val bi = BigInt(tl.getLexicalForm)
+ if (bi >= 0) {
+ reskeyExpLit("Exponent is declared to be of type non-negative integer and it is", passed, tl)
+ result = true
+ } else {
+ reskeyExpLit("Exponent is declared to be of type non-negative integer but it is negative", failed, tl)
+ }
+ } catch {
+ case e: NumberFormatException => {
+ reskeyExpLit("Exponent xsd:nonNegativeInteger failed to parse as one", failed, tl)
+ }
+ }
+
+ }
+ case XSD.integer => {
+ try {
+ BigInt(tl.getLexicalForm)
+ reskeyExpLit("Exponent is of type xsd:integer. It parsed.", passed, tl)
+ result = true
+ } catch {
+ case e: NumberFormatException => {
+ reskeyExpLit("Exponent xsd:integer is failed to parse", failed, tl)
+ }
+ }
+
+ }
+ case XSD.positiveInteger => {
+ try {
+ val bi = BigInt(tl.getLexicalForm)
+ if (bi > 0) {
+ reskeyExpLit("Exponent is declared to be of type positive integer and it is", passed, tl)
+ result = true
+ } else if (bi == 0) {
+ reskeyExpLit("Exponent is 0 which is certainly too small", failed, tl)
+ } else {
+ reskeyExpLit("Exponent is declared to be of type positive integer but it is not", failed, tl)
+ }
+ } catch {
+ case e: NumberFormatException => {
+ reskeyExpLit("Exponent xsd:positiveInteger failed to parse", failed, tl)
+ }
+ }
+
+ }
+ case littype => reskeyExpLit("We don't know how to interpret numbers of type " + littype +
+ "It would be better to use either cert:hex or cert:int", cantTell, tl)
+ }
+ case lit: Literal => reskeyExpLit("The literal needs to be of a number type, not a string", failed, lit)
+ }
+ }
+ }
+ return result
+ }
+
+
+ def testKeys(profileKeys: CollectedIter[RichGraphNode]) {
+
+ for (pkey <- profileKeys) yield {
+ //
+ //create a pointer to this key, so that future tester can refer to it
+ //
+ val graph: Graph = pkey.getNodeContext
+ val sout = Serializer.getInstance()
+ val out = new ByteArrayOutputStream(512)
+ sout.serialize(out, graph, "text/rdf+n3")
+ val n3String = out.toString("UTF-8")
+ //todo: turtle mime type literal?
+ import g._
+ val keylit: GraphNode = g.bnode -- OWL.sameAs --> (n3String^^"http://example.com/turtle".uri)
+
+
+ //
+ // some of the tester we will complete here
+ //
+ val asrtKeyModulusFunc = create(TEST.pubkeyRSAModulusFunctional, keylit.getNode)
+ val asrtKeyExpoFunc = create(TEST.pubkeyRSAExponentFunctional, keylit.getNode)
+ val asrtWffkey = create(TEST.profileWellFormedKey, keylit.getNode)
+
+
+ var claimsTobeRsaKey = pkey.hasProperty(RDF.`type`, RSA.RSAPublicKey)
+
+ val mods = pkey / RSA.modulus
+ val exps = pkey / RSA.public_exponent
+
+ claimsTobeRsaKey = claimsTobeRsaKey || mods.size > 0 || exps.size > 0
+
+ if (!claimsTobeRsaKey) {
+ asrtWffkey.result("Do not recognise the type of this key", cantTell)
+ }
+
+ var rsaExpOk, rsaModOk: Boolean = false
+
+ if (mods.size == 0) {
+ if (claimsTobeRsaKey) {
+ asrtKeyModulusFunc.result("Missing modulus in RSA key", failed)
+ }
+ else {
+ asrtKeyModulusFunc.result("Can't tell if this is an RSA key", cantTell)
+ }
+ } else if (mods.size > 1) {
+ asrtKeyModulusFunc.result("Found more than one modulus. Careful, unless the numbers are" +
+ " exactly the same, there is a danger of erratic behavior", failed)
+ } else {
+ asrtKeyModulusFunc.result("Found one Modulus", passed)
+
+ rsaModOk = testRSAModulus(mods, keylit.getNode)
+ }
+
+ if (exps.size == 0) {
+ if (claimsTobeRsaKey) {
+ asrtKeyExpoFunc.result("Missing exponent in RSA key", failed)
+ }
+ else {
+ asrtKeyExpoFunc.result("Can't tell if this is an RSA key", cantTell)
+ }
+ } else if (exps.size > 1) {
+ asrtKeyExpoFunc.result("Found more than one exponents. Careful, unless the numbers are" +
+ " exactly the same, there is a danger of erratic behavior", failed)
+ //we could have a problem
+ } else {
+ asrtKeyExpoFunc.result("Found one Modulus", passed)
+ rsaExpOk = testRSAExp(mods, keylit.getNode)
+ }
+
+ if (rsaExpOk && rsaModOk) {
+ asrtWffkey.result("Modulus and Exponent of key good", passed)
+ }
+
+ }
+ }
}
/**
@@ -678,80 +678,80 @@ class CertTester(subj: Subject, webIdGraphsService: WebIdGraphsService) extends
*/
class Assertor {
- val g = new EzMGraph(new SimpleMGraph)
-
- var assertions: List[Assertion] = Nil
-
- def add(newAssertion: Assertion) = {
- assertions = newAssertion :: assertions
- newAssertion
- }
-
- def create(testName: UriRef, subjects: Seq[Resource]) = new Assertion(testName, subjects)
-
- def create(testName: UriRef, subject: Resource) = new Assertion(testName, Seq[Resource](subject))
-
- def toRdf(): TripleCollection = {
- for (test <- assertions) {
- test.toRdf()
- }
- g
- }
-
- class Assertion(testName: UriRef,
- subjects: Seq[Resource]) {
-
- //only add this runTests to the list of assertions if there is a result
- //this makes it easier to write code that keeps track of assertions, without ending up having to
- //publish all of them
- lazy val result = {
- add(this)
- new TstResult
- }
-
- import g._
- def toRdf(): GraphNode = (
- g.bnode.a(EARL.Assertion)
- -- EARL.test --> testName
- -- EARL.result --> result.toRdf()
- -- EARL.subject -->> subjects
- )
- }
-
- class TstResult {
- var description: String = _
- var outcome: UriRef = _
- var pointers: Seq[Resource] = Nil
- var exceptions: Iterable[java.lang.Throwable] = Nil
-
- def pointer(point: NonLiteral) {
- pointers = Seq(point)
- }
-
-
- // a method to deal with most usual case
- def apply(desc: String, success: UriRef) {
- description = desc
- outcome = success
- }
-
- def apply(desc: String, success: UriRef, pointer: Resource) {
- description = desc
- outcome = success
- pointers = Seq(pointer)
- }
-
-
- def toRdf(): GraphNode = {
- import g._
- (g.bnode.a(EARL.TestResult)
- -- DC.description --> description
- -- EARL.outcome --> outcome
- -- EARL.pointer -->> pointers
- -- EARL.info -->> { for (e <- exceptions) yield new PlainLiteralImpl(e.toString) }
- )
- }
-
- }
+ val g = new EzMGraph(new SimpleMGraph)
+
+ var assertions: List[Assertion] = Nil
+
+ def add(newAssertion: Assertion) = {
+ assertions = newAssertion :: assertions
+ newAssertion
+ }
+
+ def create(testName: UriRef, subjects: Seq[Resource]) = new Assertion(testName, subjects)
+
+ def create(testName: UriRef, subject: Resource) = new Assertion(testName, Seq[Resource](subject))
+
+ def toRdf(): TripleCollection = {
+ for (test <- assertions) {
+ test.toRdf()
+ }
+ g
+ }
+
+ class Assertion(testName: UriRef,
+ subjects: Seq[Resource]) {
+
+ //only add this runTests to the list of assertions if there is a result
+ //this makes it easier to write code that keeps track of assertions, without ending up having to
+ //publish all of them
+ lazy val result = {
+ add(this)
+ new TstResult
+ }
+
+ import g._
+ def toRdf(): GraphNode = (
+ g.bnode.a(EARL.Assertion)
+ -- EARL.test --> testName
+ -- EARL.result --> result.toRdf()
+ -- EARL.subject -->> subjects
+ )
+ }
+
+ class TstResult {
+ var description: String = _
+ var outcome: UriRef = _
+ var pointers: Seq[Resource] = Nil
+ var exceptions: Iterable[java.lang.Throwable] = Nil
+
+ def pointer(point: NonLiteral) {
+ pointers = Seq(point)
+ }
+
+
+ // a method to deal with most usual case
+ def apply(desc: String, success: UriRef) {
+ description = desc
+ outcome = success
+ }
+
+ def apply(desc: String, success: UriRef, pointer: Resource) {
+ description = desc
+ outcome = success
+ pointers = Seq(pointer)
+ }
+
+
+ def toRdf(): GraphNode = {
+ import g._
+ (g.bnode.a(EARL.TestResult)
+ -- DC.description --> description
+ -- EARL.outcome --> outcome
+ -- EARL.pointer -->> pointers
+ -- EARL.info -->> { for (e <- exceptions) yield new PlainLiteralImpl(e.toString) }
+ )
+ }
+
+ }
}
http://git-wip-us.apache.org/repos/asf/clerezza/blob/35448624/platform.security.foafssl/test/src/main/scala/org/apache/clerezza/foafssl/test/pages/WebIDClaimPg.scala
----------------------------------------------------------------------
diff --git a/platform.security.foafssl/test/src/main/scala/org/apache/clerezza/foafssl/test/pages/WebIDClaimPg.scala b/platform.security.foafssl/test/src/main/scala/org/apache/clerezza/foafssl/test/pages/WebIDClaimPg.scala
index 8bf32ed..890a9d7 100644
--- a/platform.security.foafssl/test/src/main/scala/org/apache/clerezza/foafssl/test/pages/WebIDClaimPg.scala
+++ b/platform.security.foafssl/test/src/main/scala/org/apache/clerezza/foafssl/test/pages/WebIDClaimPg.scala
@@ -42,21 +42,21 @@ import org.apache.clerezza.platform.users.WebIdGraphsService
*/
class WebIDClaimPg extends SRenderlet {
- def getRdfType() = WebIDTester.testCls
+ def getRdfType() = WebIDTester.testCls
- override def renderedPage(arguments: XmlResult.Arguments) = new XhtmlWebIDClaimPg(arguments, webIdGraphsService)
+ override def renderedPage(arguments: XmlResult.Arguments) = new XhtmlWebIDClaimPg(arguments, webIdGraphsService)
- //TODO a renderlet should not need services,
+ //TODO a renderlet should not need services,
- private var webIdGraphsService: WebIdGraphsService = null
+ private var webIdGraphsService: WebIdGraphsService = null
- protected def bindWebIdGraphsService(webIdGraphsService: WebIdGraphsService): Unit = {
- this.webIdGraphsService = webIdGraphsService
- }
+ protected def bindWebIdGraphsService(webIdGraphsService: WebIdGraphsService): Unit = {
+ this.webIdGraphsService = webIdGraphsService
+ }
- protected def unbindWebIdGraphsService(webIdGraphsService: WebIdGraphsService): Unit = {
- this.webIdGraphsService = null
- }
+ protected def unbindWebIdGraphsService(webIdGraphsService: WebIdGraphsService): Unit = {
+ this.webIdGraphsService = null
+ }
@@ -69,9 +69,9 @@ object XhtmlWebIDClaimPg {
class XhtmlWebIDClaimPg(arguments: XmlResult.Arguments, webIdGraphsService: WebIdGraphsService) extends XmlResult(arguments ) {
import XhtmlWebIDClaimPg._
- resultDocModifier.setTitle("WebId Tests");
- resultDocModifier.addNodes2Elem("tx-module", <h1>Test Panel</h1>);
- resultDocModifier.addNodes2Elem("tx-module-tabs-ol", <li class="tx-active"><a href="#">WebId Tester</a></li>);
+ resultDocModifier.setTitle("WebId Tests");
+ resultDocModifier.addNodes2Elem("tx-module", <h1>Test Panel</h1>);
+ resultDocModifier.addNodes2Elem("tx-module-tabs-ol", <li class="tx-active"><a href="#">WebId Tester</a></li>);
override def content = <div id="tx-content"> <h2>WebID Login Test Page</h2>
<p>The TLS connection was established. We do not test the basic TLS connection.</p>
@@ -81,7 +81,7 @@ class XhtmlWebIDClaimPg(arguments: XmlResult.Arguments, webIdGraphsService: WebI
if (creds.size==0) <p>No X509 credentials available.</p>
else for (cred <- creds) yield describeX509Claim(cred)
}
- <p>For very detailed test information to send to support <a href="WebId/n3">download this n3 file</a>.</p>
+ <p>For very detailed test information to send to support <a href="WebId/n3">download this n3 file</a>.</p>
</div>
@@ -144,97 +144,97 @@ class XhtmlWebIDClaimPg(arguments: XmlResult.Arguments, webIdGraphsService: WebI
</p>
def displayKey(key: RichGraphNode) = <span>
- {val errs = verifyKeyClosely(key)
- if (errs.size > 0) <ul>{errs}</ul>
- else scala.xml.Null
- }
- <pre>
- {val graph: Graph = key.getNodeContext
- val sout = Serializer.getInstance()
- val out = new ByteArrayOutputStream(1024)
- sout.serialize(out, graph, "text/rdf+n3")
- out.toString("UTF-8")}
- </pre>
+ {val errs = verifyKeyClosely(key)
+ if (errs.size > 0) <ul>{errs}</ul>
+ else scala.xml.Null
+ }
+ <pre>
+ {val graph: Graph = key.getNodeContext
+ val sout = Serializer.getInstance()
+ val out = new ByteArrayOutputStream(1024)
+ sout.serialize(out, graph, "text/rdf+n3")
+ out.toString("UTF-8")}
+ </pre>
</span>
- /**
- * test numbers written in the old style with non literals
- *
- * @param The node that is the number. Should be a non literal
- * @param The relation name to the string that identifies the number
- * @param The role of the number in the public key (modulus, exponent, ...)
- *
- */
- def nonLiteralNumTest(number: RichGraphNode, relToString: UriRef, numberRole: String ): NodeSeq = {
- val typeTest = number! match {
- case uri: UriRef => <li>Warning: your {numberRole} is a uri. The new spec requires this to be a literal.
- Uri found: {uri.getUnicodeString}</li>
- case _: BNode => <li>Warning: your {numberRole} is a blank node. The newer spec requires this to be a literal</li>
- }
- typeTest++
- {
- val hexs = number / relToString
- if (hexs.size > 1) {
- <li>WARNING: Your {numberRole} has more than one relation to a hexadecimal string. Unless both of those strings
- map to the same number, your identification experience will be very random</li>
- } else if (hexs.size == 0) {
- <li>WARNING: your {numberRole} has no decimal literal attached by the {relToString} relation</li>
- } else hexs! match {
- case bnode: NonLiteral => <li>Warning: Your {numberRole} has a relation to a non literal, where it should be a
- relation to a literal. It is possible that logically it all works out, but don't even expect a few engines to
- bother reflecting deeply on this. We don't check past here.</li>
- case lit: Literal => emptyxml
- }
- }
-
- }
-
- def literalNumTest(number: Literal): NodeSeq = {
- number match {
- case tl: TypedLiteral => tl.getDataType match {
- case CERT.int_ => emptyxml
- case CERT.hex => emptyxml
- case CERT.decimal => emptyxml
- case XSD.base64Binary => <li>Base 64 binary is not a number. If you wish to have a base64 integer notation
- let the WebId Group know</li>
- case XSD.hexBinary => <li>Base hex binary is not a number. If you wish to have a hex integer notation
- use the {CERT.hex} relation. It is easier for people to write out</li>
- case XSD.nonNegativeInteger => emptyxml
- case XSD.integer => emptyxml
- case XSD.positiveInteger => emptyxml
- case XSD.int_ => emptyxml
- case littype => <li>We don't know how to interpret numbers of {littype}.
- It would be better to use either
- <a href={CERT.hex.getUnicodeString}>cert:hex</a> or <a href={CERT.int_.getUnicodeString}>cert:int</a></li>
- }
- case _: Literal => <li>Warning: you need to put a literal type, so we can know how to interpret the string.
- </li>
- }
- }
-
- def verifyKeyClosely(key: RichGraphNode) : NodeSeq= {
- val moduli = key/RSA.modulus
- val modWarn = if (moduli.size>1) {
- <li>Warning: you have written the modulus out in more than one way. If they a are not equal your
- connections might be alternatively successful</li>
- } else if (moduli.size==0) {
- <li>Warning: you have no modulus here. RSA keys must have one modulus</li>
- } else moduli! match {
- case _: NonLiteral => nonLiteralNumTest(moduli(0),CERT.hex,"modulus")
- case lit: Literal => literalNumTest(lit)
- }
- val expts = key/RSA.public_exponent
- val expWarn = if (expts.size>1) {
- <li>Warning: you have more than one exponent. They must be equal, or your connections will be unpredicable</li>
-
- } else if (expts.size==0) {
- <li>Warning: you have no exponent here. RSA keys must have one public exponent</li>
- } else expts! match {
- case _: NonLiteral => nonLiteralNumTest(expts(0),CERT.decimal,"exponent")
- case lit: Literal => literalNumTest(lit)
- }
-
- return modWarn ++ expWarn
- }
+ /**
+ * test numbers written in the old style with non literals
+ *
+ * @param The node that is the number. Should be a non literal
+ * @param The relation name to the string that identifies the number
+ * @param The role of the number in the public key (modulus, exponent, ...)
+ *
+ */
+ def nonLiteralNumTest(number: RichGraphNode, relToString: UriRef, numberRole: String ): NodeSeq = {
+ val typeTest = number! match {
+ case uri: UriRef => <li>Warning: your {numberRole} is a uri. The new spec requires this to be a literal.
+ Uri found: {uri.getUnicodeString}</li>
+ case _: BNode => <li>Warning: your {numberRole} is a blank node. The newer spec requires this to be a literal</li>
+ }
+ typeTest++
+ {
+ val hexs = number / relToString
+ if (hexs.size > 1) {
+ <li>WARNING: Your {numberRole} has more than one relation to a hexadecimal string. Unless both of those strings
+ map to the same number, your identification experience will be very random</li>
+ } else if (hexs.size == 0) {
+ <li>WARNING: your {numberRole} has no decimal literal attached by the {relToString} relation</li>
+ } else hexs! match {
+ case bnode: NonLiteral => <li>Warning: Your {numberRole} has a relation to a non literal, where it should be a
+ relation to a literal. It is possible that logically it all works out, but don't even expect a few engines to
+ bother reflecting deeply on this. We don't check past here.</li>
+ case lit: Literal => emptyxml
+ }
+ }
+
+ }
+
+ def literalNumTest(number: Literal): NodeSeq = {
+ number match {
+ case tl: TypedLiteral => tl.getDataType match {
+ case CERT.int_ => emptyxml
+ case CERT.hex => emptyxml
+ case CERT.decimal => emptyxml
+ case XSD.base64Binary => <li>Base 64 binary is not a number. If you wish to have a base64 integer notation
+ let the WebId Group know</li>
+ case XSD.hexBinary => <li>Base hex binary is not a number. If you wish to have a hex integer notation
+ use the {CERT.hex} relation. It is easier for people to write out</li>
+ case XSD.nonNegativeInteger => emptyxml
+ case XSD.integer => emptyxml
+ case XSD.positiveInteger => emptyxml
+ case XSD.int_ => emptyxml
+ case littype => <li>We don't know how to interpret numbers of {littype}.
+ It would be better to use either
+ <a href={CERT.hex.getUnicodeString}>cert:hex</a> or <a href={CERT.int_.getUnicodeString}>cert:int</a></li>
+ }
+ case _: Literal => <li>Warning: you need to put a literal type, so we can know how to interpret the string.
+ </li>
+ }
+ }
+
+ def verifyKeyClosely(key: RichGraphNode) : NodeSeq= {
+ val moduli = key/RSA.modulus
+ val modWarn = if (moduli.size>1) {
+ <li>Warning: you have written the modulus out in more than one way. If they a are not equal your
+ connections might be alternatively successful</li>
+ } else if (moduli.size==0) {
+ <li>Warning: you have no modulus here. RSA keys must have one modulus</li>
+ } else moduli! match {
+ case _: NonLiteral => nonLiteralNumTest(moduli(0),CERT.hex,"modulus")
+ case lit: Literal => literalNumTest(lit)
+ }
+ val expts = key/RSA.public_exponent
+ val expWarn = if (expts.size>1) {
+ <li>Warning: you have more than one exponent. They must be equal, or your connections will be unpredicable</li>
+
+ } else if (expts.size==0) {
+ <li>Warning: you have no exponent here. RSA keys must have one public exponent</li>
+ } else expts! match {
+ case _: NonLiteral => nonLiteralNumTest(expts(0),CERT.decimal,"exponent")
+ case lit: Literal => literalNumTest(lit)
+ }
+
+ return modWarn ++ expWarn
+ }
}