diff options
author | Alexander Sulfrian <alexander@sulfrian.net> | 2010-06-08 09:01:43 +0200 |
---|---|---|
committer | Alexander Sulfrian <alexander@sulfrian.net> | 2010-06-08 09:01:43 +0200 |
commit | d1fa08fdc9cb11dccee76d668ff85df30458c295 (patch) | |
tree | 1d19df6405103577d872902486792e8c23bce711 /trunk/infrastructure/net.appjet.oui | |
parent | d7c5ad7d6263fd1baf9bfdbaa4c50b70ef2fbdb2 (diff) | |
parent | 70d1f9d6fcaefe611e778b8dbf3bafea8934aa08 (diff) | |
download | etherpad-d1fa08fdc9cb11dccee76d668ff85df30458c295.tar.gz etherpad-d1fa08fdc9cb11dccee76d668ff85df30458c295.tar.xz etherpad-d1fa08fdc9cb11dccee76d668ff85df30458c295.zip |
Merge remote branch 'upstream/master'
Conflicts:
etherpad/src/etherpad/control/pro/admin/pro_admin_control.js
etherpad/src/etherpad/control/pro/pro_main_control.js
etherpad/src/etherpad/control/pro_help_control.js
etherpad/src/etherpad/globals.js
etherpad/src/etherpad/legacy_urls.js
etherpad/src/etherpad/pne/pne_utils.js
etherpad/src/etherpad/pro/pro_utils.js
etherpad/src/main.js
etherpad/src/plugins/fileUpload/templates/fileUpload.ejs
etherpad/src/plugins/testplugin/templates/page.ejs
etherpad/src/static/css/pad2_ejs.css
etherpad/src/static/css/pro-help.css
etherpad/src/static/img/jun09/pad/protop.gif
etherpad/src/static/js/store.js
etherpad/src/themes/default/templates/framed/framedheader-pro.ejs
etherpad/src/themes/default/templates/main/home.ejs
etherpad/src/themes/default/templates/pro-help/main.ejs
etherpad/src/themes/default/templates/pro-help/pro-help-template.ejs
infrastructure/com.etherpad/licensing.scala
trunk/etherpad/src/etherpad/collab/ace/contentcollector.js
trunk/etherpad/src/etherpad/collab/ace/linestylefilter.js
trunk/etherpad/src/static/css/home-opensource.css
trunk/etherpad/src/static/js/ace.js
trunk/etherpad/src/static/js/linestylefilter_client.js
trunk/etherpad/src/templates/email/eepnet_license_info.ejs
trunk/etherpad/src/templates/pad/pad_body2.ejs
trunk/etherpad/src/templates/pad/pad_content.ejs
trunk/etherpad/src/templates/pad/padfull_body.ejs
trunk/etherpad/src/templates/pro/admin/pne-license-manager.ejs
Diffstat (limited to '')
-rw-r--r-- | infrastructure/net.appjet.oui/ConfigParam.java (renamed from trunk/infrastructure/net.appjet.oui/ConfigParam.java) | 0 | ||||
-rw-r--r-- | infrastructure/net.appjet.oui/FastJSON.scala (renamed from trunk/infrastructure/net.appjet.oui/FastJSON.scala) | 0 | ||||
-rw-r--r-- | infrastructure/net.appjet.oui/GeneratedConfigParam.java (renamed from trunk/infrastructure/net.appjet.oui/GeneratedConfigParam.java) | 0 | ||||
-rw-r--r-- | infrastructure/net.appjet.oui/dynamicvar.scala (renamed from trunk/infrastructure/net.appjet.oui/dynamicvar.scala) | 0 | ||||
-rw-r--r-- | infrastructure/net.appjet.oui/encryption.scala (renamed from trunk/infrastructure/net.appjet.oui/encryption.scala) | 0 | ||||
-rw-r--r-- | infrastructure/net.appjet.oui/files.scala (renamed from trunk/infrastructure/net.appjet.oui/files.scala) | 0 | ||||
-rw-r--r-- | infrastructure/net.appjet.oui/logging.scala (renamed from trunk/infrastructure/net.appjet.oui/logging.scala) | 0 | ||||
-rw-r--r-- | infrastructure/net.appjet.oui/monitoring.scala (renamed from trunk/infrastructure/net.appjet.oui/monitoring.scala) | 0 | ||||
-rw-r--r-- | infrastructure/net.appjet.oui/network.scala (renamed from trunk/infrastructure/net.appjet.oui/network.scala) | 0 | ||||
-rw-r--r-- | infrastructure/net.appjet.oui/servermodel.scala (renamed from trunk/infrastructure/net.appjet.oui/servermodel.scala) | 0 | ||||
-rw-r--r-- | infrastructure/net.appjet.oui/stats.scala (renamed from trunk/infrastructure/net.appjet.oui/stats.scala) | 0 | ||||
-rw-r--r-- | infrastructure/net.appjet.oui/synchronizer.scala (renamed from trunk/infrastructure/net.appjet.oui/synchronizer.scala) | 0 | ||||
-rw-r--r-- | infrastructure/net.appjet.oui/util.scala (renamed from trunk/infrastructure/net.appjet.oui/util.scala) | 0 | ||||
-rw-r--r-- | trunk/infrastructure/net.appjet.oui/config.scala | 240 | ||||
-rw-r--r-- | trunk/infrastructure/net.appjet.oui/execution.scala | 654 | ||||
-rw-r--r-- | trunk/infrastructure/net.appjet.oui/main.scala | 386 |
16 files changed, 0 insertions, 1280 deletions
diff --git a/trunk/infrastructure/net.appjet.oui/ConfigParam.java b/infrastructure/net.appjet.oui/ConfigParam.java index 5029f28..5029f28 100644 --- a/trunk/infrastructure/net.appjet.oui/ConfigParam.java +++ b/infrastructure/net.appjet.oui/ConfigParam.java diff --git a/trunk/infrastructure/net.appjet.oui/FastJSON.scala b/infrastructure/net.appjet.oui/FastJSON.scala index 60cfc48..60cfc48 100644 --- a/trunk/infrastructure/net.appjet.oui/FastJSON.scala +++ b/infrastructure/net.appjet.oui/FastJSON.scala diff --git a/trunk/infrastructure/net.appjet.oui/GeneratedConfigParam.java b/infrastructure/net.appjet.oui/GeneratedConfigParam.java index 0986015..0986015 100644 --- a/trunk/infrastructure/net.appjet.oui/GeneratedConfigParam.java +++ b/infrastructure/net.appjet.oui/GeneratedConfigParam.java diff --git a/trunk/infrastructure/net.appjet.oui/dynamicvar.scala b/infrastructure/net.appjet.oui/dynamicvar.scala index b1f8c2e..b1f8c2e 100644 --- a/trunk/infrastructure/net.appjet.oui/dynamicvar.scala +++ b/infrastructure/net.appjet.oui/dynamicvar.scala diff --git a/trunk/infrastructure/net.appjet.oui/encryption.scala b/infrastructure/net.appjet.oui/encryption.scala index 92d463b..92d463b 100644 --- a/trunk/infrastructure/net.appjet.oui/encryption.scala +++ b/infrastructure/net.appjet.oui/encryption.scala diff --git a/trunk/infrastructure/net.appjet.oui/files.scala b/infrastructure/net.appjet.oui/files.scala index 3df5c1c..3df5c1c 100644 --- a/trunk/infrastructure/net.appjet.oui/files.scala +++ b/infrastructure/net.appjet.oui/files.scala diff --git a/trunk/infrastructure/net.appjet.oui/logging.scala b/infrastructure/net.appjet.oui/logging.scala index 9c384d2..9c384d2 100644 --- a/trunk/infrastructure/net.appjet.oui/logging.scala +++ b/infrastructure/net.appjet.oui/logging.scala diff --git a/trunk/infrastructure/net.appjet.oui/monitoring.scala b/infrastructure/net.appjet.oui/monitoring.scala index e380b84..e380b84 100644 --- a/trunk/infrastructure/net.appjet.oui/monitoring.scala +++ b/infrastructure/net.appjet.oui/monitoring.scala diff --git a/trunk/infrastructure/net.appjet.oui/network.scala b/infrastructure/net.appjet.oui/network.scala index 2965b19..2965b19 100644 --- a/trunk/infrastructure/net.appjet.oui/network.scala +++ b/infrastructure/net.appjet.oui/network.scala diff --git a/trunk/infrastructure/net.appjet.oui/servermodel.scala b/infrastructure/net.appjet.oui/servermodel.scala index 1e2363f..1e2363f 100644 --- a/trunk/infrastructure/net.appjet.oui/servermodel.scala +++ b/infrastructure/net.appjet.oui/servermodel.scala diff --git a/trunk/infrastructure/net.appjet.oui/stats.scala b/infrastructure/net.appjet.oui/stats.scala index 075182f..075182f 100644 --- a/trunk/infrastructure/net.appjet.oui/stats.scala +++ b/infrastructure/net.appjet.oui/stats.scala diff --git a/trunk/infrastructure/net.appjet.oui/synchronizer.scala b/infrastructure/net.appjet.oui/synchronizer.scala index 2a6d9c1..2a6d9c1 100644 --- a/trunk/infrastructure/net.appjet.oui/synchronizer.scala +++ b/infrastructure/net.appjet.oui/synchronizer.scala diff --git a/trunk/infrastructure/net.appjet.oui/util.scala b/infrastructure/net.appjet.oui/util.scala index ba8a736..ba8a736 100644 --- a/trunk/infrastructure/net.appjet.oui/util.scala +++ b/infrastructure/net.appjet.oui/util.scala diff --git a/trunk/infrastructure/net.appjet.oui/config.scala b/trunk/infrastructure/net.appjet.oui/config.scala deleted file mode 100644 index 46e73cf..0000000 --- a/trunk/infrastructure/net.appjet.oui/config.scala +++ /dev/null @@ -1,240 +0,0 @@ -/** - * Copyright 2009 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS-IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.appjet.oui; - -import scala.collection.mutable.HashMap; -import java.util.regex.Pattern; -import java.net.URL; -import org.mortbay.jetty.servlet.Context; -import org.mozilla.javascript.{Scriptable, ScriptableObject, Context => JSContext}; - -import net.appjet.common.util.BetterFile; - - -object config { - val values = new HashMap[String, String]; - def stringOrElse(name: String, default: String): String = { - val v = values.getOrElse(name, default); - if (v != null) { - val m = propertiesPattern.matcher(v); - val sb = new StringBuffer(); - while (m.find()) { - m.appendReplacement(sb, getClass.getDeclaredMethod(m.group(1), Array[Class[_]](): _*).invoke(this, Array[Class[_]](): _*).asInstanceOf[String]); - } - m.appendTail(sb); - sb.toString(); - } else { - null; - } - } - def boolOrElse(name: String, default: Boolean) = values.get(name).map(_.equals("true")).getOrElse(default); - def intOrElse(name: String, default: Int) = values.get(name).map(Integer.parseInt(_)).getOrElse(default); - def longOrElse(name: String, default: Long) = values.get(name).map(java.lang.Long.parseLong(_)).getOrElse(default); - - @ConfigParam("Read configuration options from this file before processing any command-line flags.") - { val argName = "file" } - def configFile = stringOrElse("configFile", null); - - // configuation parameters - var specialDebug = false; - - @ConfigParam("Enable additional logging output.") - def verbose = boolOrElse("verbose", false); - - @ConfigParam("Activate \"developer\" mode.") - def devMode = boolOrElse("devMode", false); - - @ConfigParam("Activate \"profiling\" mode.") - def profile = boolOrElse("profile", false); - - @ConfigParam("Directory to use for storing appjet support files, logs, etc. This directory will be created if it does not exist and must be writeable by the user who runs appjet.jar. Defaults to current working directory.") - { val argName = "directory" } - def appjetHome = stringOrElse("appjetHome", "appjet"); - - @ConfigParam("Directory to use for storing built-in database (Apache Derby) files. Will be created if it doesn't exist. Defaults to [appjetHome]/db") - def derbyHome = stringOrElse("derbyHome", "[appjetHome]/derbydb"); - - @ConfigParam("Directory to use for storing appserver logs. Defaults to [appjetHome]/log/appserver") - { val argName = "directory" } - def logDir = stringOrElse("logDir", "[appjetHome]/log/appserver"); - - @ConfigParam("Optional alternative directory to load built-in libraries from. Used by AppJet platform hackers to develop and debug built-in libraries. Default: use built-in libraries.") - { val argName = "directory" } - def ajstdlibHome = stringOrElse("ajstdlibHome", null); - - @ConfigParam("Optional directory to specify as the \"app home\".") - { val argName = "directory" } - def appHome = stringOrElse("appHome", ""); - - - @ConfigParam("Search path for modules imported via \"import\". Defaults to current working directory.") - { val argName = "dir1:dir2:..." } - def modulePath = stringOrElse("modulePath", null); - def moduleRoots = - Array.concat(Array("."), if (modulePath != null) modulePath.split(":") else Array[String](), Array(ajstdlibHome)); - - @ConfigParam("Where to read the static files from on the local filesystem. Don't specify this to read static files from the classpath/JAR.") - { val argName = "directory" } - def useVirtualFileRoot = stringOrElse("useVirtualFileRoot", null); - - @ConfigParam("Directory to use for storing the temporary sessions file on shutdown. Will be created if it does not exist.") - { val argName = "directory" } - def sessionStoreDir = stringOrElse("sessionStoreDir", "[appjetHome]/sessions"); - - // performance tuning - @ConfigParam("Create this many runners before opening up the server.") - { val argName = "count" } - def preloadRunners = intOrElse("preloadRunners", 0); - - @ConfigParam("Have this many JDBC connections available in the pool.") - { val argName = "count" } - def jdbcPoolSize = intOrElse("jdbcPoolSize", 10); - @ConfigParam("Max count of worker threads.") - { val argName = "num" } - def maxThreads = intOrElse("maxThreads", 250); - - // specifying ports and such - def extractHostAndPort(s: String): (String, Int) = - if (s.indexOf(":") >= 0) - (s.split(":")(0), Integer.parseInt(s.split(":")(1))) - else - ("", Integer.parseInt(s)) - - @ConfigParam("[host:]port on which to serve the app. Default: 8080.") - { val argName = "[host:]port" } - def listen = stringOrElse("listen", "8080"); - @GeneratedConfigParam - def listenHost = extractHostAndPort(listen)._1; - @GeneratedConfigParam - def listenPort = extractHostAndPort(listen)._2; - - @ConfigParam("[host:]port on which to serve the app using SSL. Default: none.") - { val argName = "[host:]port" } - def listenSecure = stringOrElse("listenSecure", "0"); - @GeneratedConfigParam - def listenSecureHost = extractHostAndPort(listenSecure)._1; - @GeneratedConfigParam - def listenSecurePort = extractHostAndPort(listenSecure)._2; - - @ConfigParam("[host:]port:port on which to listen for monitoring. Default: none.") - { val argName = "[host:]primaryPort:secondaryPort" } - def listenMonitoring = stringOrElse("listenMonitoring", "0:0"); - def extractHostAndPortPort(s: String): (String, Int, Int) = { - val spl = s.split(":", 3); - if (spl.length > 2) - (spl(0), Integer.parseInt(spl(1)), Integer.parseInt(spl(2))) - else - ("", Integer.parseInt(spl(0)), Integer.parseInt(spl(1))); - } - @GeneratedConfigParam - def listenMonitoringHost = extractHostAndPortPort(listenMonitoring)._1; - @GeneratedConfigParam - def listenMonitoringPrimaryPort = extractHostAndPortPort(listenMonitoring)._2; - @GeneratedConfigParam - def listenMonitoringSecondaryPort = extractHostAndPortPort(listenMonitoring)._3; - - @ConfigParam("[host:]port on which to listen for RPCs (via SARS). Default: none.") - { val argName = "[host:]port" } - def listenSars = stringOrElse("listenSars", "0"); - @GeneratedConfigParam - def listenSarsHost = extractHostAndPort(listenSars)._1; - @GeneratedConfigParam - def listenSarsPort = extractHostAndPort(listenSars)._2; - - // Licensing - @ConfigParam("Private key for generating license keys.") - { val argName = "pathToKey" } - def licenseGeneratorKey = stringOrElse("licenseGeneratorKey", null); - - // SARS - @ConfigParam("SARS auth key. Default: \"appjet\".") - { val argName = "authkey" } - def sarsAuthKey = stringOrElse("sarsAuthKey", "appjet"); - - // SSL - @ConfigParam("[SSL] Keystore location. Default: appjetHome/sslkeystore.") - { val argName = "keystore" } - def sslKeyStore = stringOrElse("sslKeyStore", appjetHome+"/sslkeystore"); - def sslKeyStore_isSet = values.contains("sslKeyStore"); - @ConfigParam("[SSL] Key password. Default: same as store password.") - { val argName = "password" } - def sslKeyPassword = stringOrElse("sslKeyPassword", "[sslStorePassword]"); - @ConfigParam("[SSL] Store password. Default: 'appjet'.") - { val argName = "password" } - def sslStorePassword = stringOrElse("sslStorePassword", "appjet"); - - // email - @ConfigParam("host:port of mail server to use for sending email. Default: localhost:25.") - { val argName = "host:port" } - def smtpServer = stringOrElse("smtpServer", "localhost:25"); - def smtpServerHost = extractHostAndPort(smtpServer)._1; - def smtpServerPort = extractHostAndPort(smtpServer)._2; - @ConfigParam("username for authentication to mail server. Default: no authentication.") - { val argName = "username" } - def smtpUser = stringOrElse("smtpUser", ""); - @ConfigParam("password for authentication to mail server. Default: no authentication.") - { val argName = "password" } - def smtpPass = stringOrElse("smtpPass", ""); - - // comet - @ConfigParam("prefix for all comet requests. Required to use Comet system.") - { val argName = "path" } - def transportPrefix = stringOrElse("transportPrefix", null); - @ConfigParam("Use a subdomain for all comet requests.") - def transportUseWildcardSubdomains = boolOrElse("transportUseWildcardSubdomains", false); - @ConfigParam("Don't use short polling, ever.") - def disableShortPolling = boolOrElse("disableShortPolling", false); - - // helpers - val allProperties = - for (m <- getClass.getDeclaredMethods() if (m.getAnnotation(classOf[ConfigParam]) != null || m.getAnnotation(classOf[GeneratedConfigParam]) != null)) - yield m; - val configParamNames = - for (m <- allProperties if m.getAnnotation(classOf[ConfigParam]) != null) yield m.getName - lazy val allPropertiesMap = - Map((for (m <- allProperties) yield ((m.getName, () => m.invoke(this)))): _*); - val propertiesPattern = Pattern.compile("\\[("+allProperties.map(x => "(?:"+x.getName()+")").mkString("|")+")\\]"); - - override def toString() = - (allProperties.map(m => m.getName()+" -> "+m.invoke(this)) ++ - values.keys.toList.filter(! allPropertiesMap.contains(_)).map(k => k+" -> "+values(k))).mkString("[Config ", ", ", "]"); - def print { - for (m <- allProperties) { - println(m.getName() + " -> " + m.invoke(this)); - } - for ((k, v) <- values if (! allPropertiesMap.contains(k))) { - println(k + " -> " + v); - } - } - def configObject(globalScope: Scriptable) = - new ScriptableAdapter { - val keys = (Set.empty[Object] ++ allProperties.map(m => m.getName) ++ values.keySet).toList.toArray; - override def get(n: String, start: Scriptable) = - allPropertiesMap.getOrElse(n, () => values.getOrElse(n, JSContext.getUndefinedValue()))(); - override def put(n: String, start: Scriptable, value: Object) = - values(n) = value.toString(); - override def getIds() = keys; - override def getPrototype() = ScriptableObject.getObjectPrototype(globalScope); - override def has(n: String, start: Scriptable) = - allPropertiesMap.contains(n) || values.contains(n); - override def getDefaultValue(hint: Class[_]) = config.toString(); - } -} - -object global { - var context: Context = null; -} diff --git a/trunk/infrastructure/net.appjet.oui/execution.scala b/trunk/infrastructure/net.appjet.oui/execution.scala deleted file mode 100644 index 63749b1..0000000 --- a/trunk/infrastructure/net.appjet.oui/execution.scala +++ /dev/null @@ -1,654 +0,0 @@ -/** - * Copyright 2009 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS-IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.appjet.oui; - -import java.net.URLDecoder; -import java.util.Enumeration; -import java.util.concurrent.atomic.AtomicLong; - -import javax.servlet.http.{HttpServletRequest, HttpServletResponse, HttpServlet}; - -import scala.collection.mutable.{ListBuffer, LinkedHashSet, HashMap, ArrayBuffer}; -import scala.collection.immutable.Map; -import scala.collection.jcl.Conversions; - -import org.mozilla.javascript.{Scriptable, Context, Function, ScriptableObject, JavaScriptException}; -import org.mortbay.jetty.RetryRequest; - -import net.appjet.bodylock.{BodyLock, Executable, JSRuntimeException, JSCompileException}; -import net.appjet.common.util.{HttpServletRequestFactory, BetterFile}; - -import Util.enumerationToRichEnumeration; - -class RequestWrapper(val req: HttpServletRequest) { - req.setCharacterEncoding("UTF-8"); -// private lazy val parameterNames = -// (for (i <- Conversions.convertSet(req.getParameterMap.keySet().asInstanceOf[java.util.Set[String]])) yield i).toList.toArray -// private def parameterValues(k: String) = req.getParameterValues(k); - def headerCapitalize(s: String) = - s.split("-").map( - s => - if (s == null || s.length < 1) s - else s.substring(0, 1).toUpperCase()+s.substring(1).toLowerCase() - ).mkString("-"); - def isFake = false; - lazy val path = req.getRequestURI(); - lazy val host = { - val hostFromHeader = req.getHeader("Host"); - if ((hostFromHeader ne null) && hostFromHeader.indexOf(':') >= 0) { - // fix the port, which may be wrong in Host header (e.g. IE 6) - hostFromHeader.substring(0, hostFromHeader.indexOf(':')) + ":" + - req.getLocalPort; - } - else { - hostFromHeader; - } - } - lazy val query = req.getQueryString(); - lazy val method = req.getMethod(); - lazy val scheme = req.getScheme(); - lazy val clientAddr = req.getRemoteAddr(); - - def decodeWwwFormUrlencoded(content: => String): Map[String, Array[String]] = { - val map = new HashMap[String, ArrayBuffer[String]]; - if (content != null) { - for (pair <- content.split("&").map(_.split("=", 2))) { - val key = URLDecoder.decode(pair(0), "UTF-8"); - val list = map.getOrElseUpdate(key, new ArrayBuffer[String]); - if (pair.length > 1) { - list += URLDecoder.decode(pair(1), "UTF-8"); - } - } - } - Map((for ((k, v) <- map) yield (k, v.toArray)).toSeq: _*); - } - - def postParams = decodeWwwFormUrlencoded(content.asInstanceOf[String]); - def getParams = decodeWwwFormUrlencoded(query); - - lazy val params_i = { - if (contentType != null && contentType.startsWith("application/x-www-form-urlencoded")) { - if (req.getAttribute("ajcache_parameters") == null) { - req.setAttribute("ajcache_parameters", - Map((for (k <- (postParams.keys ++ getParams.keys).toList) - yield (k, postParams.getOrElse(k, Array[String]()) ++ - getParams.getOrElse(k, Array[String]()))).toSeq: _*)); - } - req.getAttribute("ajcache_parameters").asInstanceOf[Map[String, Array[String]]]; - } else { - Conversions.convertMap(req.getParameterMap().asInstanceOf[java.util.Map[String, Array[String]]]); - } - } - - def params(globalScope: Scriptable) = new ScriptableFromMapOfStringArrays( - globalScope, - params_i.keys.toList, - params_i.get(_), - false); - def headers(globalScope: Scriptable) = new ScriptableFromMapOfStringArrays( - globalScope, - req.getHeaderNames().asInstanceOf[Enumeration[String]] - .map(headerCapitalize).toList, - h => h match { - case "Host" => Some(Array(host)); - case hh => Some(Util.enumerationToArray(req.getHeaders(headerCapitalize(hh)).asInstanceOf[Enumeration[String]])) }, - true); - lazy val protocol = req.getProtocol(); - lazy val contentType = req.getHeader("Content-Type"); - lazy val postParamsInBody = contentType != null && contentType.startsWith("application/x-www-form-urlencoded"); - lazy val content = - if ((contentType != null && contentType.startsWith("text/")) || postParamsInBody) { - val reader = req.getReader(); - if (reader != null) - BetterFile.getReaderString(req.getReader()); - else - null; - } else { - val stream = req.getInputStream(); - if (stream != null) - BetterFile.getStreamBytes(req.getInputStream()); - else - null; - } - def files(globalScope: Scriptable): Object = { -// if (! req.isInstanceOf[com.oreilly.servlet.MultipartWrapper]) { - new ScriptableAdapter(); -// } else { -// val r = req.asInstanceOf[com.oreilly.servlet.MultipartWrapper]; -// val fileScriptables = new HashMap[String, Scriptable](); -// val fileBytes = new HashMap[String, Array[byte]](); -// new ScriptableFromMapOfScriptableArrays(globalScope, -// r.getFileNames().asInstanceOf[Enumeration[String]].toList, -// name => { -// if (r.getFile(name) == null) -// None -// else -// Some(Array(fileScriptables.getOrElseUpdate(name, -// new ScriptableFromMapOfArrays[Object](globalScope, -// Set("contentType", "filesystemName", "bytes").toSeq, -// _ match { -// case "contentType" => Some(Array(r.getContentType(name))); -// case "filesystemName" => -// Some(Array(r.getFilesystemName(name))); -// case "bytes" => -// Some(Array(Context.javaToJS(fileBytes.getOrElseUpdate(name, -// BetterFile.getFileBytes(r.getFile(name))), globalScope))); -// case _ => None; -// }, -// true)))) -// }, -// true); -// } - } -} - -class ResponseWrapper(val res: HttpServletResponse) { - private lazy val outputStrings = new ListBuffer[String]; - private lazy val outputBytes = new ListBuffer[Array[byte]]; - private var statusCode = 200; - private var contentType = "text/html"; - private var redirect: String = null; - private lazy val headers = new LinkedHashSet[(String, String, HttpServletResponse => Unit)] { - def removeAll(k: String) { - this.foreach(x => if (x._1 == k) remove(x)); - } - } - - private[oui] def overwriteOutputWithError(code: Int, errorStr: String) { - statusCode = code; - outputStrings.clear(); - outputStrings += errorStr; - outputBytes.clear(); - headers.clear(); - Util.noCacheHeaders.foreach(x => headers += (x._1, x._2, res => res.setHeader(x._1, x._2))); - redirect = null; - contentType = "text/html; charset=utf-8"; - } - - def reset() { - outputStrings.clear(); - outputBytes.clear(); - redirect = null; - headers.clear(); - Util.noCacheHeaders.foreach(x => headers += (x._1, x._2, res => res.setHeader(x._1, x._2))); - statusCode = 200; - contentType = "text/html; charset=utf-8"; - } - def error(code: Int, errorStr: String) { - overwriteOutputWithError(code, errorStr); - stop(); - } - def stop() { - throw AppGeneratedStopException; - } - - def write(s: String) { - outputStrings += s; - } - def getOutput() = outputStrings.mkString(""); - def writeBytes(bytes: String) { - val a = new Array[byte](bytes.length()); - bytes.getBytes(0, bytes.length(), a, 0); - outputBytes += a; - } - def writeBytes(bytes: Array[Byte]) { - outputBytes += bytes; - } - def getOutputBytes() = outputBytes.flatMap(x => x).toArray - def setContentType(s: String) { - contentType = s; - } - def getCharacterEncoding() = { - res.setContentType(contentType); - res.getCharacterEncoding(); - } - def setStatusCode(sc: Int) { - statusCode = sc; - } - def getStatusCode() = statusCode; - def redirect(loc: String) { - statusCode = 302; - redirect = loc; - stop(); - } - def setHeader(name: String, value: String) { - headers += ((name, value, res => res.setHeader(name, value))); - } - def addHeader(name: String, value: String) { - headers += ((name, value, res => res.addHeader(name, value))); - } - def getHeader(name: String) = { - headers.filter(_._1 == name).map(_._2).toSeq.toArray; - } - def removeHeader(name: String) { - headers.removeAll(name); - } - - var gzipOutput = false; - def setGzip(gzip: Boolean) { - gzipOutput = gzip; - } - - def print() { - if (redirect != null && statusCode == 302) { - headers.foreach(_._3(res)); - res.sendRedirect(redirect); - } else { - res.setStatus(statusCode); - res.setContentType(contentType); - headers.foreach(_._3(res)); - if (gzipOutput) res.setHeader("Content-Encoding", "gzip"); - if (outputStrings.length > 0) { - var bytes: Seq[Array[Byte]] = outputStrings.map(_.getBytes(res.getCharacterEncoding())); - if (gzipOutput) bytes = List(Util.gzip(Array.concat(bytes:_*))); - res.setContentLength((bytes :\ 0) {_.length + _}); - bytes.foreach(res.getOutputStream.write(_)); - } else if (outputBytes.length > 0) { - var bytes: Seq[Array[Byte]] = outputBytes; - if (gzipOutput) bytes = List(Util.gzip(Array.concat(bytes:_*))); - res.setContentLength((bytes :\ 0) {_.length + _}); - bytes.foreach(res.getOutputStream.write(_)); - } - } - } -} - -class ScriptableAdapter extends Scriptable { - private def unsupported() = throw UnsupportedOperationException; - def delete(index: Int) { unsupported(); } - def delete(name: String) { unsupported(); } - def get(index: Int, start: Scriptable): Object = Context.getUndefinedValue(); - def get(name: String, start: Scriptable): Object = Context.getUndefinedValue(); - def getClassName() = getClass.getName(); - def getDefaultValue(hint: Class[_]) = "[ScriptableAdapter]"; - def getIds(): Array[Object] = Array[Object](); - def getParentScope: Scriptable = null; - def getPrototype: Scriptable = null; - def has(index: Int, start: Scriptable): Boolean = false; - def has(name: String, start: Scriptable): Boolean = false; - def hasInstance(instance: Scriptable): Boolean = false; - def put(index: Int, start: Scriptable, value: Object) { unsupported(); } - def put(name: String, start: Scriptable, value: Object) { unsupported(); } - def setParentScope(parent: Scriptable) { unsupported(); } - def setPrototype(prototype: Scriptable) { unsupported(); } -} - -class ScriptableFromMapOfStringArrays(globalScope: Scriptable, - keys: Seq[String], values: String => Option[Array[String]], - zeroMeansNone: Boolean) extends ScriptableFromMapOfArrays[String]( - globalScope, keys, values, zeroMeansNone); - -class ScriptableFromMapOfScriptableArrays(globalScope: Scriptable, - keys: Seq[String], values: String => Option[Array[Scriptable]], - zeroMeansNone: Boolean) extends ScriptableFromMapOfArrays[Scriptable]( - globalScope, keys, values, zeroMeansNone); - - -class ScriptableFromMapOfArrays[V <: Object](globalScope: Scriptable, - keys: Seq[String], values: String => Option[Array[V]], - zeroMeansNone: Boolean) extends ScriptableAdapter { - override def get(n: String, start: Scriptable): Object = { - val v = values(n); - if (v.isEmpty || (zeroMeansNone && v.get.length == 0)) { - Context.getUndefinedValue(); - } else if (v.get.length == 1) { - v.get.apply(0); - } else { - Context.getCurrentContext().newArray(globalScope, v.get.map(x => x.asInstanceOf[Object])); - } - } - override def getIds(): Array[Object] = keys.toArray[Object]; - override def getPrototype = ScriptableObject.getObjectPrototype(globalScope); - override def has(n: String, start: Scriptable): Boolean = ! (values(n).isEmpty || (zeroMeansNone && values(n).get.length == 0)); -} - -object AppGeneratedStopException extends JSRuntimeException("User-generated stop.", null); -class NoHandlerException(msg: String) extends JSRuntimeException(msg, null); -object UnsupportedOperationException extends JSRuntimeException("Unsupported operation.", null); - -object ExecutionContextUtils { - val uniqueIds = new AtomicLong(0); - - val ecVar = new NoninheritedDynamicVariable[ExecutionContext](null); - def withContext[E](ec: ExecutionContext)(block: => E): E = { - ecVar.withValue(ec)(block); - } - - def currentContext = ecVar.value; -} - -case class ExecutionContext( - val request: RequestWrapper, - val response: ResponseWrapper, - var runner: ScopeReuseManager.Runner) { - val asyncs = new ListBuffer[Function]; - lazy val attributes = new HashMap[String, Any]; - var completed = false; - lazy val executionId = ""+ExecutionContextUtils.uniqueIds.incrementAndGet(); - var result: AnyRef = null; -} - -object CometSupport { - trait CometHandler { - def handleCometRequest(req: HttpServletRequest, res: HttpServletResponse); - } - var cometHandler: CometHandler = null; -} - -class OuiServlet extends HttpServlet { - override def doGet(req: HttpServletRequest, res: HttpServletResponse) { - execute(req, res); - } - - override def doPost(req: HttpServletRequest, res: HttpServletResponse) { - execute(req, res); - } - - override def doHead(req: HttpServletRequest, res: HttpServletResponse) { - execute(req, res); - } - - override def doPut(req: HttpServletRequest, res: HttpServletResponse) { - execute(req, res); - } - - override def doDelete(req: HttpServletRequest, res: HttpServletResponse) { - execute(req, res); - } - - override def doTrace(req: HttpServletRequest, res: HttpServletResponse) { - execute(req, res); - } - - override def doOptions(req: HttpServletRequest, res: HttpServletResponse) { - execute(req, res); - } - - def execute(req: HttpServletRequest, res: HttpServletResponse) { - if (req.getProtocol() == "HTTP/1.1" && req.getHeader("Host") == null) { - res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid HTTP/1.1 request: No \"Host\" header found."); - } else if (config.transportPrefix != null && req.getRequestURI().startsWith(config.transportPrefix)) { - val runner = ScopeReuseManager.getRunner; - val ec = new ExecutionContext(new RequestWrapper(req), new ResponseWrapper(res), runner); - req.setAttribute("executionContext", ec); - req.setAttribute("isServerPushConnection", true); - try { - CometSupport.cometHandler.handleCometRequest(req, res); - } catch { - case e: RetryRequest => { - ec.runner = null; - ScopeReuseManager.freeRunner(runner); - throw e; - } - case _ => {}; - } - try { - ec.response.print(); - execution.onprint(ec, BodyLock.subScope(runner.mainScope)); - } finally { - ec.runner = null; - ScopeReuseManager.freeRunner(runner); - } - } else { - execution.execute(req, res); - } - } -} - -object execution { - // maybe find a better place for this? - { // initialize ajstdlib - val c = Class.forName("net.appjet.ajstdlib.ajstdlib$"); - val m = c.getDeclaredMethod("init"); - val o = c.getDeclaredField("MODULE$"); - m.invoke(o.get(null)); - } - - val requestLib = new FixedDiskLibrary(new SpecialJarOrNotFile(config.ajstdlibHome, "onrequest.js")); - val errorLib = new FixedDiskLibrary(new SpecialJarOrNotFile(config.ajstdlibHome, "onerror.js")); - val printLib = new FixedDiskLibrary(new SpecialJarOrNotFile(config.ajstdlibHome, "onprint.js")); - val syntaxErrorLib = new FixedDiskLibrary(new SpecialJarOrNotFile(config.ajstdlibHome, "syntaxerror.js")); - val onSyntaxErrorLib = new FixedDiskLibrary(new SpecialJarOrNotFile(config.ajstdlibHome, "onsyntaxerror.js")); - val sarsLib = new FixedDiskLibrary(new SpecialJarOrNotFile(config.ajstdlibHome, "onsars.js")); - val scheduledTaskLib = new FixedDiskLibrary(new SpecialJarOrNotFile(config.ajstdlibHome, "onscheduledtask.js")); - def requestExecutable = requestLib.executable; - def errorExecutable = errorLib.executable; - def printExecutable = printLib.executable; - def syntaxErrorExecutable = syntaxErrorLib.executable; - def onSyntaxErrorExecutable = onSyntaxErrorLib.executable; - def sarsExecutable = sarsLib.executable; - def scheduledTaskExecutable = scheduledTaskLib.executable; - - def postSuccessfulRun(ec: ExecutionContext) { - try { - for (f <- ec.asyncs) { - BodyLock.runInContext({ cx => - f.call(cx, f.getParentScope(), ec.runner.mainScope, Array[Object]()); - }); - } - } catch { - case e => exceptionlog(e); - } - } - - def onprint(ec: ExecutionContext, scope: Scriptable) { - try { -// ec.runner.globalScope.put("_appjetcontext_", ec.runner.globalScope, ec); - printExecutable.execute(scope); - } catch { - case e => { exceptionlog(e); } // shrug. this was best-effort anyway. - } - } - - def execute(req: HttpServletRequest, res: HttpServletResponse) { - val runner = try { - ScopeReuseManager.getRunner; - } catch { - case e: JSCompileException => { - val r = ScopeReuseManager.getEmpty { r => - syntaxErrorExecutable.execute(r.globalScope) - } - val ec = ExecutionContext(new RequestWrapper(req), new ResponseWrapper(res), r); -// r.globalScope.put("_appjetcontext_", r.globalScope, ec); - ExecutionContextUtils.withContext(ec) { - ec.attributes("error") = e; - ec.result = onSyntaxErrorExecutable.execute(r.globalScope); - ec.response.print(); - } - return; - } - } - val ec = ExecutionContext(new RequestWrapper(req), new ResponseWrapper(res), runner); - val startTime = executionlatencies.time; - execute(ec, - (sc: Int, msg: String) => { - ec.response.overwriteOutputWithError(sc, msg); - }, - () => { executionlatencies.log(Map( - "time" -> (executionlatencies.time - startTime))); - ec.response.print() }, - () => { ScopeReuseManager.freeRunner(runner) }, - None); - } - - def errorToHTML(e: Throwable) = { - val trace = new java.io.StringWriter(); - e.printStackTrace(new java.io.PrintWriter(trace)); - trace.toString().split("\n").mkString("<br>\n"); - } - def execute(ec: ExecutionContext, - errorHandler: (Int, String) => Unit, - doneWritingHandler: () => Unit, - completedHandler: () => Unit, - customExecutable: Option[Executable]) = - ExecutionContextUtils.withContext(ec) { -// ec.runner.globalScope.put("_appjetcontext_", ec.runner.globalScope, ec); - val runScope = BodyLock.subScope(ec.runner.mainScope); - try { - ec.result = customExecutable.getOrElse(requestExecutable).execute(runScope); - ec.completed = true; - } catch { - case AppGeneratedStopException => { ec.completed = true; } - case e: NoHandlerException => errorHandler(500, "No request handler is defined."); - case e: RetryRequest => { completedHandler(); throw e; } - case e => { - ec.attributes("error") = e; - try { - ec.result = errorExecutable.execute(runScope); - } catch { - case AppGeneratedStopException => { } - case nhe: NoHandlerException => { - exceptionlog(e); - e.printStackTrace(); - errorHandler(500, "An error occurred and no error handler is defined."); - } - case e2 => { - exceptionlog(e); exceptionlog(e2); - val etext = e2 match { - case jse: JavaScriptException => { (jse.getValue() match { - case ne: org.mozilla.javascript.IdScriptableObject => ne.get("message", ne) - case e => e.getClass.getName - }) + "<br>\n" + errorToHTML(jse); } - case _ => errorToHTML(e2); - } - errorHandler( - 500, - "You like apples? An error occurred in the error handler while handling an error. How do you like <i>them</i> apples?<br>\n"+ - etext+"<br>\nCaused by:<br>\n"+errorToHTML(e)); - } - } - } - } - onprint(ec, runScope); - doneWritingHandler(); - if (ec.completed && ! ec.asyncs.isEmpty) { - main.server.getThreadPool().dispatch(new Runnable { - def run() { - postSuccessfulRun(ec); - completedHandler(); - } - }); - } else { - completedHandler(); - } - } - - def runOutOfBandSimply(executable: Executable, - props: Option[Map[String, Any]]) = { - // there must be a context already. - val currentContext = ExecutionContextUtils.currentContext; - val request = - if (currentContext != null) { - currentContext.request; - } else { - val fakeHeaders = scala.collection.jcl.Conversions.convertMap( - new java.util.HashMap[String, String]); - fakeHeaders("Host") = "unknown.local"; - new RequestWrapper(HttpServletRequestFactory.createRequest( - "/", fakeHeaders.underlying, "GET", null)) { - override val isFake = true; - } - } - val response = - if (currentContext != null && currentContext.response != null) { - currentContext.response; - } else { - new ResponseWrapper(null); - } - val runner = - if (currentContext != null) { - (false, currentContext.runner); - } else { - (true, ScopeReuseManager.getRunner); - } - val ec = new ExecutionContext(request, response, runner._2) - if (props.isDefined) { - for ((k, v) <- props.get) { - ec.attributes(k) = v; - } - } - try { - ExecutionContextUtils.withContext(ec) { - executable.execute(BodyLock.subScope(ec.runner.mainScope)); - } - } finally { - if (runner._1) { - ScopeReuseManager.freeRunner(runner._2); - } - } - } - - def runOutOfBand(executable: Executable, name: String, - props: Option[Map[String, Any]], - onFailure: Any => Unit) = { - var ec: ExecutionContext = null; - try { - val runner = ScopeReuseManager.getRunner; - val currentContext = ExecutionContextUtils.currentContext; - val request = - if (currentContext != null) { - currentContext.request; - } else { - val fakeHeaders = scala.collection.jcl.Conversions.convertMap( - new java.util.HashMap[String, String]); - fakeHeaders("Host") = "unknown.local"; - new RequestWrapper(HttpServletRequestFactory.createRequest( - "/", fakeHeaders.underlying, "GET", null)) { - override val isFake = true; - } - } - val response = - if (currentContext != null && currentContext.response != null) { - new ResponseWrapper(currentContext.response.res); - } else { - new ResponseWrapper(null); - } - ec = new ExecutionContext(request, response, runner); - if (props.isDefined) - for ((k, v) <- props.get) { - ec.attributes(k) = v; - } - execution.execute(ec, - (sc: Int, msg: String) => { println(name+" execution failed with error: "+sc+"\n"+msg); onFailure((sc, msg)); }, - () => { }, - () => { ScopeReuseManager.freeRunner(runner) }, - Some(executable)); - if (ec.response != null && ec.response.getStatusCode() != 200) { - println(name+" execution failed with non-200 response: "+ec.response.getStatusCode()); - onFailure((ec.response.getStatusCode, ec.response.getOutput())); - } - ec; - } catch { - case e: JSCompileException => { - val r = ScopeReuseManager.getEmpty { r => - execution.syntaxErrorExecutable.execute(r.globalScope); - } - val ec = ExecutionContext(null, null, r); -// r.globalScope.put("_appjetcontext_", r.globalScope, ec); - ExecutionContextUtils.withContext(ec) { - ec.attributes("error") = e; - ec.result = execution.onSyntaxErrorExecutable.execute(r.globalScope); - onFailure(e); - } - ec; - } - case e => { - println(name+" execution failed with error."); onFailure(e); ec; - } - } - } -} diff --git a/trunk/infrastructure/net.appjet.oui/main.scala b/trunk/infrastructure/net.appjet.oui/main.scala deleted file mode 100644 index 42cd268..0000000 --- a/trunk/infrastructure/net.appjet.oui/main.scala +++ /dev/null @@ -1,386 +0,0 @@ -/** - * Copyright 2009 Google Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS-IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package net.appjet.oui; - -import net.appjet.bodylock.{BodyLock, Executable}; - -import java.io.File; -import java.util.{Properties, Date}; -import java.lang.annotation.Annotation; -import java.text.SimpleDateFormat; - -import scala.collection.mutable.{HashMap, SynchronizedMap, HashSet}; -import scala.collection.jcl.{IterableWrapper, Conversions}; - -import org.mortbay.thread.QueuedThreadPool; -import org.mortbay.jetty.servlet.{Context, HashSessionIdManager, FilterHolder, ServletHolder}; -import org.mortbay.jetty.handler.{HandlerCollection, RequestLogHandler, HandlerList}; -import org.mortbay.jetty.{Server, NCSARequestLog, Request, Response}; -import org.mortbay.servlet.GzipFilter; - -// removed due to license restrictions -// import com.oreilly.servlet.MultipartFilter; - -import net.appjet.common.util.{BetterFile, HttpServletRequestFactory}; -import net.appjet.common.cli._; -import net.appjet.bodylock.JSCompileException; - -import Util.enumerationToRichEnumeration; - -object main { - val startTime = new java.util.Date(); - - def quit(status: Int) { - java.lang.Runtime.getRuntime().halt(status); - } - - def setupFilesystem() { - val logdir = new File(config.logDir+"/backend/access"); - if (! logdir.isDirectory()) - if (! logdir.mkdirs()) - quit(1); - } - - val options = - for (m <- config.allProperties if (m.getAnnotation(classOf[ConfigParam]) != null)) yield { - val cp = m.getAnnotation(classOf[ConfigParam]) - new CliOption(m.getName(), cp.value(), if (cp.argName().length > 0) Some(cp.argName()) else None); - } - - def printUsage() { - println("\n--------------------------------------------------------------------------------"); - println("usage:"); - println((new CliParser(options)).usage); - println("--------------------------------------------------------------------------------\n"); - } - - def extractOptions(args: Array[String]) { - val parser = new CliParser(options); - val opts = - try { - parser.parseOptions(args)._1; - } catch { - case e: ParseException => { - println("error: "+e.getMessage()); - printUsage(); - System.exit(1); - null; - } - } - if (opts.contains("configFile")) { - val p = new Properties(); - p.load(new java.io.FileInputStream(opts("configFile"))); - extractOptions(p); - } - for ((k, v) <- opts) { - config.values(k) = v; - } - } - - def extractOptions(props: Properties) { - for (k <- for (o <- props.propertyNames()) yield o.asInstanceOf[String]) { - config.values(k) = props.getProperty(k); - } - } - - val startupExecutable = (new FixedDiskLibrary(new SpecialJarOrNotFile(config.ajstdlibHome, "onstartup.js"))).executable; - def runOnStartup() { - execution.runOutOfBand(startupExecutable, "Startup", None, { error => - error match { - case e: JSCompileException => { } - case e: Throwable => { e.printStackTrace(); } - case (sc: Int, msg: String) => { println(msg); } - case x => println(x); - } - System.exit(1); - }); - } - - lazy val shutdownExecutable = (new FixedDiskLibrary(new SpecialJarOrNotFile(config.ajstdlibHome, "onshutdown.js"))).executable; - def runOnShutdown() { - execution.runOutOfBand(shutdownExecutable, "Shutdown", None, { error => - error match { - case e: JSCompileException => { } - case e: Throwable => { } - case (sc: Int, msg: String) => { println(msg); } - case x => println(x); - } - }); - } - - def runOnSars(q: String) = { - val ec = execution.runOutOfBand(execution.sarsExecutable, "SARS", Some(Map("sarsRequest" -> q)), { error => - error match { - case e: JSCompileException => { throw e; } - case e: Throwable => { exceptionlog(e); throw e; } - case (sc: Int, msg: String) => { println(msg); throw new RuntimeException(""+sc+": "+msg) } - case x => { println(x); throw new RuntimeException(x.toString()) } - } - }); - ec.attributes.get("sarsResponse").map(_.toString()); - } - - def stfu() { - System.setProperty("org.mortbay.log.class", "net.appjet.oui.STFULogger"); - System.setProperty("com.mchange.v2.log.MLog", "com.mchange.v2.log.FallbackMLog"); - System.setProperty("com.mchange.v2.log.FallbackMLog.DEFAULT_CUTOFF_LEVEL", "OFF"); - } - var server: Server = null; - var sarsServer: net.appjet.common.sars.SarsServer = null; - - var loggers = new HashSet[GenericLogger]; - def main(args: Array[String]) { - val etherpadProperties = getClass.getResource("/etherpad.properties"); - if (etherpadProperties != null) { - val p = new Properties(); - p.load(etherpadProperties.openStream); - extractOptions(p); - } - extractOptions(args); - - if (! config.verbose) - stfu(); - setupFilesystem(); - if (config.devMode) - config.print; - if (config.profile) - profiler.start(); - if (config.listenMonitoring != "0:0") - monitoring.startMonitoringServer(); - - // this needs a better place. - if (config.devMode) - BodyLock.map = Some(new HashMap[String, String] with SynchronizedMap[String, String]); - - server = new Server(); - if (config.maxThreads > 0) - server.setThreadPool(new QueuedThreadPool(config.maxThreads)); - else - server.setThreadPool(new QueuedThreadPool()); - // set up socket connectors - val nioconnector = new CometSelectChannelConnector; - var sslconnector: CometSslSelectChannelConnector = null; - nioconnector.setPort(config.listenPort); - if (config.listenHost.length > 0) - nioconnector.setHost(config.listenHost); - if (config.listenSecurePort == 0) { - server.setConnectors(Array(nioconnector)); - } else { - sslconnector = new CometSslSelectChannelConnector; - sslconnector.setPort(config.listenSecurePort); - if (config.listenSecureHost.length > 0) - sslconnector.setHost(config.listenSecureHost); - if (! config.sslKeyStore_isSet) { - val url = getClass.getResource("/mirror/snakeoil-ssl-cert"); - if (url != null) - sslconnector.setKeystore(url.toString()); - else - sslconnector.setKeystore(config.sslKeyStore); - } else { - sslconnector.setKeystore(config.sslKeyStore); - } - sslconnector.setPassword(config.sslStorePassword); - sslconnector.setKeyPassword(config.sslKeyPassword); - sslconnector.setTrustPassword(config.sslStorePassword); - sslconnector.setExcludeCipherSuites(Array[String]( - "SSL_RSA_WITH_3DES_EDE_CBC_SHA", - "SSL_DHE_RSA_WITH_DES_CBC_SHA", - "SSL_DHE_DSS_WITH_DES_CBC_SHA", - "SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA", - "SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA", - "SSL_RSA_WITH_DES_CBC_SHA", - "SSL_RSA_EXPORT_WITH_RC4_40_MD5", - "SSL_RSA_EXPORT_WITH_DES40_CBC_SHA", - "SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA", - "SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA", - "SSL_RSA_WITH_NULL_MD5", - "SSL_RSA_WITH_NULL_SHA", - "SSL_DH_anon_WITH_3DES_EDE_CBC_SHA", - "SSL_DH_anon_WITH_DES_CBC_SHA", - "SSL_DH_anon_EXPORT_WITH_RC4_40_MD5", - "SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA")); - server.setConnectors(Array(nioconnector, sslconnector)); - } - - // set up Context and Servlet - val handler = new Context(server, "/", Context.NO_SESSIONS | Context.NO_SECURITY); - handler.addServlet(new ServletHolder(new OuiServlet), "/"); - -// val filterHolder = new FilterHolder(new MultipartFilter()); -// filterHolder.setInitParameter("uploadDir", System.getProperty("java.io.tmpdir")); -// handler.addFilter(filterHolder, "/*", 1); - - global.context = handler; - - // set up apache-style logging - val requestLogHandler = new RequestLogHandler(); - val requestLog = new NCSARequestLog(config.logDir+"/backend/access/access-yyyy_mm_dd.request.log") { - override def log(req: Request, res: Response) { - try { - if (config.devMode || config.specialDebug) - super.log(req, res); - else if (res.getStatus() != 200 || config.transportPrefix == null || ! req.getRequestURI().startsWith(config.transportPrefix)) - super.log(req, res); - val d = new Date(); - appstats.stati.foreach(_(if (res.getStatus() < 0) 404 else res.getStatus()).hit(d)); - } catch { - case e => { exceptionlog("Error writing to log?"); exceptionlog(e); } - } - } - }; - requestLog.setRetainDays(365); - requestLog.setAppend(true); - requestLog.setExtended(true); - requestLog.setLogServer(true); - requestLog.setLogLatency(true); - requestLog.setLogTimeZone("PST"); - requestLogHandler.setRequestLog(requestLog); - - // set handlers with server - val businessHandlers = new HandlerList(); - businessHandlers.setHandlers(Array(handler)); - val allHandlers = new HandlerCollection(); - allHandlers.setHandlers(Array(businessHandlers, requestLogHandler)); - server.setHandler(allHandlers); - - // fix slow startup bug - server.setSessionIdManager(new HashSessionIdManager(new java.util.Random())); - - // run the onStartup script. - runOnStartup(); - - // preload some runners, if necessary. - if (config.preloadRunners > 0) { - val b = new java.util.concurrent.CountDownLatch(config.preloadRunners); - for (i <- 0 until config.preloadRunners) - (new Thread { - ScopeReuseManager.freeRunner(ScopeReuseManager.newRunner); - b.countDown(); - }).start(); - while (b.getCount() > 0) { - b.await(); - } - println("Preloaded "+config.preloadRunners+" runners."); - } - - // start SARS server. - if (config.listenSarsPort > 0) { - try { - import net.appjet.common.sars._; - sarsServer = new SarsServer(config.sarsAuthKey, - new SarsMessageHandler { override def handle(q: String) = runOnSars(q) }, - if (config.listenSarsHost.length > 0) Some(config.listenSarsHost) else None, - config.listenSarsPort); - sarsServer.daemon = true; - sarsServer.start(); - } catch { - case e: java.net.SocketException => { - println("SARS: A socket exception occurred: "+e.getMessage()+" on SARS server at "+config.listenSarsHost+":"+config.listenSarsPort); - java.lang.Runtime.getRuntime().halt(1); - } - } - } - - // start server - java.lang.Runtime.getRuntime().addShutdownHook(new Thread() { - override def run() { - val df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSZ"); - def printts(str: String) { - println("["+df.format(new Date())+"]: "+str); - } - printts("Shutting down..."); - handler.setShutdown(true); - Thread.sleep(if (config.devMode) 500 else 3000); - printts("...done, running onshutdown."); - runOnShutdown(); - printts("...done, stopping server."); - server.stop(); - server.join(); - printts("...done, flushing logs."); - for (l <- loggers) { l.flush(); l.close(); } - printts("...done."); - } - }); - - def socketError(c: org.mortbay.jetty.Connector, e: java.net.SocketException) { - var msg = e.getMessage(); - println("SOCKET ERROR: "+msg+" - "+(c match { - case null => "(unknown socket)"; - case x => { - (x.getHost() match { - case null => "localhost"; - case y => y; - })+":"+x.getPort(); - } - })); - if (msg.contains("Address already in use")) { - println("Did you make sure that ports "+config.listenPort+" and "+config.listenSecurePort+" are not in use?"); - } - if (msg.contains("Permission denied")) { - println("Perhaps you need to run as the root user or as an Administrator?"); - } - } - - var c: org.mortbay.jetty.Connector = null; - - try { - c = nioconnector; - c.open(); - if (sslconnector != null) { - c = sslconnector; - c.open(); - } - c = null; - allHandlers.start(); - server.start(); - } catch { - case e: java.net.SocketException => { - socketError(c, e); - java.lang.Runtime.getRuntime().halt(1); - } - case e: org.mortbay.util.MultiException => { - println("SERVER ERROR: Couldn't start server; multiple errors."); - for (i <- new IterableWrapper[Throwable] { override val underlying = e.getThrowables.asInstanceOf[java.util.List[Throwable]] }) { - i match { - case se: java.net.SocketException => { - socketError(c, se); - } - case e => - println("SERVER ERROR: Couldn't start server: "+i.getMessage()); - } - } - java.lang.Runtime.getRuntime().halt(1); - } - case e => { - println("SERVER ERROR: Couldn't start server: "+e.getMessage()); - java.lang.Runtime.getRuntime().halt(1); - } - } - - println("HTTP server listening on http://"+ - (if (config.listenHost.length > 0) config.listenHost else "localhost")+ - ":"+config.listenPort+"/"); - if (config.listenSecurePort > 0) - println("HTTPS server listening on https://"+ - (if (config.listenSecureHost.length > 0) config.listenSecureHost else "localhost")+ - ":"+config.listenSecurePort+"/"); - if (config.listenSarsPort > 0) - println("SARS server listening on "+ - (if (config.listenSarsHost.length > 0) config.listenSarsHost else "localhost")+ - ":"+config.listenSarsPort); - } -} |