code
stringlengths 10
343k
| docstring
stringlengths 36
21.9k
| func_name
stringlengths 1
3.35k
| language
stringclasses 1
value | repo
stringlengths 7
58
| path
stringlengths 4
131
| url
stringlengths 44
195
| license
stringclasses 5
values |
---|---|---|---|---|---|---|---|
exports.resetTime = (date) => {
return new Date(date.getFullYear(), date.getMonth(), date.getDate());
}; | Resets the time values to 0, keeping only year, month and day.
@param {Date} date to reset
@returns {Date} date without any time values
@example const d = new Date(2016, 5, 10, 10, 20, 30);
// Fri Jun 10 2016 00:00:00 GMT+0200 (MESZ)
dates.resetTime(d); | exports.resetTime | javascript | ringo/ringojs | modules/ringo/utils/dates.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/utils/dates.js | Apache-2.0 |
exports.resetDate = (date) => {
return new Date(1970, 0, 1, date.getHours(), date.getMinutes(), date.getSeconds(), date.getMilliseconds());
}; | Drops the date values, keeping only hours, minutes, seconds and milliseconds.
@param {Date} date to reset
@returns {Date} date with the original time values and 1970-01-01 as date.
@example const d = new Date(2016, 5, 10, 10, 20, 30);
// Thu Jan 01 1970 10:20:30 GMT+0100 (MEZ)
dates.resetDate(d); | exports.resetDate | javascript | ringo/ringojs | modules/ringo/utils/dates.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/utils/dates.js | Apache-2.0 |
exports.toISOString = (date, withTime, withTimeZone, withSeconds, withMilliseconds) => {
let year, month, day, hours, minutes, seconds, milliseconds, str;
withTime = withTime !== false;
withTimeZone = withTimeZone === true;
withSeconds = withSeconds !== false;
withMilliseconds = withMilliseconds !== false;
// use local time if output is not in UTC
if (withTimeZone) {
year = date.getFullYear();
month = date.getMonth();
day = date.getDate();
hours = date.getHours();
minutes = date.getMinutes();
seconds = date.getSeconds();
milliseconds = date.getMilliseconds();
} else { // use UTC
year = date.getUTCFullYear();
month = date.getUTCMonth();
day = date.getUTCDate();
hours = date.getUTCHours();
minutes = date.getUTCMinutes();
seconds = date.getUTCSeconds();
milliseconds = date.getUTCMilliseconds();
}
str = year + "-" + ("0".repeat(2) + (month + 1)).slice(-2) + "-" + ("0".repeat(2) + day).slice(-2);
// Append the time
if (withTime) {
str += "T" + ("0".repeat(2) + hours).slice(-2) + ":" + ("0".repeat(2) + minutes).slice(-2);
if (withSeconds) {
str += ":" + ("0".repeat(2) + seconds).slice(-2);
if (withMilliseconds) {
str += "." + ("0".repeat(3) + milliseconds).slice(-3);
}
}
}
// Append the timezone offset
if (withTime && withTimeZone) {
const offset = date.getTimezoneOffset(),
inHours = Math.floor(Math.abs(offset / 60)),
inMinutes = Math.abs(offset) - (inHours * 60);
// Write the time zone offset in hours
if (offset <= 0) {
str += "+";
} else {
str += "-";
}
str += ("0".repeat(2) + inHours).slice(-2) + ":" + ("0".repeat(2) + inMinutes).slice(-2);
} else if(withTime) {
str += "Z"; // UTC indicator
}
return str;
}; | Creates an ISO 8601 compatible string from the date. This is similar to <code>Date.toISOString()</code>, which
only returns an UTC-based string. If you don't need a timezone, <code>Date.toISOString()</code> will be the better
choice. Use this function only if you need to include the timezone offset in your string, or if you need to control
the granularity of the output fields.
@param {Date} date to format
@param {Boolean} withTime if true, the string will contain the time, if false only the date. Default is true.
@param {Boolean} withTimeZone if true, the string will be in local time, if false it's in UTC. Default is false.
@param {Boolean} withSeconds if true, the string will contain also the seconds of the date. Default is true.
@param {Boolean} withMilliseconds if true, the string will contain the millisecond part of the date. Default is true.
@returns {String} date as ISO 8601 string.
@example // "2018-08-08T17:16:44.926+02:00"
dates.toISOString(new Date(), true, true); | exports.toISOString | javascript | ringo/ringojs | modules/ringo/utils/dates.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/utils/dates.js | Apache-2.0 |
exports.fromUTCDate = (year, month, date, hour, minute, second, millisecond) => {
return new Date(Date.UTC(year, month, date, hour || 0 , minute || 0, second || 0, millisecond || 0));
}; | Create new Date from UTC timestamp.
This is an alternative to <code>new Date(Date.UTC(…));</code>
@param {Number} year
@param {Number} month
@param {Number} date
@param {Number} hour (optional, default 0)
@param {Number} minute (optional, default 0)
@param {Number} second (optional, default 0)
@param {Number} millisecond (optional, default 0)
@returns {Date} | exports.fromUTCDate | javascript | ringo/ringojs | modules/ringo/utils/dates.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/utils/dates.js | Apache-2.0 |
exports.toInstant = (date) => {
return java.time.Instant.ofEpochMilli(date.getTime());
}; | Converts the given date to a <code>java.time.Instant</code> instance. Helps to interact with the
<code>java.time</code> API for dates, times, and durations.
@param date {Date} the JavaScript Date object to convert
@return {java.time.Instant} instant instance at the given point in time
@see <a href="https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html">java.time</a> | exports.toInstant | javascript | ringo/ringojs | modules/ringo/utils/dates.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/utils/dates.js | Apache-2.0 |
exports.toOffsetDateTime = (date) => {
return Instant.ofEpochMilli(date.getTime()).atOffset(
ZoneOffset.ofTotalSeconds(date.getTimezoneOffset() * -60)
);
}; | Converts the given date to a <code>java.time.OffsetDateTime</code> instance using the date's offset.
Helps to interact with the <code>java.time</code> API for dates, times, and durations.
@param date {Date} the JavaScript Date object to convert
@return {java.time.OffsetDateTime} time instance with offset representing the given date
@see <a href="https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html">java.time</a> | exports.toOffsetDateTime | javascript | ringo/ringojs | modules/ringo/utils/dates.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/utils/dates.js | Apache-2.0 |
const clone = exports.clone = (object, circular, depth, prototype) => {
if (typeof circular === 'object') {
throw new Error("Old function signature used for objects.clone()!");
}
// maintain two arrays for circular references, where corresponding parents
// and children have the same index
const allParents = [];
const allChildren = [];
if (typeof circular == 'undefined') {
circular = true;
}
if (typeof depth == 'undefined') {
depth = Infinity;
}
// recurse this function so we don't reset allParents and allChildren
function _clone(parent, depth) {
// cloning null always returns null
if (parent === null) {
return null;
}
if (depth === 0) {
return parent;
}
if (typeof parent != 'object') {
return parent;
}
let child;
let proto;
if (Array.isArray(parent)) {
child = [];
} else if (parent instanceof RegExp) {
let flags = "";
if (parent.global) {
flags += 'g';
}
if (parent.ignoreCase) {
flags += 'i';
}
if (parent.multiline) {
flags += 'm';
}
child = new RegExp(parent.source, flags);
if (parent.lastIndex) {
child.lastIndex = parent.lastIndex;
}
} else if (parent instanceof Date) {
child = new Date(parent.getTime());
} else {
if (typeof prototype == 'undefined') {
proto = Object.getPrototypeOf(parent);
child = Object.create(proto);
} else {
child = Object.create(prototype);
proto = prototype;
}
}
if (circular) {
const index = allParents.indexOf(parent);
if (index !== -1) {
return allChildren[index];
}
allParents.push(parent);
allChildren.push(child);
}
Object.keys(parent).forEach(key => {
let attrs;
if (proto) {
attrs = Object.getOwnPropertyDescriptor(proto, key);
}
if (!attrs || attrs.set !== null) {
child[key] = _clone(parent[key], depth - 1);
}
});
return child;
}
return _clone(object, depth);
}; | Creates a deep clone (full copy) of the given object.
It supports cloning objects with circular references by tracking visited properties.
Only if the object to clone cannot hold any circular reference by foreknowledge,
tracking can be turned off to save CPU and memory.
@param {Object} object the object to clone
@param {Boolean} circular (optional, default true) true if the object to be cloned may contain circular references
@param {Number} depth (optional, default Infinity) limits the non-shallow clone of an object to a particular depth
@param {Object} prototype (optional) sets the prototype to be used when cloning an object
@returns {Object} the clone object
@see <a href="https://github.com/pvorb/node-clone/">node-clone</a>
@example let objects = require("ringo/utils/objects");
let a = [1, 2, 3];
// shallow clone: b.a and c.a will share the same array
let b = objects.clone(a);
a[0] = 100;
console.dir(a); // -> [ 100, 2, 3 ]
console.dir(b); // -> [ 1, 2, 3 ]
let root = { simple: 1 };
let circle = { circ: root };
root.circle = circle;
let copy = objects.clone(root);
console.dir(root); // -> { simple: 1, circle: { circ: [CyclicRef] }}
console.dir(copy); // -> { simple: 1, circle: { circ: [CyclicRef] }}
// endless loop, throws a java.lang.StackOverflowError
let danger = objects.clone(root, false);
// limiting the depth might lead to shallow clones!
let tree = { root: 1, a: { b: { c: { d: { e: "foo" } } } } };
let fullClone = objects.clone(tree);
let shallowClone = objects.clone(tree, true, 1);
tree.root = 2; // depth = 1
tree.a.b.c.d.e = "bar"; // depth = 5
console.log(tree.root); // --> 2
console.dir(tree.a.b.c.d); // --> { e: 'bar' }
console.log(fullClone.root); // --> 1
console.dir(fullClone.a.b.c.d); // --> { e: 'foo' }
console.log(shallowClone.root); // --> 1
console.dir(shallowClone.a.b.c.d); // --> { e: 'bar' } | exports.clone | javascript | ringo/ringojs | modules/ringo/utils/objects.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/utils/objects.js | Apache-2.0 |
exports.merge = function() {
const result = {};
for (let i = arguments.length; i > 0; --i) {
let obj = arguments[i - 1];
if (obj !== null && obj !== undefined) {
Object.keys(obj).forEach(key => result[key] = obj[key]);
}
}
return result;
}; | Creates a new object as the as the keywise union of the provided objects.
Whenever a key exists in a later object that already existed in an earlier
object, the according value of the earlier object takes precedence.
@param {Object...} obj... The objects to merge
@example const a = { "k1": "val-A" };
const b = { "k1": "val-B", "k2": "val-B" };
const c = { "k1": "val-C", "k2": "val-C" };
// result: { k1: 'val-A', k2: 'val-B' }
const result = objects.merge(a, b, c); | exports.merge ( ) | javascript | ringo/ringojs | modules/ringo/utils/objects.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/utils/objects.js | Apache-2.0 |
const contains = exports.contains = (array, val) => {
return array.indexOf(val) > -1;
}; | Check if an array passed as argument contains
a specific value (start from end of array).
@param {Array} array the array
@param {Object} val the value to check
@returns {Boolean} true if the value is contained | exports.contains | javascript | ringo/ringojs | modules/ringo/utils/arrays.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/utils/arrays.js | Apache-2.0 |
exports.peek = (array) => {
return array[array.length - 1];
}; | Return the last element of the array. This is like pop(), but
without modifying the array.
@param {Array} array the array
@returns {Object} the last element of the array, or undefined if the array is empty. | exports.peek | javascript | ringo/ringojs | modules/ringo/utils/arrays.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/utils/arrays.js | Apache-2.0 |
exports.remove = (array, val) => {
const index = array.indexOf(val);
if(index > -1) {
array.splice(index, 1);
}
return array;
}; | Remove the first occurrence of the argument value from the array. This method
mutates and returns the array on which it is called and does not create a
new array instance.
@param {Array} array the array
@param {Object} val the value to remove
@returns {Array} the array | exports.remove | javascript | ringo/ringojs | modules/ringo/utils/arrays.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/utils/arrays.js | Apache-2.0 |
const union = exports.union = function() {
const result = [];
const map = new java.util.HashMap();
for (let i = 0; i < arguments.length; i += 1) {
for (let n in arguments[i]) {
let item = arguments[i][n];
if (!map.containsKey(item)) {
result.push(item);
map.put(item, true);
}
}
}
return result;
}; | Retrieve the union set of a bunch of arrays.
@param {Array} array1,... the arrays to unify
@returns {Array} the union set | exports.union ( ) | javascript | ringo/ringojs | modules/ringo/utils/arrays.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/utils/arrays.js | Apache-2.0 |
exports.intersection = function(array) {
return union.apply(null, arguments).reduce((result, item) => {
let chksum = 0;
for (let i = 0; i < arguments.length; i += 1) {
if (contains(arguments[i], item)) {
chksum += 1;
} else {
break;
}
}
if (chksum === arguments.length) {
result.push(item);
}
return result;
}, []);
}; | Retrieve the intersection set of a bunch of arrays.
@param {Array} array,... the arrays to intersect
@returns {Array} the intersection set | exports.intersection ( array ) | javascript | ringo/ringojs | modules/ringo/utils/arrays.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/utils/arrays.js | Apache-2.0 |
exports.max = (array) => {
return Math.max.apply(Math, array);
}; | @param {Array} array the array
@returns {Number} the maximal element in an array obtained by calling Math.max(). | exports.max | javascript | ringo/ringojs | modules/ringo/utils/arrays.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/utils/arrays.js | Apache-2.0 |
exports.min = (array) => {
return Math.min.apply(Math, array);
}; | @param {Array} array the array
@returns {Number} the minimal element in an array obtained by calling Math.min(). | exports.min | javascript | ringo/ringojs | modules/ringo/utils/arrays.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/utils/arrays.js | Apache-2.0 |
const sanitizeHeaderValue = (fieldValue) => {
return fieldValue.replace(/\n/g, "").trim();
}; | @ignore interal function, following RFC 7230 section 3.2.2. field order | sanitizeHeaderValue | javascript | ringo/ringojs | modules/ringo/utils/http.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/utils/http.js | Apache-2.0 |
exports.Headers = function(headers) {
// when is a duck a duck?
if (headers && headers.get && headers.set) {
return headers;
}
headers = headers || {};
// populate internal lower case to original case map
const keys = Object.keys(headers).reduce((result, key) => {
result[String(key).toLowerCase()] = key;
return result;
}, {});
/**
* Get the value of the header with the given name
* @param {String} name the header name
* @returns {String} the header value
* @name Headers.instance.get
*/
Object.defineProperty(headers, "get", {
value: function(key) {
const value = this[key] || this[keys[key.toLowerCase()]];
return (typeof value === "string") ? sanitizeHeaderValue(value) : value;
}
});
/**
* Set the header with the given name to the given value.
* @param {String} name the header name
* @param {String} value the header value
* @name Headers.instance.set
*/
Object.defineProperty(headers, "set", {
value: function(key, value) {
value = sanitizeHeaderValue(value);
const oldKey = keys[key.toLowerCase()];
if (oldKey) {
delete this[oldKey];
}
this[key] = value;
keys[key.toLowerCase()] = key;
}
});
/**
* Add a header with the given name and value.
* @param {String} name the header name
* @param {String} value the header value
* @name Headers.instance.add
*/
Object.defineProperty(headers, "add", {
value: function(key, value) {
value = sanitizeHeaderValue(value);
if (this[key]) {
// shortcut
this[key] = this[key] + "," + value;
return;
}
const lowerKey = key.toLowerCase();
const oldKey = keys[lowerKey];
if (oldKey) {
value = this[oldKey] + "," + value;
if (key !== oldKey) {
delete this[oldKey];
}
}
this[key] = value;
keys[lowerKey] = key;
}
});
/**
* Queries whether a header with the given name is set
* @param {String} name the header name
* @returns {Boolean} true if a header with this name is set
* @name Headers.instance.contains
*/
Object.defineProperty(headers, "contains", {
value: function(key) {
return Boolean(this[key] !== undefined ||
this[keys[key.toLowerCase()]] !== undefined);
}
});
/**
* Unsets any header with the given name
* @param {String} name the header name
* @name Headers.instance.unset
*/
Object.defineProperty(headers, "unset", {
value: function(key) {
key = key.toLowerCase();
if (key in keys) {
delete this[keys[key]];
delete keys[key];
}
}
});
/**
* Returns a string representation of the headers in MIME format.
* @returns {String} a string representation of the headers
* @name Headers.instance.toString
*/
Object.defineProperty(headers, "toString", {
value: function() {
const buffer = new Buffer();
Object.keys(this).forEach(key => {
String(this[key]).split("\n").forEach(function(value) {
buffer.write(key).write(": ").writeln(value);
});
}, this);
return buffer.toString();
}
});
return headers;
} | Returns an object for use as a HTTP request header collection. The returned object
provides methods for setting, getting, and deleting its properties in a
case-insensitive and case-preserving way. Multiple headers with the same
field name will be merged into a comma-separated string. Therefore the
<code>Set-Cookie</code> header is not supported by this function.
This function can be used as mixin for an existing JavaScript object or as a
constructor.
@param {Object} headers an existing JS object. If undefined, a new object is
created | exports.Headers ( headers ) | javascript | ringo/ringojs | modules/ringo/utils/http.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/utils/http.js | Apache-2.0 |
const handleRequest = exports.handleRequest = (moduleId, functionObj, request) => {
initRequest(request);
let app;
if (typeof(functionObj) === 'function') {
app = functionObj;
} else {
app = require(moduleId);
if (typeof(app) !== 'function') {
app = app[functionObj];
}
request.env.app = moduleId;
}
// if RINGO_ENV environment variable is set and application supports
// modular JSGI environment feature use the proper environment
if (app && system.env.RINGO_ENV && typeof(app.env) === 'function') {
app = app.env(system.env.RINGO_ENV);
}
if (typeof(app) !== 'function') {
throw new Error('No valid JSGI app: ' + app);
}
const result = app(request);
if (!result) {
throw new Error('No valid JSGI response: ' + result);
}
commitResponse(request, result);
}; | Handle a JSGI request.
@param {String} moduleId the module id. Ignored if functionObj is already a function.
@param {Function|String} functionObj the function, either as function
object or function name to be imported from the module moduleId.
@param {Object} request the JSGI request object
@returns {Object} the JSGI response object | exports.handleRequest | javascript | ringo/ringojs | modules/ringo/jsgi/connector.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/jsgi/connector.js | Apache-2.0 |
const commitResponse = (req, result) => {
const request = req.env.servletRequest;
if (typeof request.isAsyncStarted === "function" && request.isAsyncStarted()) {
return;
}
const response = req.env.servletResponse;
const {status, headers, body} = result;
if (!status || !headers || !body) {
// Check if this is an asynchronous response. If not throw an Error
throw new Error('No valid JSGI response: ' + result);
}
// Allow application/middleware to handle request via Servlet API
if (!response.isCommitted() && !Headers(headers).contains("X-JSGI-Skip-Response")) {
writeResponse(response, status, headers, body);
}
}; | Apply the return value of a JSGI application to a servlet response.
This is used internally by the org.ringojs.jsgi.JsgiServlet class, so
you won't need this unless you're implementing your own servlet
based JSGI connector.
@param {Object} req the JSGI request argument
@param {Object} result the object returned by a JSGI application | commitResponse | javascript | ringo/ringojs | modules/ringo/jsgi/connector.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/jsgi/connector.js | Apache-2.0 |
exports.AsyncResponse = function(request, timeout) {
if (!request || !request.env) {
throw new Error("Invalid request argument: " + request);
}
const {servletRequest, servletResponse} = request.env;
const asyncContext = servletRequest.startAsync();
if (timeout != null && isFinite(timeout)) {
asyncContext.setTimeout(timeout);
}
asyncContext.addListener(new AsyncListener({
"onComplete": function(event) {
log.debug("AsyncListener.onComplete", event);
},
"onError": function(event) {
log.debug("AsyncListener.onError", event);
},
"onStartAsync": function(event) {
log.debug("AsyncListener.onStartAsync", event);
},
"onTimeout": function(event) {
log.debug("AsyncListener.onTimeout", event);
event.getAsyncContext().complete();
}
}));
const out = servletResponse.getOutputStream();
const writeListener = new WriteListenerImpl(asyncContext);
out.setWriteListener(writeListener);
return {
"start": function(status, headers) {
servletResponse.setStatus(status);
writeHeaders(servletResponse, headers || {});
return this;
},
"write": function(data, encoding) {
if (asyncContext.getHttpChannelState().isResponseCompleted()) {
throw new Error("AsyncResponse already closed");
}
if (!(data instanceof binary.Binary)) {
data = binary.toByteArray(String(data), encoding);
}
writeListener.queue.add(data);
writeListener.onWritePossible();
return this;
},
"flush": function() {
this.write(FLUSH);
},
"close": function() {
if (asyncContext.getHttpChannelState().isResponseCompleted()) {
throw new Error("AsyncResponse already closed");
}
return writeListener.close();
}
};
} | Creates a streaming asynchronous response. The returned response object can be used
both synchronously from the current thread or asynchronously from another thread,
even after the original thread has finished execution. AsyncResponse objects are
threadsafe.
To enable async support inside a Servlet 3.0+ container, an additional
<code><async-supported>true</async-supported></code> element in
the <code>web.xml</code> deployment descriptor might be required.
This indicates that Ringo's JsgiServlet supports asynchronous request processing.
@param {Object} request the JSGI request object
@param {Number} timeout time in milliseconds in which the async operation has to be completed;
otherwise the request is aborted by the Servlet container.
A negative value lets the async operation never time out. Defaults to 30 seconds.
@returns {Object} <code>AsyncResponse</code> object with helpers to control the response's <code>WriteListener</code>. Contains the following methods:
<dl>
<dt><code>start(status, headers)</code>
<dd>sends the status code and HTTP headers object, must be called before any write
<dt><code>write(data, encoding)</code>
<dd>adds the given data (instance of <code>String</code> or <code>Binary</code>) to output queue to be written back to the client
<dt><code>flush()</code>
<dd>forces any queued data to be written out
<dt><code>close()</code>
<dd>completes the async response and closes the write listener
</dl>
@see <a href="http://download.oracle.com/otndocs/jcp/servlet-3.0-fr-oth-JSpec/">Servlet 3.0 specification - <async-supported></a>
@example const response = new AsyncResponse(request, 10000);
response.start(200, {"Content-Type": "text/plain"});
// this functions returns a ringo promise
doSomeAsyncStuff().then(function(data) {
// write out result
response.write(data);
response.close();
}, function() {
// just close the connection in case of an error
response.close();
});
return response; | exports.AsyncResponse ( request , timeout ) | javascript | ringo/ringojs | modules/ringo/jsgi/connector.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/jsgi/connector.js | Apache-2.0 |
const WriteListenerImpl = function(asyncContext) {
this.isReady = new AtomicBoolean(true);
this.isFinished = false;
this.queue = new ConcurrentLinkedQueue();
this.asyncContext = asyncContext;
return new WriteListener(this);
}; | Creates a new WriteListener instance
@param {jakarta.servlet.AsyncContext} asyncContext The async context of the request
@param {jakarta.servlet.ServletOutputStream} outStream The output stream to write to
@returns {jakarta.servlet.WriteListener}
@constructor | WriteListenerImpl ( asyncContext ) | javascript | ringo/ringojs | modules/ringo/jsgi/connector.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/jsgi/connector.js | Apache-2.0 |
WriteListenerImpl.prototype.onWritePossible = function() {
const outStream = this.asyncContext.getResponse().getOutputStream();
if (this.isReady.compareAndSet(true, false)) {
// Note: .isReady() schedules a call for onWritePossible
// if it returns false
while (outStream.isReady() && !this.queue.isEmpty()) {
let data = this.queue.poll();
if (data === FLUSH) {
outStream.flush();
} else {
outStream.write(data, 0, data.length);
}
if (!outStream.isReady()) {
this.isReady.set(true);
return;
}
}
// at this point the queue is empty: mark this listener as ready
// and close the response if we're finished
this.isReady.set(true);
if (this.isFinished === true &&
!this.asyncContext.getHttpChannelState().isResponseCompleted()) {
this.asyncContext.complete();
}
}
}; | Called by the servlet container or directly. Polls all byte buffers from
the internal queue and writes them to the response's output stream. | WriteListenerImpl.prototype.onWritePossible ( ) | javascript | ringo/ringojs | modules/ringo/jsgi/connector.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/jsgi/connector.js | Apache-2.0 |
WriteListenerImpl.prototype.onError = function(error) {
if (!(error instanceof EofException)) {
log.error("WriteListener.onError", error);
}
try {
this.asyncContext.complete();
} catch (e) {
// ignore, what else could we do?
}
}; | Called on every write listener error
@param {java.lang.Throwable} error The error | WriteListenerImpl.prototype.onError ( error ) | javascript | ringo/ringojs | modules/ringo/jsgi/connector.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/jsgi/connector.js | Apache-2.0 |
WriteListenerImpl.prototype.close = function() {
this.isFinished = true;
this.onWritePossible();
}; | Marks this write listener as finished and calls onWritePossible().
This will finish the queue and then complete the async context. | WriteListenerImpl.prototype.close ( ) | javascript | ringo/ringojs | modules/ringo/jsgi/connector.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/jsgi/connector.js | Apache-2.0 |
const JsgiResponse = exports.JsgiResponse = function(base) {
// Internal use only
/** @ignore */
Object.defineProperty(this, "_charset", {
value: "utf-8",
writable: true
});
this.status = 200;
this.headers = { "content-type": "text/plain; charset=" + this._charset };
this.body = [""];
if (base !== undefined) {
this.status = base.status || this.status;
this.headers = base.headers || this.headers;
this.body = base.body || this.body;
}
}; | A wrapper around a JSGI response object. `JsgiResponse` is chainable.
@param {Object} base a base object for the new JSGI response with the
initial <code>status</code>, <code>headers</code> and
<code>body</code> properties.
@constructor
@example // Using the constructor
const {JsgiResponse} = require('ringo/jsgi/response');
return (new JsgiResponse()).text('Hello World!').setCharset('ISO-8859-1');
// Using a static helper
const response = require('ringo/jsgi/response');
return response.json({'foo': 'bar'}).error(); | exports.JsgiResponse ( base ) | javascript | ringo/ringojs | modules/ringo/jsgi/response.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/jsgi/response.js | Apache-2.0 |
exports.range = function (request, representation, size, contentType, timeout, maxRanges) {
// this would be an application error --> throw an exception
if (!request || !request.headers || !request.headers["range"]) {
throw new Error("Request is not a range request!");
}
// only GET is allowed
// https://tools.ietf.org/html/rfc7233#section-3.1
if (request.method !== "GET") {
return new JsgiResponse().setStatus(400).text("Method not allowed.");
}
let stream;
if (typeof representation == "string") {
let localPath = fs.absolute(representation);
if (!fs.exists(localPath) || !fs.isReadable(localPath)) {
throw new Error("Resource does not exist or is not readable.");
}
if (size == null) {
try {
size = fs.size(localPath);
} catch (e) {
// ignore --> use -1 at the end
}
}
stream = fs.openRaw(localPath, "r");
} else if (representation instanceof org.ringojs.repository.Resource) {
stream = new io.Stream(representation.getInputStream());
if (size == null && representation.getLength != null) {
size = representation.getLength();
}
} else if (representation instanceof io.Stream) {
stream = representation;
} else {
throw new Error("Invalid representation! Must be a path to a file, a resource, or a stream.");
}
if (!stream.readable()) {
throw new Error("Stream must be readable!");
}
const BOUNDARY = new binary.ByteString("sjognir_doro_" +
java.lang.System.identityHashCode(this).toString(36) +
java.lang.System.identityHashCode(request).toString(36) +
java.lang.System.identityHashCode(stream).toString(36) +
(java.lang.System.currentTimeMillis() % 100000).toString(36) +
(Math.random().toFixed(10).slice(2)), "ASCII");
contentType = contentType || "application/octet-stream";
maxRanges = (maxRanges != null && Number.isSafeInteger(maxRanges) && maxRanges >= 0 ? maxRanges : 20);
// returns the raw ranges; might be overlapping / invalid
let ranges = parseRange(request.headers["range"], size);
if (ranges == null || ranges.length === 0 || ranges.length > maxRanges) {
return new JsgiResponse().setStatus(416).text("Invalid Range header!");
}
// make ranges canonical and check their validity
// https://tools.ietf.org/html/rfc7233#section-4.3
try {
ranges = canonicalRanges(ranges);
} catch (e) {
let invalidRangeResponse = new JsgiResponse().setStatus(416).text("Range Not Satisfiable");
if (size != null) {
invalidRangeResponse.addHeaders({
"content-range": "bytes */" + size
});
}
return invalidRangeResponse;
}
// check if range can be fulfilled
if (size != null && ranges[ranges.length - 1][1] > size) {
return new JsgiResponse().setStatus(416).addHeaders({
"content-range": "bytes */" + size
}).text("Range Not Satisfiable");
}
const {servletResponse} = request.env;
servletResponse.setStatus(206);
if (ranges.length > 1) {
servletResponse.setHeader("content-type", "multipart/byteranges; boundary=" + BOUNDARY.decodeToString("ASCII"));
} else {
servletResponse.setHeader("content-type", contentType);
servletResponse.setHeader("content-range", "bytes " + ranges[0].join("-") + "/" + size);
servletResponse.setContentLengthLong(ranges[0][1] - ranges[0][0] + 1);
}
const outStream = servletResponse.getOutputStream();
const responseBufferSize = Math.max(request.env.servletResponse.getBufferSize() - 70, 8192);
try {
let currentBytePos = 0;
ranges.forEach(function(range, index, arr) {
const [start, end] = range;
const numBytes = end - start + 1;
const rounds = Math.floor(numBytes / responseBufferSize);
const restBytes = numBytes % responseBufferSize;
stream.skip(start - currentBytePos);
if (arr.length > 1) {
const boundary = new io.MemoryStream(70);
if (index > 0) {
boundary.write(CRLF);
}
boundary.write(HYPHEN);
boundary.write(HYPHEN);
boundary.write(BOUNDARY);
boundary.write(CRLF);
boundary.write(new binary.ByteString("Content-Type: " + contentType, "ASCII"));
boundary.write(CRLF);
boundary.write(new binary.ByteString("Content-Range: bytes " + range.join("-") + "/" + (size >= 0 ? size : "*"), "ASCII"));
boundary.write(EMPTY_LINE);
boundary.position = 0;
outStream.write(boundary.read().unwrap());
boundary.close();
}
for (let i = 0; i < rounds; i++) {
outStream.write(stream.read(responseBufferSize).unwrap());
}
if (restBytes > 0) {
outStream.write(stream.read(restBytes).unwrap());
}
if (arr.length > 1 && index === arr.length - 1) {
// final boundary
const eofBoundary = new io.MemoryStream(70);
eofBoundary.write(CRLF);
eofBoundary.write(HYPHEN);
eofBoundary.write(HYPHEN);
eofBoundary.write(BOUNDARY);
eofBoundary.write(HYPHEN);
eofBoundary.write(HYPHEN);
eofBoundary.position = 0;
outStream.write(eofBoundary.read().unwrap());
eofBoundary.close();
}
currentBytePos = end + 1;
});
// commit response
servletResponse.flushBuffer();
} catch (e) {
if (!(e.javaException instanceof org.eclipse.jetty.io.EofException)) {
throw e;
}
// no problem, remote client closed connection ...
}
return {
status: -1,
headers: {
"x-jsgi-skip-response": "true"
},
body: {}
};
}; | An async response representing a resource as a single or multiple part response.
Multiple or overlapping byte ranges are coalesced into a canonical response range.
@param {Object} request a JSGI request object
@param {String|Resource|Stream} representation path of a file as string, a resource, or a readable <a href="../../../io/">io.Stream</a>
@param {Number} size optional size of the resource in bytes, -1 indicates an unknown size.
@param {String} contentType optional content type to send for single range responses
@param {Number} timeout optional timeout to send back the ranges, defaults to 30 seconds, -1 indicates an infinite timeout.
@param {Number} maxRanges optional maximum number of ranges in a request, defaults to 20. Similar to Apache's <code>MaxRanges</code> directive.
@returns {AsyncResponse} async response filled with the give ranges
@see <a href="https://tools.ietf.org/html/rfc7233">RFC 7233 - Range Requests</a>
@see <a href="https://tools.ietf.org/html/rfc7233#section-6">Range Requests - Security Considerations</a> | exports.range ( request , representation , size , contentType , timeout , maxRanges ) | javascript | ringo/ringojs | modules/ringo/jsgi/response.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/jsgi/response.js | Apache-2.0 |
this.event = sync(function(name, data) {
if (this.response === null) {
throw new Error('Connection not open');
}
this.response.write(EVENT_FIELD);
this.response.write(name);
this.response.write(CRLF);
this.data(data);
}, this); | Send a named event
@param {String} name The event name
@param {String} data The event data
@throws {Error} | (anonymous) ( name , data ) | javascript | ringo/ringojs | modules/ringo/jsgi/eventsource.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/jsgi/eventsource.js | Apache-2.0 |
this.data = sync(function(data) {
if (this.response === null) {
throw new Error('Connection not open');
}
this.response.write(DATA_FIELD);
this.response.write(data);
this.response.write(CRLF);
this.response.write(CRLF);
this.response.flush();
}, this); | Send data
@param {String} data The event data
@throws {Error} | (anonymous) ( data ) | javascript | ringo/ringojs | modules/ringo/jsgi/eventsource.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/jsgi/eventsource.js | Apache-2.0 |
this.comment = sync(function(comment) {
if (this.response === null) {
throw new Error('Connection not open');
}
this.response.write(COMMENT_FIELD);
this.response.write(comment);
this.response.write(CRLF);
this.response.write(CRLF);
this.response.flush();
}, this); | Send a comment.
@param {String} comment The comment
@throws {Error} | (anonymous) ( comment ) | javascript | ringo/ringojs | modules/ringo/jsgi/eventsource.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/jsgi/eventsource.js | Apache-2.0 |
this.close = sync(function() {
clearInterval(heartBeat);
this.response.close();
}, this); | Close the event source.
@throws {Error} | (anonymous) ( ) | javascript | ringo/ringojs | modules/ringo/jsgi/eventsource.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/jsgi/eventsource.js | Apache-2.0 |
this.start = function(headers, heartBeatInterval) {
if (this.response !== null) {
throw new Error('Connection already open');
}
if (heartBeatInterval === undefined || isNaN(heartBeatInterval)) {
heartBeatInterval = 15;
}
heartBeat = setInterval((function() {
try {
this.ping();
} catch (e) {
clearInterval(heartBeat);
}
}).bind(this), heartBeatInterval * 1000);
this.response = new AsyncResponse(request, 0);
this.response.start(200, objects.merge(headers || {}, {
'Content-Type': 'text/event-stream; charset=utf-8',
'Connection': 'close'
}));
this.response.flush();
}; | Start the async response. Optionally set additional headers here.
@param {Object} headers Additional headers (optional)
@param {Number} heartBeatInterval in seconds (optional. default: 15) | this.start ( headers , heartBeatInterval ) | javascript | ringo/ringojs | modules/ringo/jsgi/eventsource.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/jsgi/eventsource.js | Apache-2.0 |
this.ping = sync(function() {
this.response.write('\r');
this.response.flush();
}, this); | Sends a ping to the client
@throws {Error} | (anonymous) ( ) | javascript | ringo/ringojs | modules/ringo/jsgi/eventsource.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/jsgi/eventsource.js | Apache-2.0 |
exports.EventSource = function(request) {
let heartBeat = null;
this.response = null;
/**
* Send a named event
* @param {String} name The event name
* @param {String} data The event data
* @throws {Error}
*/
this.event = sync(function(name, data) {
if (this.response === null) {
throw new Error('Connection not open');
}
this.response.write(EVENT_FIELD);
this.response.write(name);
this.response.write(CRLF);
this.data(data);
}, this);
/**
* Send data
* @param {String} data The event data
* @throws {Error}
*/
this.data = sync(function(data) {
if (this.response === null) {
throw new Error('Connection not open');
}
this.response.write(DATA_FIELD);
this.response.write(data);
this.response.write(CRLF);
this.response.write(CRLF);
this.response.flush();
}, this);
/**
* Send a comment.
* @param {String} comment The comment
* @throws {Error}
*/
this.comment = sync(function(comment) {
if (this.response === null) {
throw new Error('Connection not open');
}
this.response.write(COMMENT_FIELD);
this.response.write(comment);
this.response.write(CRLF);
this.response.write(CRLF);
this.response.flush();
}, this);
/**
* Close the event source.
* @throws {Error}
*/
this.close = sync(function() {
clearInterval(heartBeat);
this.response.close();
}, this);
/**
* Start the async response. Optionally set additional headers here.
* @param {Object} headers Additional headers (optional)
* @param {Number} heartBeatInterval in seconds (optional. default: 15)
*/
this.start = function(headers, heartBeatInterval) {
if (this.response !== null) {
throw new Error('Connection already open');
}
if (heartBeatInterval === undefined || isNaN(heartBeatInterval)) {
heartBeatInterval = 15;
}
heartBeat = setInterval((function() {
try {
this.ping();
} catch (e) {
clearInterval(heartBeat);
}
}).bind(this), heartBeatInterval * 1000);
this.response = new AsyncResponse(request, 0);
this.response.start(200, objects.merge(headers || {}, {
'Content-Type': 'text/event-stream; charset=utf-8',
'Connection': 'close'
}));
this.response.flush();
};
/**
* Sends a ping to the client
* @throws {Error}
*/
this.ping = sync(function() {
this.response.write('\r');
this.response.flush();
}, this);
return this;
}; | EventSource (or Server-Sent-Events) is a server push technology utilizing
plain HTTP responses. The event stream format defines three types of messages:
* data-only
* named events with data
* comments
One method for each message type is available. Data is expected to be in JSON format.
EventSource instances are thread-safe.
The EventSource wraps an AsyncResponse and is used similarly:
@example
const eventSource = new EventSource(request);
// send headers and start heartbeat
eventSource.start({
"X-Additional-Header": "Foo"
});
setInterval(function() {
eventSource.event('foo-field', 'foo-value');
}, 5 * 1000);
// close the response. No more data can be written
// and the hearbeat stops.
eventSource.close();
// Each EventSource instance exposes the wrapped JSGI asynchronous response
eventSource.response
@param {JSGIRequest} request
@see ringo/jsgi/connector#AsyncResponse
@see https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events | exports.EventSource ( request ) | javascript | ringo/ringojs | modules/ringo/jsgi/eventsource.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/jsgi/eventsource.js | Apache-2.0 |
exports.isEventSourceRequest = (request) => {
return request.headers.accept.indexOf('text/event-stream') > -1;
}; | Static helper to check whether request accepts eventstream.
@param {JSGIRequest} request
@returns {Boolean} whether the accept header matches 'text/event-stream | exports.isEventSourceRequest | javascript | ringo/ringojs | modules/ringo/jsgi/eventsource.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/jsgi/eventsource.js | Apache-2.0 |
const HttpServer = module.exports = function HttpServer(options) {
if (!(this instanceof HttpServer)) {
return new HttpServer(options);
}
const jetty = new Server();
let xmlConfig = null;
Object.defineProperties(this, {
"jetty": {
"value": jetty,
"enumerable": true
},
"xmlConfig": {
"get": function() {
return xmlConfig;
},
"set": function(config) {
if (!(config instanceof XmlConfiguration)) {
throw new Error("Invalid jetty xml configuration");
}
xmlConfig = config;
xmlConfig.configure(jetty);
},
"enumerable": true
},
"contexts": {
"value": {},
"enumerable": true
}
});
if (options !== null && options !== undefined) {
if (typeof(options) === "string") {
// path to jetty xml configuration
this.configure(options);
} else if (typeof(options) === "object" && options.constructor === Object) {
jetty.setStopAtShutdown(options.stopAtShutdown !== false);
jetty.setStopTimeout(options.stopTimeout || 1000);
jetty.setDumpAfterStart(options.dumpAfterStart === true);
jetty.setDumpBeforeStop(options.dumpBeforeStop === true);
}
}
return this;
}; | HttpServer constructor
@name HttpServer
@see <a href="../index/index.html#build">build()</a>
@constructor | HttpServer ( options ) | javascript | ringo/ringojs | modules/ringo/httpserver/httpserver.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/httpserver/httpserver.js | Apache-2.0 |
HttpServer.prototype.configure = function(xmlPath) {
const path = Paths.get(xmlPath);
if (!Files.exists(path)) {
throw Error('Jetty XML configuration "' + xmlPath + '" not found');
}
return this.xmlConfig = new XmlConfiguration(Resource.newResource(path));
}; | Configures this instance with the specified jetty.xml configuration file
@name HttpServer.instance.configure
@param {String} xmlPath The path to the jetty.xml configuration file | HttpServer.prototype.configure ( xmlPath ) | javascript | ringo/ringojs | modules/ringo/httpserver/httpserver.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/httpserver/httpserver.js | Apache-2.0 |
HttpServer.prototype.createHttpConfig = function(options) {
options = objects.merge(options || {}, {
"requestHeaderSize": 8129,
"outputBufferSize": 32768,
"responseHeaderSize": 8129,
"secureScheme": "https"
});
const httpConfig = new HttpConfiguration();
httpConfig.setRequestHeaderSize(options.requestHeaderSize);
httpConfig.setOutputBufferSize(options.outputBufferSize);
httpConfig.setResponseHeaderSize(options.responseHeaderSize);
httpConfig.setSecureScheme(options.secureScheme);
httpConfig.setSendServerVersion(options.sendServerVersion === true);
httpConfig.setSendDateHeader(options.sendDateHeader !== false);
return httpConfig;
}; | Creates a new HttpConfiguration instance
@name HttpServer.instance.createHttpConfig
@param {Object} options An object containing the following properties:
<ul>
<li>requestHeaderSize: (Number, default: 8129) The maximum size of request headers allowed</li>
<li>outputBufferSize: (Number, default: 32768) Sets the size of the buffer into which response content is aggregated before being sent to the client</li>
<li>responseHeaderSize: (Number, default: 8129) The maximum size of response headers</li>
<li>sendServerVersion: (boolean, default: false) Includes the Jetty server version in responses</li>
<li>sendDateHeader: (boolean, default: true) Enables/disables <em>Date</em> header in responses</li>
<li>secureScheme: (String, default: "https") Defines the URI scheme used for confidential and integral redirections</li>
</ul>
@returns {org.eclipse.jetty.server.HttpConfiguration} | HttpServer.prototype.createHttpConfig ( options ) | javascript | ringo/ringojs | modules/ringo/httpserver/httpserver.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/httpserver/httpserver.js | Apache-2.0 |
HttpServer.prototype.createConnector = function(connectionFactory, options) {
const connector = new ServerConnector(this.jetty, options.acceptors || -1,
options.selectors || -1, connectionFactory);
connector.setHost(options.host);
connector.setPort(options.port);
connector.setIdleTimeout(options.idleTimeout || 30000);
connector.setAcceptorPriorityDelta(options.acceptorPriorityDelta || 0);
connector.setAcceptQueueSize(options.acceptQueueSize || 0);
if (typeof(options.name) === "string") {
connector.setName(options.name);
}
return connector;
}; | Creates a new connector
@name HttpServer.instance.createConnector
@param {o.e.j.s.HttpConnectionFactory} connectionFactory The connection factory
@param {Object} options An object containing the following properties:
<ul>
<li>host: (String) </li>
<li>port: (Number)</li>
<li>name: (String) Optional connector name</li>
<li>idleTimeout: (Number, defaults to 30000 millis)</li>
<li>acceptorPriorityDelta: (Number, defaults to 0)</li>
<li>acceptQueueSize: (Number, defaults to 0)</li>
</ul>
@returns org.eclipse.jetty.server.ServerConnector | HttpServer.prototype.createConnector ( connectionFactory , options ) | javascript | ringo/ringojs | modules/ringo/httpserver/httpserver.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/httpserver/httpserver.js | Apache-2.0 |
HttpServer.prototype.createHttpConnector = function(options) {
options = objects.merge(options || {}, {
"host": "0.0.0.0",
"port": 8080
});
const httpConfig = this.createHttpConfig(options);
const connectionFactory = new HttpConnectionFactory(httpConfig);
return this.createConnector(connectionFactory, options);
}; | Creates a new http connector
@name HttpServer.instance.createHttpConnector
@param {Object} options An object containing options
@see <a href="#createConnector">createConnector</a>
@returns org.eclipse.jetty.server.ServerConnector | HttpServer.prototype.createHttpConnector ( options ) | javascript | ringo/ringojs | modules/ringo/httpserver/httpserver.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/httpserver/httpserver.js | Apache-2.0 |
HttpServer.prototype.createSslContextFactory = function(options) {
options = objects.merge(options || {}, {
"verbose": false,
"includeCipherSuites": [],
"excludeCipherSuites": [
"^SSL_.*",
"^TLS_DHE_.*",
"TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA",
"TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA"
],
"includeProtocols": ["TLSv1.2"]
});
const sslContextFactory = new SslContextFactory.Server();
if (typeof options.keyStore === "string") {
sslContextFactory.setKeyStorePath(options.keyStore || null);
sslContextFactory.setKeyStorePassword(options.keyStorePassword || null);
if (typeof options.keyStoreType === "string") {
sslContextFactory.setKeyStoreType(options.keyStoreType);
}
}
sslContextFactory.setKeyManagerPassword(options.keyManagerPassword || null);
if (typeof options.trustStore === "string") {
sslContextFactory.setTrustStorePath(options.trustStore || options.keyStore || null);
sslContextFactory.setTrustStorePassword(options.trustStorePassword ||
options.keyStorePassword || null);
}
sslContextFactory.setIncludeCipherSuites(options.includeCipherSuites);
sslContextFactory.setExcludeCipherSuites(options.excludeCipherSuites);
sslContextFactory.setIncludeProtocols(options.includeProtocols);
if (Array.isArray(options.excludeProtocols)) {
sslContextFactory.setExcludeProtocols(options.excludeProtocols);
}
sslContextFactory.setRenegotiationAllowed(options.allowRenegotiation === true);
if (options.verbose === true) {
log.info(sslContextFactory.dump());
}
return sslContextFactory;
}; | Creates a new SSL context factory
@name HttpServer.instance.createSslContextFactory
@param {Object} options An object containing options (in addition to those
passed to <a href="#createConnector">createConnector</a>):
<ul>
<li>verbose: (boolean, default: false) Dump the SSL configuration at startup</li>
<li>keyStore: (String) The path to the key store</li>
<li>keyStoreType: (String, default: "JKS") The type of keystore</li>
<li>keyStorePassword: (String) The key store password</li>
<li>keyManagerPassword: (String) The key manager password</li>
<li>trustStore: (String, default: options.keyStore) The path to an optional trust store</li>
<li>trustStorePassword: (String, default: options.keysStorePassword) The password of the optional trust store</li>
<li>includeCipherSuites: (Array, default: []) An array of cipher suites to enable</li>
<li>excludeCipherSuites: (Array, default: ["^SSL_.*", "^TLS_DHE_.*", "TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA", "TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA"]) An array of cipher suites to disable</li>
<li>includeProtocols: (Array, default: ["TLSv1.2"]) An array containing protocols to support</li>
<li>excludeProtocols: (Array, default: null) An array of protocols to exclude</li>
<li>allowRenegotiation: (boolean, default: false) Enables TLS renegotiation</li>
</ul>
@see <a href="#createConnector">createConnector</a>
@returns org.eclipse.jetty.util.ssl.SslContextFactory; | HttpServer.prototype.createSslContextFactory ( options ) | javascript | ringo/ringojs | modules/ringo/httpserver/httpserver.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/httpserver/httpserver.js | Apache-2.0 |
HttpServer.prototype.createHttpsConnector = function(options) {
options = objects.merge(options || {}, {
"host": "0.0.0.0",
"port": 8443,
"sniHostCheck": true,
"stsMaxAgeSeconds": -1,
"stsIncludeSubdomains": false
});
const sslContextFactory = this.createSslContextFactory(options);
const sslConnectionFactory = new SslConnectionFactory(sslContextFactory,
HttpVersion.HTTP_1_1.toString());
const httpsConfig = this.createHttpConfig(options);
const customizer = new SecureRequestCustomizer();
customizer.setSniHostCheck(options.sniHostCheck === true);
if (!isNaN(options.stsMaxAgeSeconds)) {
customizer.setStsMaxAge(options.stsMaxAgeSeconds);
}
customizer.setStsIncludeSubDomains(options.stsIncludeSubdomains === true);
httpsConfig.addCustomizer(customizer);
const httpConnectionFactory = new HttpConnectionFactory(httpsConfig);
return this.createConnector([sslConnectionFactory, httpConnectionFactory], options);
}; | Creates a new https connector
@name HttpServer.instance.createHttpsConnector
@param {Object} options An object containing options (in addition to those
passed to <a href="#createSslContextFactory">createSslContextFactory</a>):
<ul>
<li>sniHostCheck: (boolean, default: true) If true the SNI Host name must match when there is an SNI certificate.</li>
<li>stsMaxAgeSeconds: (Number, default: -1) The max age in seconds for a Strict-Transport-Security response header (-1 means no header is sent)</li>
<li>stsIncludeSubdomains: (boolean, default: false) If true a include subdomain property is sent with any Strict-Transport-Security header</li>
</ul>
@see <a href="#createSslContextFactory">createSslContextFactory</a>
@see <a href="#createConnector">createConnector</a>
@returns org.eclipse.jetty.server.ServerConnector | HttpServer.prototype.createHttpsConnector ( options ) | javascript | ringo/ringojs | modules/ringo/httpserver/httpserver.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/httpserver/httpserver.js | Apache-2.0 |
HttpServer.prototype.createHttpListener = function(options) {
const connector = this.createHttpConnector(options);
this.jetty.addConnector(connector);
return connector;
}; | Creates a new http listener and adds it to the encapsulated jetty http server
@name HttpServer.instance.createHttpListener
@param {Object} options see <a href="#createHttpConnector">createHttpConnector</a>
@returns {org.eclipse.jetty.server.ServerConnector} | HttpServer.prototype.createHttpListener ( options ) | javascript | ringo/ringojs | modules/ringo/httpserver/httpserver.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/httpserver/httpserver.js | Apache-2.0 |
HttpServer.prototype.createHttpsListener = function(options) {
const connector = this.createHttpsConnector(options);
this.jetty.addConnector(connector);
return connector;
}; | Creates a new http listener and adds it to the encapsulated jetty http server
@name HttpServer.instance.createHttpsListener
@param {Object} options see <a href="#createHttpsConnector">createHttpsConnector</a>
@returns {org.eclipse.jetty.server.ServerConnector} | HttpServer.prototype.createHttpsListener ( options ) | javascript | ringo/ringojs | modules/ringo/httpserver/httpserver.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/httpserver/httpserver.js | Apache-2.0 |
HttpServer.prototype.getHandlerCollection = function() {
let handlerCollection = this.jetty.getHandler();
if (handlerCollection === null) {
handlerCollection = new HandlerCollection();
this.jetty.setHandler(handlerCollection);
}
return handlerCollection;
}; | Returns the handler collection of the encapsulated jetty server, instantiating
it if it doesn't exist already
@name HttpServer.instance.getHandlerCollection
@returns {org.eclipse.jetty.server.handler.HandlerCollection}; | HttpServer.prototype.getHandlerCollection ( ) | javascript | ringo/ringojs | modules/ringo/httpserver/httpserver.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/httpserver/httpserver.js | Apache-2.0 |
HttpServer.prototype.getContextHandlerCollection = function() {
const handlerCollection = this.getHandlerCollection();
let contextHandlerCollection =
handlerCollection.getChildHandlerByClass(ContextHandlerCollection);
if (contextHandlerCollection === null) {
contextHandlerCollection = new ContextHandlerCollection();
handlerCollection.addHandler(contextHandlerCollection);
}
return contextHandlerCollection;
}; | Returns the context handler collection of the encapsulated jetty server,
instantiating it if it doesn't exist already
@name HttpServer.instance.getContextHandlerCollection
@returns {org.eclipse.jetty.server.handler.ContextHandlerCollection}; | HttpServer.prototype.getContextHandlerCollection ( ) | javascript | ringo/ringojs | modules/ringo/httpserver/httpserver.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/httpserver/httpserver.js | Apache-2.0 |
HttpServer.prototype.addContext = function(context) {
this.contexts[context.getKey()] = context;
if (this.jetty.isRunning()) {
context.contextHandler.start();
}
return context;
}; | Adds a context and starts it
@name HttpServer.instance.addContext
@param {Context} context The context to add
@returns {Context} The context passed as argument | HttpServer.prototype.addContext ( context ) | javascript | ringo/ringojs | modules/ringo/httpserver/httpserver.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/httpserver/httpserver.js | Apache-2.0 |
HttpServer.prototype.enableSessions = function(options) {
options || (options = {});
// if random is null, jetty will fall back to a SecureRandom in its initRandom()
const sessionIdManager = new DefaultSessionIdManager(this.jetty, options.random || null);
sessionIdManager.setWorkerName(options.name || "node1");
this.jetty.setSessionIdManager(sessionIdManager);
return sessionIdManager;
}; | Enables sessions in the jetty server
@name HttpServer.instance.enableSessions
@params {Object} options An object containing options
@see <a href="../builder/index.html#HttpServerBuilder.prototype.enableSessions">HttpServerBuilder.enableSessions()</a>
@returns {org.eclipse.jetty.server.session.DefaultSessionIdManager} | HttpServer.prototype.enableSessions ( options ) | javascript | ringo/ringojs | modules/ringo/httpserver/httpserver.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/httpserver/httpserver.js | Apache-2.0 |
HttpServer.prototype.serveApplication = function(mountpoint, app, options) {
if (typeof(mountpoint) !== "string") {
throw new Error("Missing mountpoint argument");
}
options || (options = {});
if (typeof(options.sameSiteCookies) === "string") {
options.sameSiteCookies = options.sameSiteCookies.toUpperCase();
const allowedValues = Array.from(HttpCookie.SameSite.values()).map(value => value.toString());
if (!allowedValues.includes(options.sameSiteCookies)) {
throw new Error("Invalid sameSiteCookies option, must be one of " + allowedValues.join(", "));
}
}
options = {
"security": options.security !== false,
"sessions": options.sessions !== false,
"sessionsMaxInactiveInterval": options.sessionsMaxInactiveInterval || null,
"cookieName": options.cookieName || null,
"cookieDomain": options.cookieDomain || null,
"cookiePath": options.cookiePath || null,
"cookieMaxAge": options.cookieMaxAge || -1,
"httpOnlyCookies": options.httpOnlyCookies !== false,
"secureCookies": options.secureCookies === true,
"sameSiteCookies": options.sameSiteCookies || null,
"statistics": options.statistics === true,
"virtualHosts": options.virtualHosts
};
const parentContainer = this.getContextHandlerCollection();
const context = new ApplicationContext(parentContainer, mountpoint, options);
context.serve(app);
return this.addContext(context);
}; | @name HttpServer.instance.serveApplication
@see <a href="../builder/index.html#HttpServerBuilder.prototype.serveApplication">HttpServerBuilder.serveApplication()</a>
@returns {Context} | HttpServer.prototype.serveApplication ( mountpoint , app , options ) | javascript | ringo/ringojs | modules/ringo/httpserver/httpserver.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/httpserver/httpserver.js | Apache-2.0 |
HttpServer.prototype.serveStatic = function(mountpoint, directory, options) {
if (typeof(mountpoint) !== "string") {
throw new Error("Missing mountpoint argument");
}
if (typeof(directory) !== "string") {
throw new Error("Missing directory argument");
}
const path = Paths.get(directory);
if (!Files.exists(path) || !Files.isDirectory(path)) {
throw new Error("Directory '" + directory + "' doesn't exist or is not a directory");
}
options || (options = {});
const initParameters = {
"acceptRanges": options.acceptRanges === true,
"dirAllowed": options.allowDirectoryListing === true,
"gzip": options.gzip === true,
"stylesheet": options.stylesheet || null,
"etags": options.etags !== false,
"maxCacheSize": options.maxCacheSize || 0,
"maxCachedFileSize": options.maxCachedFileSize || 0,
"maxCachedFiles": options.maxCachedFiles || 0,
"cacheControl": options.cacheControl || null,
"otherGzipFileExtensions": options.gzipExtensions || null
};
const parentContainer = this.getContextHandlerCollection();
const context = new StaticContext(parentContainer, mountpoint, {
"security": options.security === true,
"sessions": options.sessions === true,
"sessionsMaxInactiveInterval": options.sessionsMaxInactiveInterval || null,
"cookieName": options.cookieName || null,
"cookieDomain": options.cookieDomain || null,
"cookiePath": options.cookiePath || null,
"cookieMaxAge": options.cookieMaxAge || -1,
"httpOnlyCookies": options.httpOnlyCookies !== false,
"secureCookies": options.secureCookies === true,
"sameSiteCookies": options.sameSiteCookies || null,
"statistics": options.statistics === true,
"virtualHosts": options.virtualHosts
});
context.serve(directory, initParameters);
return this.addContext(context);
}; | @name HttpServer.instance.serveStatic
@see <a href="../builder/index.html#HttpServerBuilder.prototype.serveStatic">HttpServerBuilder.serveStatic()</a>
@returns {Context} | HttpServer.prototype.serveStatic ( mountpoint , directory , options ) | javascript | ringo/ringojs | modules/ringo/httpserver/httpserver.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/httpserver/httpserver.js | Apache-2.0 |
HttpServer.prototype.enableConnectionStatistics = function() {
ServerConnectionStatistics.addToAllConnectors(this.jetty);
}; | @name HttpServer.instance.enableConnectionStatistics
@see <a href="../builder/index.html#HttpServerBuilder.prototype.enableConnectionStatistics">HttpServerBuilder.enableConnectionStatistics()</a> | HttpServer.prototype.enableConnectionStatistics ( ) | javascript | ringo/ringojs | modules/ringo/httpserver/httpserver.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/httpserver/httpserver.js | Apache-2.0 |
HttpServer.prototype.start = function() {
this.jetty.start();
this.jetty.getConnectors().forEach(function(connector) {
log.info("Server on {}:{} started", connector.getHost(), connector.getPort());
});
}; | Starts the jetty http server
@name HttpServer.instance.start | HttpServer.prototype.start ( ) | javascript | ringo/ringojs | modules/ringo/httpserver/httpserver.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/httpserver/httpserver.js | Apache-2.0 |
HttpServer.prototype.stop = function() {
return this.jetty.stop();
}; | Stops the jetty http server
@name HttpServer.instance.stop | HttpServer.prototype.stop ( ) | javascript | ringo/ringojs | modules/ringo/httpserver/httpserver.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/httpserver/httpserver.js | Apache-2.0 |
HttpServer.prototype.destroy = function() {
return this.jetty.destroy();
}; | Destroys the jetty http server
@name HttpServer.instance.destroy | HttpServer.prototype.destroy ( ) | javascript | ringo/ringojs | modules/ringo/httpserver/httpserver.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/httpserver/httpserver.js | Apache-2.0 |
HttpServer.prototype.isRunning = function() {
return this.jetty.isRunning();
}; | Returns true if the server is running
@name HttpServer.instance.isRunning
@returns {boolean} True if the server is running | HttpServer.prototype.isRunning ( ) | javascript | ringo/ringojs | modules/ringo/httpserver/httpserver.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/httpserver/httpserver.js | Apache-2.0 |
const WebSocket = module.exports = function() {
this.session = null;
// make WebSocket a java event-emitter (mixin)
JavaEventEmitter.call(this, [WebSocketListener], {
"onWebSocketConnect": "connect",
"onWebSocketClose": "close",
"onWebSocketText": "text",
"onWebSocketBinary": "binary",
"onWebSocketError": "error"
});
return this;
}; | Provides support for WebSocket connections in the HTTP server.
WebSocket is an event emitter that supports the
following events:
* **connect**: called when a new websocket connection is accepted
* **close**: called when an established websocket connection closes
* **text**: called when a text message arrived
* **binary**: called when a binary message arrived
* **error**: called when an error occurred
@name EventSource | module.exports ( ) | javascript | ringo/ringojs | modules/ringo/httpserver/websocket.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/httpserver/websocket.js | Apache-2.0 |
WebSocket.prototype.close = function() {
try {
this.session.close();
} finally {
this.session = null;
}
}; | Closes the WebSocket connection.
@name WebSocket.instance.close
@function | WebSocket.prototype.close ( ) | javascript | ringo/ringojs | modules/ringo/httpserver/websocket.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/httpserver/websocket.js | Apache-2.0 |
WebSocket.prototype.send = function(message) {
return this.sendString(message);
}; | Send a string over the WebSocket.
@param {String} message a string
@name WebSocket.instance.send
@deprecated
@see #sendString
@function | WebSocket.prototype.send ( message ) | javascript | ringo/ringojs | modules/ringo/httpserver/websocket.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/httpserver/websocket.js | Apache-2.0 |
WebSocket.prototype.sendString = function(message) {
if (!this.isOpen()) {
throw new Error("Not connected");
}
this.session.getRemote().sendString(message);
}; | Send a string over the WebSocket. This method
blocks until the message has been transmitted
@param {String} message a string
@name WebSocket.instance.sendString
@function | WebSocket.prototype.sendString ( message ) | javascript | ringo/ringojs | modules/ringo/httpserver/websocket.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/httpserver/websocket.js | Apache-2.0 |
WebSocket.prototype.sendBinary = function(byteArray, offset, length) {
if (!this.isOpen()) {
throw new Error("Not connected");
}
const buffer = ByteBuffer.wrap(byteArray, parseInt(offset, 10) || 0,
parseInt(length, 10) || byteArray.length);
return this.session.getRemote().sendBytes(buffer);
}; | Send a byte array over the WebSocket. This method
blocks until the message as been transmitted.
@param {ByteArray} byteArray The byte array to send
@param {Number} offset Optional offset (defaults to zero)
@param {Number} length Optional length (defaults to the
length of the byte array)
@name WebSocket.instance.sendBinary
@function | WebSocket.prototype.sendBinary ( byteArray , offset , length ) | javascript | ringo/ringojs | modules/ringo/httpserver/websocket.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/httpserver/websocket.js | Apache-2.0 |
WebSocket.prototype.isOpen = function() {
return this.session !== null && this.session.isOpen();
}; | Check whether the WebSocket is open.
@name WebSocket.instance.isOpen
@return {Boolean} true if the connection is open
@function | WebSocket.prototype.isOpen ( ) | javascript | ringo/ringojs | modules/ringo/httpserver/websocket.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/httpserver/websocket.js | Apache-2.0 |
HttpServerBuilder.prototype.configure = function(xmlPath) {
this.server.configure(xmlPath);
return this;
}; | Configures the HttpServer with the jetty.xml configuration file
@name HttpServerBuilder.instance.configure
@param {String} xmlPath The path to the jetty.xml configuration file
@returns {HttpServerBuilder} | HttpServerBuilder.prototype.configure ( xmlPath ) | javascript | ringo/ringojs | modules/ringo/httpserver/builder.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/httpserver/builder.js | Apache-2.0 |
HttpServerBuilder.prototype.serveApplication = function(mountpoint, app, options) {
this.currentContext = this.server.serveApplication(mountpoint, app, options);
return this;
}; | Configures the http server to serve an application at the specified mountpoint
@name HttpServerBuilder.instance.serveApplication
@param {String} mountpoint The mountpoint to server the application at
@param {String|Function} app The application to server. Can be defined either
as string specifying the application module to load, or as a function.
@param {Object} options An object containing the following options:
<ul>
<li>security: (boolean, default: true)</li>
<li>sessions: (boolean, default: true)</li>
<li>sessionsMaxInactiveInterval: (Number, default: null) </li>
<li>cookieName: (String, default: null)</li>
<li>cookieDomain: (String, default: null) The domain of session cookies</li>
<li>cookiePath: (String, default: null) The path of session cookies</li>
<li>cookieMaxAge: (Number, default: -1) The max age of session cookies, -1 means </li>
<li>httpOnlyCookies: (boolean, default: true) Enable/disables the HttpOnly flag of session cookies</li>
<li>secureCookies: (boolean, default: false) Enable/disables the Secure flag of session cookies</li>
<li>sameSiteCookies: (String, default: null) Sets the SameSite flag of session cookies. Possible values: "lax" (default of modern Browsers), "strict" or "none"</li>
<li>statistics: (boolean, default: false) Enable request statistics</li>
<li>virtualHosts: (String|Array) Virtual host(s) under which this application should be reachable</li>
<ul>
@returns {HttpServerBuilder} | HttpServerBuilder.prototype.serveApplication ( mountpoint , app , options ) | javascript | ringo/ringojs | modules/ringo/httpserver/builder.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/httpserver/builder.js | Apache-2.0 |
HttpServerBuilder.prototype.serveStatic = function(mountpoint, directory, options) {
this.currentContext = this.server.serveStatic(mountpoint, directory, options);
return this;
}; | Configures the http server to serve static files at the specified mountpoint
@name HttpServerBuilder.instance.serveStatic
@param {String} mountpoint The mountpoint to server the static files at
@param {String} directory The directory containing the static files
@param {Object} options An object containing the following options:
<ul>
<li>acceptRanges: (boolean, default: false) Enables range requests</li>
<li>allowDirectoryListing: (boolean, default: false) Enables directory listing</li>
<li>gzip: (boolean, default: false) Enables gzip compression</li>
<li>stylesheet: (String, default: null) The location to an optional stylesheet</li>
<li>etags: (boolean, default: true) Enables/disables ETag generation for static files</li>
<li>maxCacheSize: (Number, default: 0) The maximum total size of the cache (0 meaning no cache at all)</li>
<li>maxCachedFileSize: (Number, default: 0) The maximum size of a file to cache</li>
<li>maxCachedFiles: (Number, default: 0) The maximum number of files to cache</li>
<li>cacheControl: (String, default: null) If set, all files are served with this cache-control response header</li>
<li>gzipExtensions: (String, default: null) Other file extensions that signify that a file is already compressed, eg. ".svgz"</li>
</ul>
@returns {HttpServerBuilder} | HttpServerBuilder.prototype.serveStatic ( mountpoint , directory , options ) | javascript | ringo/ringojs | modules/ringo/httpserver/builder.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/httpserver/builder.js | Apache-2.0 |
HttpServerBuilder.prototype.http = function(options) {
this.server.createHttpListener(options);
return this;
}; | Configures a HTTP listener with the specified options
@name HttpServerBuilder.instance.http
@param {Object} options An object containing the following options:
<ul>
<li>host: (String, default: "0.0.0.0") </li>
<li>port: (Number, default: 8080)</li>
<li>requestHeaderSize: (Number, default: 8129) The maximum size of request headers allowed</li>
<li>outputBufferSize: (Number, default: 32768) Sets the size of the buffer into which response content is aggregated before being sent to the client</li>
<li>responseHeaderSize: (Number, default: 8129) The maximum size of response headers</li>
<li>sendServerVersion: (boolean, default: false) Includes the Jetty server version in responses</li>
<li>sendDateHeader: (boolean, default: true) Enables/disables <em>Date</em> header in responses</li>
<li>secureScheme: (String, default: "https") Defines the URI scheme used for confidential and integral redirections</li>
</ul>
@returns {HttpServerBuilder} | HttpServerBuilder.prototype.http ( options ) | javascript | ringo/ringojs | modules/ringo/httpserver/builder.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/httpserver/builder.js | Apache-2.0 |
HttpServerBuilder.prototype.https = function(options) {
this.server.createHttpsListener(options);
return this;
}; | Configures a HTTPS listener with the specified options
@name HttpServerBuilder.instance.https
@param {Object} options An object containing the following options:
<ul>
<li>host: (String, default: "0.0.0.0") </li>
<li>port: (Number, default: 8443)</li>
<li>sniHostCheck: (boolean, default: true) If true the SNI Host name must match when there is an SNI certificate.</li>
<li>stsMaxAgeSeconds: (Number, default: -1) The max age in seconds for a Strict-Transport-Security response header (-1 means no header is sent)</li>
<li>stsIncludeSubdomains: (boolean, default: false) If true a include subdomain property is sent with any Strict-Transport-Security header</li>
<li>requestHeaderSize: (Number, default: 8129) The maximum size of request headers allowed</li>
<li>outputBufferSize: (Number, default: 32768) Sets the size of the buffer into which response content is aggregated before being sent to the client</li>
<li>responseHeaderSize: (Number, default: 8129) The maximum size of response headers</li>
<li>sendServerVersion: (boolean, default: false) Includes the Jetty server version in responses</li>
<li>sendDateHeader: (boolean, default: true) Enables/disables <em>Date</em> header in responses</li>
<li>secureScheme: (String, default: "https") Defines the URI scheme used for confidential and integral redirections</li>
<li>verbose: (boolean, default: false) Dump the SSL configuration at startup</li>
<li>keyStore: (String) The path to the key store</li>
<li>keyStoreType: (String, default: "JKS") The type of keystore</li>
<li>keyStorePassword: (String) The key store password</li>
<li>keyManagerPassword: (String) The key manager password</li>
<li>trustStore: (String, default: options.keyStore) The path to an optional trust store</li>
<li>trustStorePassword: (String, default: options.keysStorePassword) The password of the optional trust store</li>
<li>includeCipherSuites: (Array, default: []) An array of cipher suites to enable</li>
<li>excludeCipherSuites: (Array, default: ["^SSL_.*", "^TLS_DHE_.*", "TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA", "TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA"]) An array of cipher suites to disable</li>
<li>includeProtocols: (Array, default: ["TLSv1.2"]) An array containing protocols to support</li>
<li>excludeProtocols: (Array, default: null) An array of protocols to exclude</li>
<li>allowRenegotiation: (boolean, default: false) Enables TLS renegotiation</li>
</ul>
@returns {HttpServerBuilder} | HttpServerBuilder.prototype.https ( options ) | javascript | ringo/ringojs | modules/ringo/httpserver/builder.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/httpserver/builder.js | Apache-2.0 |
HttpServerBuilder.prototype.enableSessions = function(options) {
this.server.enableSessions(options);
return this;
}; | Enables sessions with the specified options
@name HttpServerBuilder.instance.enableSessions
@param {Object} options An object containing the following options:
<ul>
<li>name: (String, default: "node1") The worker name that is appended to the session ID</li>
<li>random: (java.util.Random, default: null) A random number generator to use for session IDs</li>
</ul>
@returns {HttpServerBuilder} | HttpServerBuilder.prototype.enableSessions ( options ) | javascript | ringo/ringojs | modules/ringo/httpserver/builder.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/httpserver/builder.js | Apache-2.0 |
HttpServerBuilder.prototype.enableConnectionStatistics = function() {
this.server.enableConnectionStatistics();
return this;
}; | Enables statistics for all connectors
@name HttpServerBuilder.instance.enableConnectionStatistics
@returns {HttpServerBuilder} | HttpServerBuilder.prototype.enableConnectionStatistics ( ) | javascript | ringo/ringojs | modules/ringo/httpserver/builder.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/httpserver/builder.js | Apache-2.0 |
HttpServerBuilder.prototype.start = function() {
this.server.start();
return this;
}; | Starts the http server
@name HttpServerBuilder.instance.start
@returns {HttpServerBuilder} | HttpServerBuilder.prototype.start ( ) | javascript | ringo/ringojs | modules/ringo/httpserver/builder.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/httpserver/builder.js | Apache-2.0 |
HttpServerBuilder.prototype.addWebSocket = function(path, onConnect, onCreate, initParams) {
this.currentContext.addWebSocket(path, onConnect, onCreate, initParams);
return this;
}; | Adds a websocket connector to the current application context., which must have
been configured before.
@name HttpServerBuilder.instance.addWebSocket
@param {String} path The path of the websocket connector
@param {Function} onConnect An optional callback function invoked with the websocket and the session as arguments
@param {Function} onCreate An optional callback function invoked with the request and response objects
as arguments. If this callback returns a value other than true, the connection is aborted.
@param {Object} initParams An object containing servlet init parameters
(see <a href="https://www.eclipse.org/jetty/javadoc/current/org/eclipse/jetty/websocket/servlet/WebSocketServlet.html">org.eclipse.jetty.websocket.servlet.WebSocketServlet</a>
@returns {HttpServerBuilder} | HttpServerBuilder.prototype.addWebSocket ( path , onConnect , onCreate , initParams ) | javascript | ringo/ringojs | modules/ringo/httpserver/builder.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/httpserver/builder.js | Apache-2.0 |
HttpServerBuilder.prototype.addEventSource = function(path, onConnect, initParams) {
this.currentContext.addEventSource(path, onConnect, initParams);
return this;
}; | Adds an EventSource connnector to the current application context, which must have
been configured before.
@name HttpServerBuilder.instance.addEventSource
@param {String} path The path of the EventSource connector
@param {Function} onConnect An optional callback function invoked with the EventSource
instance and the request object as arguments
@param {Object} initParams An object containing servlet init parameters
(see <a href="https://www.eclipse.org/jetty/javadoc/current/org/eclipse/jetty/servlets/EventSourceServlet.html">org.eclipse.jetty.servlets.EventSourceServlet</a>)
@returns {HttpServerBuilder} | HttpServerBuilder.prototype.addEventSource ( path , onConnect , initParams ) | javascript | ringo/ringojs | modules/ringo/httpserver/builder.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/httpserver/builder.js | Apache-2.0 |
HttpServerBuilder.prototype.addFilter = function(path, filter, initParams) {
this.currentContext.addFilter(path, filter, initParams);
return this;
}; | Adds a servlet filter to the chain of the current application context, which must have
been configured before.
@name HttpServerBuilder.instance.addFilter
@param {String} path The path spec of this filter
@param {jakarta.servlet.Filter} filter The filter to add
@param {Object} initParams An object containing init parameters to pass to the <a href="https://www.eclipse.org/jetty/javadoc/current/org/eclipse/jetty/servlet/FilterHolder.html">org.eclipse.jetty.servlet.FilterHolder</a>
@returns {HttpServerBuilder} | HttpServerBuilder.prototype.addFilter ( path , filter , initParams ) | javascript | ringo/ringojs | modules/ringo/httpserver/builder.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/httpserver/builder.js | Apache-2.0 |
exports.build = function(options) {
return new HttpServerBuilder(options);
}; | Returns a new HttpServerBuilder instance
@param {String|Object} options Either the path to the jetty.xml configuration
file, or an object containing the following properties:
<ul>
<li>stopAtShutdown: (boolean, default: true)</li>
<li>stopTimeout: (Number, default: 1000 millis)</li>
<li>dumpBeforeStart: (boolean, default: false)</li>
<li>dumpBeforeStop: (boolean, default: false)</li>
</ul>
@returns {HttpServerBuilder} A newly created <a href="../builder/index.html">HttpServerBuilder</a> instance | exports.build ( options ) | javascript | ringo/ringojs | modules/ringo/httpserver/index.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/httpserver/index.js | Apache-2.0 |
exports.init = function(path) {
// parse command line options
options = {};
const args = system.args.slice(1);
try {
// remove command from command line arguments
options = utils.parseOptions(args, options);
} catch (error) {
log.error("Error parsing options:", error);
system.exit(1);
}
options.path = path;
if (options.path === undefined) {
if (args[0]) {
// take app module from command line
options.path = fs.resolve(fs.workingDirectory(), args[0]);
} else {
options.path = fs.workingDirectory();
}
}
// if argument is a directory assume app in main.js
if (fs.isDirectory(options.path)) {
options.path = fs.join(options.path, "main");
}
log.info("Start app module at", options.path);
httpServer = new HttpServer();
httpServer.serveApplication("/", options.path);
httpServer.createHttpListener(options);
const app = require(options.path);
if (typeof(app.init) === "function") {
app.init(httpServer);
}
return httpServer;
}; | Daemon life cycle function invoked by init script. Creates a new Server with
the application at `appPath`. If the application exports a function called
`init`, it will be invoked with the new server as argument.
@param {String} path Optional application file name or module id.
If undefined, the first command line argument will be used as application.
If there are no command line arguments, module `main` in the current
working directory is used.
@returns {Server} the Server instance. | exports.init ( path ) | javascript | ringo/ringojs | modules/ringo/httpserver/index.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/httpserver/index.js | Apache-2.0 |
exports.start = function() {
if (httpServer !== null && httpServer.isRunning()) {
return httpServer;
}
httpServer.start();
const app = require(options.path);
if (typeof(app.start) === "function") {
app.start(httpServer);
}
return httpServer;
}; | Daemon life cycle function invoked by init script. Starts the Server created
by `init()`. If the application exports a function called `start`, it will be
invoked with the server as argument immediately after it has started.
@returns {Server} the Server instance. | exports.start ( ) | javascript | ringo/ringojs | modules/ringo/httpserver/index.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/httpserver/index.js | Apache-2.0 |
exports.stop = function() {
if (httpServer !== null && !httpServer.isRunning()) {
return httpServer;
}
const app = require(options.path);
if (typeof app.stop === "function") {
app.stop(httpServer);
}
httpServer.stop();
return httpServer;
}; | Daemon life cycle function invoked by init script. Stops the Server started
by `start()`.
@returns {Server} the Server instance. If the application exports a function
called `stop`, it will be invoked with the server as argument immediately
before it is stopped.
@returns {Server} the Server instance. | exports.stop ( ) | javascript | ringo/ringojs | modules/ringo/httpserver/index.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/httpserver/index.js | Apache-2.0 |
exports.destroy = function() {
if (httpServer !== null) {
const app = require(options.path);
if (typeof(app.destroy) === "function") {
app.destroy(httpServer);
}
httpServer.destroy();
}
try {
return httpServer;
} finally {
httpServer = null;
}
}; | Daemon life cycle function invoked by init script. Frees any resources
occupied by the Server instance. If the application exports a function
called `destroy`, it will be invoked with the server as argument.
@returns {Server} the Server instance. | exports.destroy ( ) | javascript | ringo/ringojs | modules/ringo/httpserver/index.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/httpserver/index.js | Apache-2.0 |
exports.main = function(path) {
exports.init(path);
exports.start();
require("ringo/engine").addShutdownHook(function() {
exports.stop();
exports.destroy();
});
// return the server instance
return httpServer;
}; | Main function to start an HTTP server from the command line.
It automatically adds a shutdown hook which will stop and destroy the server at the JVM termination.
@param {String} path optional application file name or module id.
@returns {Server} the Server instance.
@example // starts the current module via module.id as web application
require("ringo/httpserver").main(module.id);
// starts the module "./app/actions" as web application
require("ringo/httpserver").main(module.resolve('./app/actions')); | exports.main ( path ) | javascript | ringo/ringojs | modules/ringo/httpserver/index.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/httpserver/index.js | Apache-2.0 |
this.close = function() {
if (conn) {
conn.close();
log.debug("Closed connection", conn);
}
}; | Closes the EventSource connection.
@name EventSource.instance.close | this.close ( ) | javascript | ringo/ringojs | modules/ringo/httpserver/eventsource.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/httpserver/eventsource.js | Apache-2.0 |
this.data = function(msg) {
if (conn) {
try {
conn.data(msg);
} catch (e) {
if (log.isDebugEnabled()) {
log.error("Error sending data to {}:", conn, e);
}
conn = null;
this.emit("close");
}
}
}; | Send a default event to the client
@param {String} msg a string
@name EventSource.instance.data | this.data ( msg ) | javascript | ringo/ringojs | modules/ringo/httpserver/eventsource.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/httpserver/eventsource.js | Apache-2.0 |
this.event = function(name, msg) {
if (conn) {
try {
conn.event(name, msg);
} catch (e) {
if (log.isDebugEnabled()) {
log.error("Error sending '{}' event to {}:", name, conn, e);
}
conn = null;
this.emit("close");
}
}
}; | Send a named event
@param {String} name a string
@param {String} msg a string
@name EventSource.instance.event | this.event ( name , msg ) | javascript | ringo/ringojs | modules/ringo/httpserver/eventsource.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/httpserver/eventsource.js | Apache-2.0 |
this.comment = function(msg) {
if (conn) {
try {
conn.comment(msg);
} catch (e) {
if (log.isDebugEnabled()) {
log.error("Error sending comment to {}:", conn, e);
}
conn = null;
this.emit("close");
}
}
}; | Send a comment
@param {String} msg a string
@name EventSource.instance.comment | this.comment ( msg ) | javascript | ringo/ringojs | modules/ringo/httpserver/eventsource.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/httpserver/eventsource.js | Apache-2.0 |
module.exports = function EventSourceWrapper() {
let conn = null;
/**
* Closes the EventSource connection.
* @name EventSource.instance.close
*/
this.close = function() {
if (conn) {
conn.close();
log.debug("Closed connection", conn);
}
};
/**
* Send a default event to the client
* @param {String} msg a string
* @name EventSource.instance.data
*/
this.data = function(msg) {
if (conn) {
try {
conn.data(msg);
} catch (e) {
if (log.isDebugEnabled()) {
log.error("Error sending data to {}:", conn, e);
}
conn = null;
this.emit("close");
}
}
};
/**
* Send a named event
* @param {String} name a string
* @param {String} msg a string
* @name EventSource.instance.event
*/
this.event = function(name, msg) {
if (conn) {
try {
conn.event(name, msg);
} catch (e) {
if (log.isDebugEnabled()) {
log.error("Error sending '{}' event to {}:", name, conn, e);
}
conn = null;
this.emit("close");
}
}
};
/**
* Send a comment
* @param {String} msg a string
* @name EventSource.instance.comment
*/
this.comment = function(msg) {
if (conn) {
try {
conn.comment(msg);
} catch (e) {
if (log.isDebugEnabled()) {
log.error("Error sending comment to {}:", conn, e);
}
conn = null;
this.emit("close");
}
}
};
/** @ignore **/
this.setConnection = function(connection) {
conn = connection;
};
JavaEventEmitter.call(this, [EventSource]);
this.addListener("open", function(connection) {
conn = connection;
});
return this;
}; | Provides support for EventSource in the HTTP server.
EventSource is an event emitter that supports the
following events:
* **open**: called when a new eventsource connection is accepted
* **close**: called when an established eventsource connection closes
@name EventSource | EventSourceWrapper ( ) | javascript | ringo/ringojs | modules/ringo/httpserver/eventsource.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/httpserver/eventsource.js | Apache-2.0 |
const Context = module.exports = function Context(parentContainer, mountpoint, options) {
let statisticsHandler = null;
if (options.statistics === true) {
// add statistics handler and use it as parent container for
// the context handler created below
statisticsHandler = new StatisticsHandler();
parentContainer.addHandler(statisticsHandler);
parentContainer = statisticsHandler;
}
const contextHandler = new ServletContextHandler(parentContainer, mountpoint,
options.sessions, options.security);
if (options.virtualHosts) {
contextHandler.setVirtualHosts(Array.isArray(options.virtualHosts) ?
options.virtualHosts : [String(options.virtualHosts)]);
}
const sessionHandler = contextHandler.getSessionHandler();
if (sessionHandler !== null) {
if (Number.isInteger(options.sessionsMaxInactiveInterval)) {
sessionHandler.setMaxInactiveInterval(options.sessionsMaxInactiveInterval);
}
if (typeof(options.sameSiteCookies) === "string") {
sessionHandler.setSameSite(HttpCookie.SameSite.valueOf(options.sameSiteCookies));
}
const sessionCookieConfig = sessionHandler.getSessionCookieConfig();
sessionCookieConfig.setHttpOnly(options.httpOnlyCookies !== false);
sessionCookieConfig.setSecure(options.secureCookies === true);
if (typeof(options.cookieName) === "string") {
sessionCookieConfig.setName(options.cookieName);
}
sessionCookieConfig.setDomain(options.cookieDomain || null);
sessionCookieConfig.setPath(options.cookiePath || null);
sessionCookieConfig.setMaxAge(options.cookieMaxAge || -1);
}
Object.defineProperties(this, {
/**
* The statistics handler (if options.statistics is set to true)
* @type org.eclipse.jetty.server.handler.StatisticsHandler
*/
"statisticsHandler": {
"value": statisticsHandler,
"enumerable": true
},
/**
* The servlet context handler
* @type org.eclipse.jetty.servlet.ServletContextHandler
*/
"contextHandler": {
"value": contextHandler,
"enumerable": true
}
});
return this;
}; | Base context handler constructor
@param {org.eclipse.jetty.server.handler.ContextHandlerCollection} parentContainer The parent container of this context handler
@param {String} mountpoint The mountpoint of this context handler
@param {Object} options An options object to pass to the extending context (see
<a href="./application.html">ApplicationContext</a> and <a href="./static.html">StaticContext</a>)
@constructor | Context ( parentContainer , mountpoint , options ) | javascript | ringo/ringojs | modules/ringo/httpserver/context/context.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/httpserver/context/context.js | Apache-2.0 |
Context.prototype.getKey = function() {
const mountpoint = this.contextHandler.getContextPath();
const virtualHosts = this.contextHandler.getVirtualHosts();
if (virtualHosts !== null && virtualHosts.length > 0) {
return String(virtualHosts) + mountpoint;
}
return mountpoint;
}; | Returns the key of this context handler
@returns {String} The key | Context.prototype.getKey ( ) | javascript | ringo/ringojs | modules/ringo/httpserver/context/context.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/httpserver/context/context.js | Apache-2.0 |
Context.prototype.addServlet = function(path, servlet, initParams) {
log.debug("Adding servlet {} -> {}", path, "->", servlet);
const servletHolder = new ServletHolder(servlet);
if (initParams != null && initParams.constructor === Object) {
Object.keys(initParams).forEach(function(key) {
servletHolder.setInitParameter(key, initParams[key]);
});
}
this.contextHandler.addServlet(servletHolder, path);
return servletHolder;
}; | Adds a servlet at the give path to this context handler
@param {String} path The mountpoint
@param {jakarta.servlet.Servlet} servlet The servlet to add
@param {Object} initParams An object containing init parameters to pass to
<a href="https://www.eclipse.org/jetty/javadoc/current/org/eclipse/jetty/servlet/ServletContextHandler.html">org.eclipse.jetty.servlet.ServletContextHandler</a>
@returns {org.eclipse.jetty.servlet.ServletHolder} The servlet holder of this servlet | Context.prototype.addServlet ( path , servlet , initParams ) | javascript | ringo/ringojs | modules/ringo/httpserver/context/context.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/httpserver/context/context.js | Apache-2.0 |
Context.prototype.addFilter = function(path, filter, initParams) {
log.debug("Adding filter {} -> {}", path, "->", filter);
const filterHolder = new FilterHolder(filter);
filterHolder.setName(filter.getClass().getName());
if (initParams != null && initParams.constructor === Object) {
Object.keys(initParams).forEach(function(key) {
filterHolder.setInitParameter(key, initParams[key]);
});
}
this.contextHandler.addFilter(filterHolder, path,
EnumSet.of(DispatcherType.REQUEST, DispatcherType.ASYNC));
return filterHolder;
}; | Adds a servlet filter at the give path to this context handler
@param {String} path The path spec of this filter
@param {jakarta.servlet.Filter} filter The servlet filter to add
@param {Object} initParams An object containing init parameters to pass to
<a href="https://www.eclipse.org/jetty/javadoc/current/org/eclipse/jetty/servlet/FilterHolder.html">org.eclipse.jetty.servlet.FilterHolder</a>
@returns {org.eclipse.jetty.servlet.FilterHolder} The filter holder of this servlet filter | Context.prototype.addFilter ( path , filter , initParams ) | javascript | ringo/ringojs | modules/ringo/httpserver/context/context.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/httpserver/context/context.js | Apache-2.0 |
const ApplicationContext = module.exports = function ApplicationContext() {
Context.apply(this, arguments);
return this;
}; | Application context handler constructor
@param {org.eclipse.jetty.server.handler.ContextHandlerCollection} The parent container of this context handler
@param {String} The mountpoint of this context handler
@param {Object} An options object (see <a href="./builder.html#serveApplication">HttpServerBuilder.serveApplication</a>)
@constructor
@extends Context | ApplicationContext ( ) | javascript | ringo/ringojs | modules/ringo/httpserver/context/application.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/httpserver/context/application.js | Apache-2.0 |
ApplicationContext.prototype.serve = function(app, engine) {
log.info("Adding JSGI application {} -> {}",
this.contextHandler.getContextPath(), app);
engine = engine || require("ringo/engine").getRhinoEngine();
let servlet = null;
const params = {};
if (typeof(app) === "string") {
params["app-module"] = app;
servlet = new JsgiServlet(engine);
} else if (typeof(app) === "function") {
servlet = new JsgiServlet(engine, app);
} else {
throw new Error("Application must be either a function or the path " +
"to a module exporting a function");
}
return this.addServlet("/*", servlet, params);
}; | Serves the application passed as argument in this context
@param {String|Function} app The application to server. Can be defined either
as string specifying the application module to load, or as a function.
@param {org.ringojs.engine.RhinoEngine} engine Optional engine to pass to the JsgiServlet constructor
@returns {org.eclipse.jetty.servlet.ServletHolder} | ApplicationContext.prototype.serve ( app , engine ) | javascript | ringo/ringojs | modules/ringo/httpserver/context/application.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/httpserver/context/application.js | Apache-2.0 |
ApplicationContext.prototype.addWebSocket = function(path, onConnect, onCreate, initParams) {
log.info("Starting websocket support");
JettyWebSocketServletContainerInitializer.configure(this.contextHandler, null);
const webSocketCreator = new JettyWebSocketCreator({
"createWebSocket": function(request, response) {
if (typeof(onCreate) === "function" && onCreate(request, response) !== true) {
return null;
}
const socket = new WebSocket();
socket.addListener("connect", function(session) {
socket.session = session;
if (typeof onConnect === "function") {
onConnect(socket, session);
}
});
return socket.impl;
}
});
this.addServlet(path, new JettyWebSocketServlet({
"configure": function(factory) {
factory.setCreator(webSocketCreator);
}
}), initParams);
}; | @see <a href="../builder.html#addWebSocket">HttpServerBuilder.addWebSocket()</a>
@returns {org.eclipse.jetty.servlet.ServletHolder} | ApplicationContext.prototype.addWebSocket ( path , onConnect , onCreate , initParams ) | javascript | ringo/ringojs | modules/ringo/httpserver/context/application.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/httpserver/context/application.js | Apache-2.0 |
ApplicationContext.prototype.addEventSource = function(path, onConnect, initParams) {
log.info("Starting eventsource support");
this.addServlet(path, new EventSourceServlet({
"newEventSource": function(request) {
const socket = new EventSource();
if (typeof onConnect === "function") {
onConnect(socket, request);
}
return socket.impl;
}
}), initParams);
}; | @see <a href="../builder.html#addEventSource">HttpServerBuilder.addEventSource()</a>
@returns {org.eclipse.jetty.servlet.ServletHolder} | ApplicationContext.prototype.addEventSource ( path , onConnect , initParams ) | javascript | ringo/ringojs | modules/ringo/httpserver/context/application.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/httpserver/context/application.js | Apache-2.0 |
const StaticContext = module.exports = function StaticContext() {
Context.apply(this, arguments);
return this;
}; | Static files context handler constructor
@param {org.eclipse.jetty.server.handler.ContextHandlerCollection} The parent container of this context handler
@param {String} The mountpoint of this context handler
@param {Object} An options object (see <a href="./builder.html#serveApplication">HttpServerBuilder.serveApplication</a>)
@constructor
@extends Context | StaticContext ( ) | javascript | ringo/ringojs | modules/ringo/httpserver/context/static.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/httpserver/context/static.js | Apache-2.0 |
StaticContext.prototype.serve = function(directory, initParameters) {
log.debug("Adding static handler {} -> {}",
this.contextHandler.getContextPath(), directory);
const repo = getRepository(directory);
this.contextHandler.setResourceBase(repo.exists() ? repo.getPath() : directory);
return this.addServlet("/*", DefaultServlet, initParameters);
}; | Serve the files in the specified directory
@param {String} directory The path to the directory containing the static files
@param {Object} initParameters An object containing init parameters to pass
to the servlet holder (see <a href="../builder.html#serveStatic">HttpServerBuilder.serveStatic()</a>
@returns {org.eclipse.jetty.servlet.ServletHolder} | StaticContext.prototype.serve ( directory , initParameters ) | javascript | ringo/ringojs | modules/ringo/httpserver/context/static.js | https://github.com/ringo/ringojs/blob/master/modules/ringo/httpserver/context/static.js | Apache-2.0 |
exports.isInstalled = function(path) {
return fs.exists(fs.join.apply(null, Array.prototype.slice.call(arguments)));
}; | Returns true if a package is installed. This method accepts multiple
arguments, which are all joined to the package path used to check.
@param {String} path The path to the package
@returns True if the package is installed
@type Boolean | exports.isInstalled ( path ) | javascript | ringo/ringojs | tools/admin/utils/packages.js | https://github.com/ringo/ringojs/blob/master/tools/admin/utils/packages.js | Apache-2.0 |
const createApplication = (path, options) => {
log.debug("Creating application in {} (options: {}) ...", path, JSON.stringify(options));
const home = packages.getRingoHome();
const skeletons = fs.join(home, "tools/admin/skeletons");
const appSource = options.appSource || fs.join(skeletons, "app");
const appTemplate = options.googleAppEngine ? "appengine" :
options.javaWebApp ? "webapp" : null;
if (appTemplate) {
const symlink = Boolean(options.symlink);
copyTree(fs.join(skeletons, appTemplate), path);
// symlink app source if requested unless it's the skeleton app
if (!options.googleAppengine) {
copyTree(appSource, fs.join(path, "WEB-INF/app"), symlink && options.appSource);
}
copyTree(fs.join(home, "modules"), fs.join(path, "WEB-INF/modules"), symlink);
createAppEngineDirs(path);
copyJars(home, path, symlink);
} else if (copyTree(appSource, path)) {
if (!options.appSource) {
const descriptor = packages.getDescriptor(path);
term.writeln("Installing dependencies ...");
const packagesDirectory = fs.join(path, "packages");
if (!fs.exists(packagesDirectory)) {
fs.makeDirectory(packagesDirectory);
}
install.installDependencies(descriptor, packagesDirectory);
}
}
log.debug("Created application in", path);
term.writeln(term.GREEN, "Created application in", path, term.RESET);
}; | Create a new RingoJS web application at the given path.
@param {String} path The path where to create the application
@param {Object} options Options defining the application to create | createApplication | javascript | ringo/ringojs | tools/admin/commands/create.js | https://github.com/ringo/ringojs/blob/master/tools/admin/commands/create.js | Apache-2.0 |
const createPackage = (path) => {
log.debug("Creating package in", path);
const home = packages.getRingoHome();
const source = fs.join(home, "tools/admin/skeletons/package");
copyTree(source, path);
log.debug("Created package in", path);
term.writeln(term.GREEN, "Created RingoJS package in", path, term.RESET);
}; | Create a new RingoJS package at the given path.
@param {String} path The path where to create the package | createPackage | javascript | ringo/ringojs | tools/admin/commands/create.js | https://github.com/ringo/ringojs/blob/master/tools/admin/commands/create.js | Apache-2.0 |
exports.run = (args) => {
const options = parser.parse(args);
if (options.help) {
term.writeln(exports.help);
return;
} else if (!!options.googleAppengine + !!options.ringoPackage + !!options.javaWebapp > 1) {
term.writeln(term.RED, "Options are mutually exclusive.", term.RESET);
}
const type = options.googleAppEngine ? "Google App Engine app":
options.ringoPackage ? "Ringo package" :
options.javaWebApp ? "Java web application" :
"Ringo web application";
const path = fs.absolute(args[0] || shell.readln("Path for new " + type + ": "));
if (prepare(path, type)) {
term.writeln(term.GREEN, "Creating", type, "in", path, term.RESET);
if (options.ringoPackage) {
createPackage(path);
} else {
createApplication(path, options);
}
}
}; | Create a new RingoJS web application from the command line.
@param args | exports.run | javascript | ringo/ringojs | tools/admin/commands/create.js | https://github.com/ringo/ringojs/blob/master/tools/admin/commands/create.js | Apache-2.0 |
exports.testOk = function() {
assert.ok(true);
assert.ok("1");
assert.ok([]);
assert.ok({});
assert.ok(new Boolean(false));
assert.ok(Infinity);
assert.throws(getFunction(assert.ok, 0), assert.AssertionError);
assert.throws(getFunction(assert.ok, false), assert.AssertionError);
assert.throws(getFunction(assert.ok, null), assert.AssertionError);
assert.throws(getFunction(assert.ok, undefined), assert.AssertionError);
}; | *************************************************************
**** C O M M O N J S A S S E R T I O N T E S T S *****
************************************************************** | exports.testOk ( ) | javascript | ringo/ringojs | test/assert.js | https://github.com/ringo/ringojs/blob/master/test/assert.js | Apache-2.0 |
exports.testIsTrue = function() {
assert.isTrue(true);
assert.throws(getFunction(assert.isTrue, false), assert.AssertionError);
return;
}; | *********************************************************
**** C U S T O M A S S E R T I O N T E S T S *****
********************************************************** | exports.testIsTrue ( ) | javascript | ringo/ringojs | test/assert.js | https://github.com/ringo/ringojs/blob/master/test/assert.js | Apache-2.0 |
exports.testDumpObject = function() {
assert.strictEqual(
jsDump({
"a": 1,
"b": {
"c": 2
},
"e": 23
}),
[
'{',
' "a": 1,',
' "b": {',
' "c": 2',
' },',
' "e": 23',
'}'
].join("\n")
);
return;
}; | *************************************
**** J S D U M P T E S T S *****
************************************** | exports.testDumpObject ( ) | javascript | ringo/ringojs | test/assert.js | https://github.com/ringo/ringojs/blob/master/test/assert.js | Apache-2.0 |
function onmessage(e) {
if (e.data.test == 1) {
setTimeout(function(arg) {
e.source.postMessage(arg);
e.data.semaphore.signal();
}, 1, "value");
} else {
var id = setInterval(function(arg) {
e.source.postMessage(arg);
e.data.semaphore.signal();
}, 5, 10);
}
} | The worker module needed by scheduler_test | onmessage ( e ) | javascript | ringo/ringojs | test/ringo/scheduler_worker.js | https://github.com/ringo/ringojs/blob/master/test/ringo/scheduler_worker.js | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.