lang
stringclasses 2
values | license
stringclasses 13
values | stderr
stringlengths 0
343
| commit
stringlengths 40
40
| returncode
int64 0
128
| repos
stringlengths 6
87.7k
| new_contents
stringlengths 0
6.23M
| new_file
stringlengths 3
311
| old_contents
stringlengths 0
6.23M
| message
stringlengths 6
9.1k
| old_file
stringlengths 3
311
| subject
stringlengths 0
4k
| git_diff
stringlengths 0
6.31M
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
Java | mit | 06e714810f454b0be0b9154df0aff478c2670407 | 0 | CCI-MIT/XCoLab,CCI-MIT/XCoLab,CCI-MIT/XCoLab,CCI-MIT/XCoLab | package org.xcolab.view.pages.proposals.utils;
import org.xcolab.client.contest.pojo.AbstractContest;
import org.xcolab.client.contest.pojo.Contest;
import java.util.Comparator;
public enum ContestsColumn {
CONTEST_NAME (Comparator.comparing(o -> o.getTitleWithEndYear().toLowerCase())),
PROPOSALS_COUNT((o1, o2) -> (int) (o1.getProposalsCount() - o2.getProposalsCount())),
COMMENTS_COUNT((o1, o2) -> (int) (o1.getTotalCommentsCount() - o2.getTotalCommentsCount())),
VOTES_COUNT((o1, o2) -> (int) (o1.getVotesCount() - o2.getVotesCount())),
WHAT((o1, o2) -> {
String s1 = o1.getWhatName();
String s2 = o2.getWhatName();
return compareContestsByStringValues(o1, s1, o2, s2);
}),
WHERE((o1, o2) -> {
String s1 = o1.getWhereName();
String s2 = o2.getWhereName();
return compareContestsByStringValues(o1, s1, o2, s2);
}),
WHO((o1, o2) -> {
String s1 = o1.getWhoName();
String s2 = o2.getWhoName();
return compareContestsByStringValues(o1, s1, o2, s2);
}),
HOW((o1, o2) -> {
String s1 = o1.getHowName();
String s2 = o2.getHowName();
return compareContestsByStringValues(o1, s1, o2, s2);
}),
REFERENCE_DATE ((o1, o2) -> {
if(o2.getLastPhase() != null && o1.getLastPhase() != null) {
return o2.getLastPhase().getPhaseReferenceDate().compareTo(o1.getLastPhase().getPhaseReferenceDate());
}
if(o2.getLastPhase() == null){
return 1;
}
return 0;
}),
DEFAULT(Comparator.comparingInt(Contest::getWeight).reversed());
private final Comparator<Contest> columnComparator;
ContestsColumn(Comparator<Contest> columnComparator) {
this.columnComparator = columnComparator;
}
public Comparator<Contest> getColumnComparator() {
return columnComparator;
}
private static int compareContestsByStringValues(Contest c1, String s1, Contest c2, String s2) {
if (s1.isEmpty()) {
if (s2.isEmpty()) {
return (int) (c1.getId() - c2.getId());
}
return -1;
}
if (s2.isEmpty()) {
return 1;
}
return s1.toLowerCase().compareTo(s2.toLowerCase());
}
}
| view/src/main/java/org/xcolab/view/pages/proposals/utils/ContestsColumn.java | package org.xcolab.view.pages.proposals.utils;
import org.xcolab.client.contest.pojo.AbstractContest;
import org.xcolab.client.contest.pojo.Contest;
import java.util.Comparator;
public enum ContestsColumn {
CONTEST_NAME (Comparator.comparing(o -> o.getTitleWithEndYear().toLowerCase())),
PROPOSALS_COUNT((o1, o2) -> (int) (o1.getProposalsCount() - o2.getProposalsCount())),
COMMENTS_COUNT((o1, o2) -> (int) (o1.getTotalCommentsCount() - o2.getTotalCommentsCount())),
VOTES_COUNT((o1, o2) -> (int) (o1.getVotesCount() - o2.getVotesCount())),
WHAT((o1, o2) -> {
String s1 = o1.getWhatName();
String s2 = o2.getWhatName();
return compareContestsByStringValues(o1, s1, o2, s2);
}),
WHERE((o1, o2) -> {
String s1 = o1.getWhereName();
String s2 = o2.getWhereName();
return compareContestsByStringValues(o1, s1, o2, s2);
}),
WHO((o1, o2) -> {
String s1 = o1.getWhoName();
String s2 = o2.getWhoName();
return compareContestsByStringValues(o1, s1, o2, s2);
}),
HOW((o1, o2) -> {
String s1 = o1.getHowName();
String s2 = o2.getHowName();
return compareContestsByStringValues(o1, s1, o2, s2);
}),
REFERENCE_DATE ((o1, o2) -> {
if(o2.getLastPhase() != null && o1.getLastPhase() != null) {
return o2.getLastPhase().getPhaseReferenceDate().compareTo(o1.getLastPhase().getPhaseReferenceDate());
}
if(o2.getLastPhase() == null){
return 1;
}
return 0;
}),
DEFAULT(Comparator.comparingInt(AbstractContest::getWeight));
private final Comparator<Contest> columnComparator;
ContestsColumn(Comparator<Contest> columnComparator) {
this.columnComparator = columnComparator;
}
public Comparator<Contest> getColumnComparator() {
return columnComparator;
}
private static int compareContestsByStringValues(Contest c1, String s1, Contest c2, String s2) {
if (s1.isEmpty()) {
if (s2.isEmpty()) {
return (int) (c1.getId() - c2.getId());
}
return -1;
}
if (s2.isEmpty()) {
return 1;
}
return s1.toLowerCase().compareTo(s2.toLowerCase());
}
}
| [COLAB-2920]: reversed default sort order of contests by weight
| view/src/main/java/org/xcolab/view/pages/proposals/utils/ContestsColumn.java | [COLAB-2920]: reversed default sort order of contests by weight | <ide><path>iew/src/main/java/org/xcolab/view/pages/proposals/utils/ContestsColumn.java
<ide> return 0;
<ide> }),
<ide>
<del> DEFAULT(Comparator.comparingInt(AbstractContest::getWeight));
<add> DEFAULT(Comparator.comparingInt(Contest::getWeight).reversed());
<ide>
<ide> private final Comparator<Contest> columnComparator;
<ide> |
|
JavaScript | mit | 858fa61cac9a8c08b56c856e6d2f95f71ade97be | 0 | mcwonka/casperjs,jjyycchh/casperjs,linkedin/casperjs,casperjs/casperjs,vietch2612/casperjs,ravindrasingh22/casperjs,hexid/casperjs,jamesanthonyferguson/casperjs,pbrazdil/casperjs,sircelsiussexy/casperjs,muntasir2000/casperjs,ravindrasingh22/casperjs,vietch2612/casperjs,mickaelandrieu/casperjs,ravindrasingh22/casperjs,davidwhthomas/casperjs,davidwhthomas/casperjs,artillery/casperjs,ravindrasingh22/casperjs,JZL/casperjs,pbrazdil/casperjs,kyroskoh/casperjs,artillery/casperjs,sircelsiussexy/casperjs,mickaelandrieu/casperjs,mcwonka/casperjs,flyHe/casperjs,pbrazdil/casperjs,jefleponot/casperjs,JZL/casperjs,dj31416/casperjs,hexid/casperjs,jamesanthonyferguson/casperjs,alexbiehl/casperjs,hexid/casperjs,Andrey-Pavlov/casperjs,dj31416/casperjs,JZL/casperjs,kyroskoh/casperjs,HienLeThi/Casperjs_Demo,kyroskoh/casperjs,pbrazdil/casperjs,flyHe/casperjs,hexid/casperjs,kyroskoh/casperjs,jjyycchh/casperjs,jefleponot/casperjs,jamesanthonyferguson/casperjs,JZL/casperjs,dj31416/casperjs,soundyogi/casperjs,alexbiehl/casperjs,Andrey-Pavlov/casperjs,hlr1983/casperjs,hlr1983/casperjs,linkedin/casperjs,mickaelandrieu/casperjs,cryptoquick/casperjs,jjyycchh/casperjs,sircelsiussexy/casperjs,hudl/casperjs,pbrazdil/casperjs,soundyogi/casperjs,dj31416/casperjs,ravindrasingh22/casperjs,artillery/casperjs,joshuafcole/casperjs,soundyogi/casperjs,HienLeThi/Casperjs_Demo,jamesanthonyferguson/casperjs,RobertoMalatesta/casperjs,muntasir2000/casperjs,pbrazdil/casperjs,jefleponot/casperjs,joshuafcole/casperjs,vietch2612/casperjs,dj31416/casperjs,davidwhthomas/casperjs,istr/casperjs,n1k0/casperjs,vietch2612/casperjs,dj31416/casperjs,n1k0/casperjs,casperjs/casperjs,casperjs/casperjs,joshuafcole/casperjs,hlr1983/casperjs,PeterWangPo/casperjs,flyHe/casperjs,PeterWangPo/casperjs,cryptoquick/casperjs,singhdev/casperjs,alexbiehl/casperjs,linkedin/casperjs,hexid/casperjs,mickaelandrieu/casperjs,cryptoquick/casperjs,mickaelandrieu/casperjs,HienLeThi/Casperjs_Demo,flyHe/casperjs,soundyogi/casperjs,singhdev/casperjs,muntasir2000/casperjs,mcwonka/casperjs,RobertoMalatesta/casperjs,istr/casperjs,hlr1983/casperjs,muntasir2000/casperjs,casperjs/casperjs,cryptoquick/casperjs,JZL/casperjs,mcwonka/casperjs,PeterWangPo/casperjs,sircelsiussexy/casperjs,hudl/casperjs,artillery/casperjs,jamesanthonyferguson/casperjs,artillery/casperjs,RobertoMalatesta/casperjs,kyroskoh/casperjs,n1k0/casperjs,istr/casperjs,jjyycchh/casperjs,cryptoquick/casperjs,JZL/casperjs,mickaelandrieu/casperjs,artillery/casperjs,alexbiehl/casperjs,flyHe/casperjs,jjyycchh/casperjs,soundyogi/casperjs,hlr1983/casperjs,jefleponot/casperjs,hexid/casperjs,singhdev/casperjs,hlr1983/casperjs,HienLeThi/Casperjs_Demo,sircelsiussexy/casperjs,vietch2612/casperjs,Andrey-Pavlov/casperjs,singhdev/casperjs,HienLeThi/Casperjs_Demo,Andrey-Pavlov/casperjs,mcwonka/casperjs,Andrey-Pavlov/casperjs,ravindrasingh22/casperjs,muntasir2000/casperjs,RobertoMalatesta/casperjs,casperjs/casperjs,linkedin/casperjs,hudl/casperjs,n1k0/casperjs,linkedin/casperjs,mcwonka/casperjs,HienLeThi/Casperjs_Demo,muntasir2000/casperjs,vietch2612/casperjs,jamesanthonyferguson/casperjs,alexbiehl/casperjs,singhdev/casperjs,RobertoMalatesta/casperjs,jjyycchh/casperjs,Andrey-Pavlov/casperjs,kyroskoh/casperjs,istr/casperjs,davidwhthomas/casperjs,cryptoquick/casperjs,n1k0/casperjs,n1k0/casperjs,joshuafcole/casperjs,casperjs/casperjs,joshuafcole/casperjs,PeterWangPo/casperjs,RobertoMalatesta/casperjs,soundyogi/casperjs,sircelsiussexy/casperjs,PeterWangPo/casperjs,PeterWangPo/casperjs,istr/casperjs,istr/casperjs,jefleponot/casperjs,hudl/casperjs,linkedin/casperjs,davidwhthomas/casperjs,jefleponot/casperjs,alexbiehl/casperjs,davidwhthomas/casperjs,hudl/casperjs,joshuafcole/casperjs,flyHe/casperjs | /*!
* Casper is a navigation utility for PhantomJS.
*
* Documentation: http://casperjs.org/
* Repository: http://github.com/n1k0/casperjs
*
* Copyright (c) 2011-2012 Nicolas Perriault
*
* Part of source code is Copyright Joyent, Inc. and other Node contributors.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
/*global CasperError, exports, phantom, __utils__, patchRequire, require:true*/
var require = patchRequire(require);
var fs = require('fs');
var events = require('events');
var utils = require('utils');
var f = utils.format;
function AssertionError(msg, result) {
"use strict";
Error.call(this);
this.message = msg;
this.name = 'AssertionError';
this.result = result;
}
AssertionError.prototype = new Error();
exports.AssertionError = AssertionError;
function TerminationError(msg) {
"use strict";
Error.call(this);
this.message = msg;
this.name = 'TerminationError';
}
TerminationError.prototype = new Error();
exports.TerminationError = TerminationError;
function TimedOutError(msg) {
"use strict";
Error.call(this);
this.message = msg;
this.name = 'TimedOutError';
}
TimedOutError.prototype = new Error();
exports.TimedOutError = TimedOutError;
/**
* Creates a tester instance.
*
* @param Casper casper A Casper instance
* @param Object options Tester options
* @return Tester
*/
exports.create = function create(casper, options) {
"use strict";
return new Tester(casper, options);
};
/**
* Casper tester: makes assertions, stores test results and display then.
*
* @param Casper casper A valid Casper instance
* @param Object|null options Options object
*/
var Tester = function Tester(casper, options) {
"use strict";
/*jshint maxstatements:99*/
if (!utils.isCasperObject(casper)) {
throw new CasperError("Tester needs a Casper instance");
}
// self reference
var self = this;
// casper reference
this.casper = casper;
// public properties
this._setUp = undefined;
this._tearDown = undefined;
this.aborted = false;
this.executed = 0;
this.currentTestFile = null;
this.currentTestStartTime = new Date();
this.currentSuite = undefined;
this.currentSuiteNum = 0;
this.lastAssertTime = 0;
this.loadIncludes = {
includes: [],
pre: [],
post: []
};
this.options = utils.mergeObjects({
concise: false, // concise output?
failFast: false, // terminates a suite as soon as a test fails?
failText: "FAIL", // text to use for a failed test
passText: "PASS", // text to use for a succesful test
skipText: "SKIP", // text to use for a skipped test
pad: 80 , // maximum number of chars for a result line
warnText: "WARN" // text to use for a dubious test
}, options);
this.queue = [];
this.running = false;
this.started = false;
this.suiteResults = new TestSuiteResult();
this.on('success', function onSuccess(success) {
var timeElapsed = new Date() - this.currentTestStartTime;
this.currentSuite.addSuccess(success, timeElapsed - this.lastAssertTime);
this.lastAssertTime = timeElapsed;
});
this.on('skipped', function onSkipped(skipped) {
var timeElapsed = new Date() - this.currentTestStartTime;
this.currentSuite.addSkip(skipped, timeElapsed - this.lastAssertTime);
this.lastAssertTime = timeElapsed;
});
this.on('fail', function onFail(failure) {
// export
var valueKeys = Object.keys(failure.values),
timeElapsed = new Date() - this.currentTestStartTime;
this.currentSuite.addFailure(failure, timeElapsed - this.lastAssertTime);
this.lastAssertTime = timeElapsed;
// special printing
if (failure.type) {
this.comment(' type: ' + failure.type);
}
if (failure.file) {
this.comment(' file: ' + failure.file + (failure.line ? ':' + failure.line : ''));
}
if (failure.lineContents) {
this.comment(' code: ' + failure.lineContents);
}
if (!failure.values || valueKeys.length === 0) {
return;
}
valueKeys.forEach(function(name) {
this.comment(f(' %s: %s', name, utils.formatTestValue(failure.values[name], name)));
}.bind(this));
// check for fast failing
if (this.options.failFast) {
return this.terminate('--fail-fast: aborted all remaining tests');
}
});
function errorHandler(error, backtrace) {
self.casper.unwait();
if (error instanceof Error) {
self.processError(error);
return;
}
if (utils.isString(error) && /^(Assertion|Termination|TimedOut)Error/.test(error)) {
return;
}
var line = 0;
try {
line = (backtrace || []).filter(function(entry) {
return self.currentTestFile === entry.file;
})[0].line;
} catch (e) {}
self.uncaughtError(error, self.currentTestFile, line, backtrace);
}
function errorHandlerAndDone(error, backtrace) {
errorHandler(error, backtrace);
self.done();
}
// casper events
this.casper.on('error', function onCasperError(msg, backtrace) {
self.processPhantomError(msg, backtrace);
});
[
'wait.error',
'waitFor.timeout.error',
'event.error',
'complete.error'
].forEach(function(event) {
self.casper.on(event, errorHandlerAndDone);
});
self.casper.on('step.error', errorHandler);
this.casper.on('warn', function(warning) {
if (self.currentSuite) {
self.currentSuite.addWarning(warning);
}
});
// Do not hook casper if we're not testing
if (!phantom.casperTest) {
return;
}
// specific timeout callbacks
this.casper.options.onStepTimeout = function test_onStepTimeout(timeout, step) {
throw new TimedOutError(f("Step timeout occured at step %s (%dms)", step, timeout));
};
this.casper.options.onTimeout = function test_onTimeout(timeout) {
throw new TimedOutError(f("Timeout occured (%dms)", timeout));
};
this.casper.options.onWaitTimeout = function test_onWaitTimeout(timeout, details) {
/*jshint maxcomplexity:10*/
var message = f("Wait timeout occured (%dms)", timeout);
details = details || {};
if (details.selector) {
message = f(details.waitWhile ? '"%s" never went away in %dms' : '"%s" still did not exist in %dms', details.selector, timeout);
}
else if (details.visible) {
message = f(details.waitWhile ? '"%s" never disappeared in %dms' : '"%s" never appeared in %dms', details.visible, timeout);
}
else if (details.url || details.resource) {
message = f('%s did not load in %dms', details.url || details.resource, timeout);
}
else if (details.popup) {
message = f('%s did not pop up in %dms', details.popup, timeout);
}
else if (details.text) {
message = f('"%s" did not appear in the page in %dms', details.text, timeout);
}
else if (details.selectorTextChange) {
message = f('"%s" did not have a text change in %dms', details.selectorTextChange, timeout);
}
else if (utils.isFunction(details.testFx)) {
message = f('"%s" did not evaluate to something truthy in %dms', details.testFx.toString(), timeout);
}
errorHandlerAndDone(new TimedOutError(message));
};
};
// Tester class is an EventEmitter
utils.inherits(Tester, events.EventEmitter);
exports.Tester = Tester;
/**
* Aborts current test suite.
*
* @param String message Warning message (optional)
*/
Tester.prototype.abort = function abort(message) {
"use strict";
throw new TerminationError(message || 'test suite aborted');
};
/**
* Skip `nb` tests.
*
* @param Integer nb Number of tests to skip
* @param String message Message to display
* @return Object
*/
Tester.prototype.skip = function skip(nb, message) {
"use strict";
return this.processAssertionResult({
success: null,
standard: f("%d test%s skipped", nb, nb > 1 ? "s" : ""),
message: message,
type: "skip",
number: nb,
skipped: true
});
};
/**
* Asserts that a condition strictly resolves to true. Also returns an
* "assertion object" containing useful informations about the test case
* results.
*
* This method is also used as the base one used for all other `assert*`
* family methods; supplementary informations are then passed using the
* `context` argument.
*
* Note: an AssertionError is thrown if the assertion fails.
*
* @param Boolean subject The condition to test
* @param String message Test description
* @param Object|null context Assertion context object (Optional)
* @return Object An assertion result object if test passed
* @throws AssertionError in case the test failed
*/
Tester.prototype.assert =
Tester.prototype.assertTrue = function assert(subject, message, context) {
"use strict";
this.executed++;
var result = utils.mergeObjects({
success: subject === true,
type: "assert",
standard: "Subject is strictly true",
message: message,
file: this.currentTestFile,
doThrow: true,
values: {
subject: utils.getPropertyPath(context, 'values.subject') || subject
}
}, context || {});
if (!result.success && result.doThrow) {
throw new AssertionError(message || result.standard, result);
}
return this.processAssertionResult(result);
};
/**
* Asserts that two values are strictly equals.
*
* @param Mixed subject The value to test
* @param Mixed expected The expected value
* @param String message Test description (Optional)
* @return Object An assertion result object
*/
Tester.prototype.assertEquals =
Tester.prototype.assertEqual = function assertEquals(subject, expected, message) {
"use strict";
return this.assert(utils.equals(subject, expected), message, {
type: "assertEquals",
standard: "Subject equals the expected value",
values: {
subject: subject,
expected: expected
}
});
};
/**
* Asserts that two values are strictly not equals.
*
* @param Mixed subject The value to test
* @param Mixed expected The unwanted value
* @param String|null message Test description (Optional)
* @return Object An assertion result object
*/
Tester.prototype.assertNotEquals = function assertNotEquals(subject, shouldnt, message) {
"use strict";
return this.assert(!this.testEquals(subject, shouldnt), message, {
type: "assertNotEquals",
standard: "Subject doesn't equal what it shouldn't be",
values: {
subject: subject,
shouldnt: shouldnt
}
});
};
/**
* Asserts that a selector expression matches n elements.
*
* @param Mixed selector A selector expression
* @param Number count Expected number of matching elements
* @param String message Test description (Optional)
* @return Object An assertion result object
*/
Tester.prototype.assertElementCount = function assertElementCount(selector, count, message) {
"use strict";
if (!utils.isNumber(count) || count < 0) {
throw new CasperError('assertElementCount() needs a positive integer count');
}
var elementCount = this.casper.evaluate(function(selector) {
try {
return __utils__.findAll(selector).length;
} catch (e) {
return -1;
}
}, selector);
return this.assert(elementCount === count, message, {
type: "assertElementCount",
standard: f('%d element%s matching selector "%s" found',
count,
count > 1 ? 's' : '',
selector),
values: {
selector: selector,
expected: count,
obtained: elementCount
}
});
};
/**
* Asserts that a code evaluation in remote DOM resolves to true.
*
* @param Function fn A function to be evaluated in remote DOM
* @param String message Test description
* @param Object params Object/Array containing the parameters to inject into
* the function (optional)
* @return Object An assertion result object
*/
Tester.prototype.assertEval =
Tester.prototype.assertEvaluate = function assertEval(fn, message, params) {
"use strict";
return this.assert(this.casper.evaluate(fn, params), message, {
type: "assertEval",
standard: "Evaluated function returns true",
values: {
fn: fn,
params: params
}
});
};
/**
* Asserts that the result of a code evaluation in remote DOM equals
* an expected value.
*
* @param Function fn The function to be evaluated in remote DOM
* @param Boolean expected The expected value
* @param String|null message Test description
* @param Object|null params Object containing the parameters to inject into the
* function (optional)
* @return Object An assertion result object
*/
Tester.prototype.assertEvalEquals =
Tester.prototype.assertEvalEqual = function assertEvalEquals(fn, expected, message, params) {
"use strict";
var subject = this.casper.evaluate(fn, params);
return this.assert(utils.equals(subject, expected), message, {
type: "assertEvalEquals",
standard: "Evaluated function returns the expected value",
values: {
fn: fn,
params: params,
subject: subject,
expected: expected
}
});
};
/**
* Asserts that the provided assertion fails (used for internal testing).
*
* @param Function fn A closure calling an assertion
* @param String|null message Test description
* @return Object An assertion result object
*/
Tester.prototype.assertFail = function assertFail(fn, message) {
"use strict";
var failed = false;
try {
fn();
} catch (e) {
failed = true;
}
return this.assert(failed, message, {
type: "assertFail",
standard: "Assertion fails as expected"
});
};
/**
* Asserts that a given input field has the provided value.
*
* @param String inputName The name attribute of the input element
* @param String expected The expected value of the input element
* @param String message Test description
* @param Object options ClientUtils#getFieldValue options (optional)
* @return Object An assertion result object
*/
Tester.prototype.assertField = function assertField(inputName, expected, message, options) {
"use strict";
var actual = this.casper.evaluate(function(inputName, options) {
return __utils__.getFieldValue(inputName, options);
}, inputName, options);
return this.assert(utils.equals(actual, expected), message, {
type: 'assertField',
standard: f('"%s" input field has the value "%s"', inputName, expected),
values: {
inputName: inputName,
actual: actual,
expected: expected
}
});
};
/**
* Asserts that an element matching the provided selector expression exists in
* remote DOM.
*
* @param String selector Selector expression
* @param String message Test description
* @return Object An assertion result object
*/
Tester.prototype.assertExists =
Tester.prototype.assertExist =
Tester.prototype.assertSelectorExists =
Tester.prototype.assertSelectorExist = function assertExists(selector, message) {
"use strict";
return this.assert(this.casper.exists(selector), message, {
type: "assertExists",
standard: f("Find an element matching: %s", selector),
values: {
selector: selector
}
});
};
/**
* Asserts that an element matching the provided selector expression does not
* exist in remote DOM.
*
* @param String selector Selector expression
* @param String message Test description
* @return Object An assertion result object
*/
Tester.prototype.assertDoesntExist =
Tester.prototype.assertNotExists = function assertDoesntExist(selector, message) {
"use strict";
return this.assert(!this.casper.exists(selector), message, {
type: "assertDoesntExist",
standard: f("Fail to find element matching selector: %s", selector),
values: {
selector: selector
}
});
};
/**
* Asserts that current HTTP status is the one passed as argument.
*
* @param Number status HTTP status code
* @param String message Test description
* @return Object An assertion result object
*/
Tester.prototype.assertHttpStatus = function assertHttpStatus(status, message) {
"use strict";
var currentHTTPStatus = this.casper.currentHTTPStatus;
return this.assert(utils.equals(this.casper.currentHTTPStatus, status), message, {
type: "assertHttpStatus",
standard: f("HTTP status code is: %s", status),
values: {
current: currentHTTPStatus,
expected: status
}
});
};
/**
* Asserts that a provided string matches a provided RegExp pattern.
*
* @param String subject The string to test
* @param RegExp pattern A RegExp object instance
* @param String message Test description
* @return Object An assertion result object
*/
Tester.prototype.assertMatch =
Tester.prototype.assertMatches = function assertMatch(subject, pattern, message) {
"use strict";
if (utils.betterTypeOf(pattern) !== "regexp") {
throw new CasperError('Invalid regexp.');
}
return this.assert(pattern.test(subject), message, {
type: "assertMatch",
standard: "Subject matches the provided pattern",
values: {
subject: subject,
pattern: pattern.toString()
}
});
};
/**
* Asserts a condition resolves to false.
*
* @param Boolean condition The condition to test
* @param String message Test description
* @return Object An assertion result object
*/
Tester.prototype.assertNot =
Tester.prototype.assertFalse = function assertNot(condition, message) {
"use strict";
return this.assert(!condition, message, {
type: "assertNot",
standard: "Subject is falsy",
values: {
condition: condition
}
});
};
/**
* Asserts that a selector expression is not currently visible.
*
* @param String expected selector expression
* @param String message Test description
* @return Object An assertion result object
*/
Tester.prototype.assertNotVisible =
Tester.prototype.assertInvisible = function assertNotVisible(selector, message) {
"use strict";
return this.assert(!this.casper.visible(selector), message, {
type: "assertVisible",
standard: "Selector is not visible",
values: {
selector: selector
}
});
};
/**
* Asserts that the provided function called with the given parameters
* will raise an exception.
*
* @param Function fn The function to test
* @param Array args The arguments to pass to the function
* @param String message Test description
* @return Object An assertion result object
*/
Tester.prototype.assertRaises =
Tester.prototype.assertRaise =
Tester.prototype.assertThrows = function assertRaises(fn, args, message) {
"use strict";
var context = {
type: "assertRaises",
standard: "Function raises an error"
};
try {
fn.apply(null, args);
this.assert(false, message, context);
} catch (error) {
this.assert(true, message, utils.mergeObjects(context, {
values: {
error: error
}
}));
}
};
/**
* Asserts that the current page has a resource that matches the provided test
*
* @param Function/String test A test function that is called with every response
* @param String message Test description
* @return Object An assertion result object
*/
Tester.prototype.assertResourceExists =
Tester.prototype.assertResourceExist = function assertResourceExists(test, message) {
"use strict";
return this.assert(this.casper.resourceExists(test), message, {
type: "assertResourceExists",
standard: "Confirm page has resource",
values: {
test: test
}
});
};
/**
* Asserts that given text doesn't exist in the document body.
*
* @param String text Text not to be found
* @param String message Test description
* @return Object An assertion result object
*/
Tester.prototype.assertTextDoesntExist =
Tester.prototype.assertTextDoesntExist = function assertTextDoesntExist(text, message) {
"use strict";
var textFound = (this.casper.evaluate(function _evaluate() {
return document.body.textContent || document.body.innerText;
}).indexOf(text) === -1);
return this.assert(textFound, message, {
type: "assertTextDoesntExists",
standard: "Text doesn't exist within the document body",
values: {
text: text
}
});
};
/**
* Asserts that given text exists in the document body.
*
* @param String text Text to be found
* @param String message Test description
* @return Object An assertion result object
*/
Tester.prototype.assertTextExists =
Tester.prototype.assertTextExist = function assertTextExists(text, message) {
"use strict";
var textFound = (this.casper.evaluate(function _evaluate() {
return document.body.textContent || document.body.innerText;
}).indexOf(text) !== -1);
return this.assert(textFound, message, {
type: "assertTextExists",
standard: "Find text within the document body",
values: {
text: text
}
});
};
/**
* Asserts a subject is truthy.
*
* @param Mixed subject Test subject
* @param String message Test description
* @return Object An assertion result object
*/
Tester.prototype.assertTruthy = function assertTruthy(subject, message) {
"use strict";
/*jshint eqeqeq:false*/
return this.assert(utils.isTruthy(subject), message, {
type: "assertTruthy",
standard: "Subject is truthy",
values: {
subject: subject
}
});
};
/**
* Asserts a subject is falsy.
*
* @param Mixed subject Test subject
* @param String message Test description
* @return Object An assertion result object
*/
Tester.prototype.assertFalsy = function assertFalsy(subject, message) {
"use strict";
/*jshint eqeqeq:false*/
return this.assert(utils.isFalsy(subject), message, {
type: "assertFalsy",
standard: "Subject is falsy",
values: {
subject: subject
}
});
};
/**
* Asserts that given text exists in the provided selector.
*
* @param String selector Selector expression
* @param String text Text to be found
* @param String message Test description
* @return Object An assertion result object
*/
Tester.prototype.assertSelectorHasText =
Tester.prototype.assertSelectorContains = function assertSelectorHasText(selector, text, message) {
"use strict";
var got = this.casper.fetchText(selector);
var textFound = got.indexOf(text) !== -1;
return this.assert(textFound, message, {
type: "assertSelectorHasText",
standard: f('Find "%s" within the selector "%s"', text, selector),
values: {
selector: selector,
text: text,
actualContent: got
}
});
};
/**
* Asserts that given text does not exist in the provided selector.
*
* @param String selector Selector expression
* @param String text Text not to be found
* @param String message Test description
* @return Object An assertion result object
*/
Tester.prototype.assertSelectorDoesntHaveText =
Tester.prototype.assertSelectorDoesntContain = function assertSelectorDoesntHaveText(selector, text, message) {
"use strict";
var textFound = this.casper.fetchText(selector).indexOf(text) === -1;
return this.assert(textFound, message, {
type: "assertSelectorDoesntHaveText",
standard: f('Did not find "%s" within the selector "%s"', text, selector),
values: {
selector: selector,
text: text
}
});
};
/**
* Asserts that title of the remote page equals to the expected one.
*
* @param String expected The expected title string
* @param String message Test description
* @return Object An assertion result object
*/
Tester.prototype.assertTitle = function assertTitle(expected, message) {
"use strict";
var currentTitle = this.casper.getTitle();
return this.assert(utils.equals(currentTitle, expected), message, {
type: "assertTitle",
standard: f('Page title is: "%s"', expected),
values: {
subject: currentTitle,
expected: expected
}
});
};
/**
* Asserts that title of the remote page matched the provided pattern.
*
* @param RegExp pattern The pattern to test the title against
* @param String message Test description
* @return Object An assertion result object
*/
Tester.prototype.assertTitleMatch =
Tester.prototype.assertTitleMatches = function assertTitleMatch(pattern, message) {
"use strict";
if (utils.betterTypeOf(pattern) !== "regexp") {
throw new CasperError('Invalid regexp.');
}
var currentTitle = this.casper.getTitle();
return this.assert(pattern.test(currentTitle), message, {
type: "assertTitle",
details: "Page title does not match the provided pattern",
values: {
subject: currentTitle,
pattern: pattern.toString()
}
});
};
/**
* Asserts that the provided subject is of the given type.
*
* @param mixed subject The value to test
* @param String type The javascript type name
* @param String message Test description
* @return Object An assertion result object
*/
Tester.prototype.assertType = function assertType(subject, type, message) {
"use strict";
var actual = utils.betterTypeOf(subject);
return this.assert(utils.equals(actual, type), message, {
type: "assertType",
standard: f('Subject type is: "%s"', type),
values: {
subject: subject,
type: type,
actual: actual
}
});
};
/**
* Asserts that the provided subject has the provided constructor in its prototype hierarchy.
*
* @param mixed subject The value to test
* @param Function constructor The javascript type name
* @param String message Test description
* @return Object An assertion result object
*/
Tester.prototype.assertInstanceOf = function assertInstanceOf(subject, constructor, message) {
"use strict";
if (utils.betterTypeOf(constructor) !== "function") {
throw new CasperError('Subject is null or undefined.');
}
return this.assert(utils.betterInstanceOf(subject, constructor), message, {
type: "assertInstanceOf",
standard: f('Subject is instance of: "%s"', constructor.name),
values: {
subject: subject,
constructorName: constructor.name
}
});
};
/**
* Asserts that a the current page url matches a given pattern. A pattern may be
* either a RegExp object or a String. The method will test if the URL matches
* the pattern or contains the String.
*
* @param RegExp|String pattern The test pattern
* @param String message Test description
* @return Object An assertion result object
*/
Tester.prototype.assertUrlMatch =
Tester.prototype.assertUrlMatches = function assertUrlMatch(pattern, message) {
"use strict";
var currentUrl = this.casper.getCurrentUrl(),
patternType = utils.betterTypeOf(pattern),
result;
if (patternType === "regexp") {
result = pattern.test(currentUrl);
} else if (patternType === "string") {
result = currentUrl.indexOf(pattern) !== -1;
} else {
throw new CasperError("assertUrlMatch() only accepts strings or regexps");
}
return this.assert(result, message, {
type: "assertUrlMatch",
standard: "Current url matches the provided pattern",
values: {
currentUrl: currentUrl,
pattern: pattern.toString()
}
});
};
/**
* Asserts that a selector expression is currently visible.
*
* @param String expected selector expression
* @param String message Test description
* @return Object An assertion result object
*/
Tester.prototype.assertVisible = function assertVisible(selector, message) {
"use strict";
return this.assert(this.casper.visible(selector), message, {
type: "assertVisible",
standard: "Selector is visible",
values: {
selector: selector
}
});
};
/**
* Prints out a colored bar onto the console.
*
*/
Tester.prototype.bar = function bar(text, style) {
"use strict";
this.casper.echo(text, style, this.options.pad);
};
/**
* Defines a function which will be executed before every test.
*
* @param Function fn
*/
Tester.prototype.setUp = function setUp(fn) {
"use strict";
this._setUp = fn;
};
/**
* Defines a function which will be executed after every test.
*
* @param Function fn
*/
Tester.prototype.tearDown = function tearDown(fn) {
"use strict";
this._tearDown = fn;
};
/**
* Starts a suite.
*
* Can be invoked different ways:
*
* casper.test.begin("suite description", plannedTests, function(test){})
* casper.test.begin("suite description", function(test){})
*/
Tester.prototype.begin = function begin() {
"use strict";
if (this.started && this.running)
return this.queue.push(arguments);
function getConfig(args) {
var config = {
setUp: function(){},
tearDown: function(){}
};
if (utils.isFunction(args[1])) {
config.test = args[1];
} else if (utils.isObject(args[1])) {
config = utils.mergeObjects(config, args[1]);
} else if (utils.isNumber(args[1]) && utils.isFunction(args[2])) {
config.planned = ~~args[1] || undefined;
config.test = args[2];
} else if (utils.isNumber(args[1]) && utils.isObject(args[2])) {
config.config = utils.mergeObjects(config, args[2]);
config.planned = ~~args[1] || undefined;
} else {
throw new CasperError('Invalid call');
}
if (!utils.isFunction(config.test))
throw new CasperError('begin() is missing a mandatory test function');
return config;
}
var description = arguments[0] || f("Untitled suite in %s", this.currentTestFile),
config = getConfig([].slice.call(arguments)),
next = function() {
config.test(this, this.casper);
if (this.options.concise)
this.casper.echo([
this.colorize('PASS', 'INFO'),
this.formatMessage(description),
this.colorize(f('(%d test%s)',
config.planned,
config.planned > 1 ? 's' : ''), 'INFO')
].join(' '));
}.bind(this);
if (!this.options.concise)
this.comment(description);
this.currentSuite = new TestCaseResult({
name: description,
file: this.currentTestFile,
config: config,
planned: config.planned || undefined
});
this.executed = 0;
this.running = this.started = true;
try {
if (config.setUp)
config.setUp(this, this.casper);
if (!this._setUp)
return next();
if (this._setUp.length > 0)
return this._setUp.call(this, next); // async
this._setUp.call(this); // sync
next();
} catch (err) {
this.processError(err);
this.done();
}
};
/**
* Render a colorized output. Basically a proxy method for
* `Casper.Colorizer#colorize()`.
*
* @param String message
* @param String style The style name
* @return String
*/
Tester.prototype.colorize = function colorize(message, style) {
"use strict";
return this.casper.getColorizer().colorize(message, style);
};
/**
* Writes a comment-style formatted message to stdout.
*
* @param String message
*/
Tester.prototype.comment = function comment(message) {
"use strict";
this.casper.echo('# ' + message, 'COMMENT');
};
/**
* Declares the current test suite done.
*
*/
Tester.prototype.done = function done() {
"use strict";
/*jshint maxstatements:20, maxcomplexity:20*/
var planned, config = this.currentSuite && this.currentSuite.config || {};
if (arguments.length && utils.isNumber(arguments[0])) {
this.casper.warn('done() `planned` arg is deprecated as of 1.1');
planned = arguments[0];
}
if (config && config.tearDown && utils.isFunction(config.tearDown)) {
try {
config.tearDown(this, this.casper);
} catch (error) {
this.processError(error);
}
}
var next = function() {
if (this.currentSuite && this.currentSuite.planned &&
this.currentSuite.planned !== this.executed + this.currentSuite.skipped &&
!this.currentSuite.failed) {
this.dubious(this.currentSuite.planned, this.executed, this.currentSuite.name);
} else if (planned && planned !== this.executed) {
// BC
this.dubious(planned, this.executed);
}
if (this.currentSuite) {
this.suiteResults.push(this.currentSuite);
this.currentSuite = undefined;
this.executed = 0;
}
this.emit('test.done');
this.casper.currentHTTPResponse = {};
this.running = this.started = false;
var nextTest = this.queue.shift();
if (nextTest) {
this.begin.apply(this, nextTest);
}
}.bind(this);
if (!this._tearDown) {
return next();
}
try {
if (this._tearDown.length > 0) {
// async
this._tearDown.call(this, next);
} else {
// sync
this._tearDown.call(this);
next();
}
} catch (error) {
this.processError(error);
}
};
/**
* Marks a test as dubious, when the number of planned tests doesn't match the
* number of actually executed one.
*
* @param String message
*/
Tester.prototype.dubious = function dubious(planned, executed, suite) {
"use strict";
var message = f('%s: %d tests planned, %d tests executed', suite || 'global', planned, executed);
this.casper.warn(message);
if (!this.currentSuite) return;
this.currentSuite.addFailure({
type: "dubious",
file: this.currentTestFile,
standard: message
});
};
/**
* Writes an error-style formatted message to stdout.
*
* @param String message
*/
Tester.prototype.error = function error(message) {
"use strict";
this.casper.echo(message, 'ERROR');
};
/**
* Executes a file, wraping and evaluating its code in an isolated
* environment where only the current `casper` instance is passed.
*
* @param String file Absolute path to some js/coffee file
*/
Tester.prototype.exec = function exec(file) {
"use strict";
file = this.filter('exec.file', file) || file;
if (!fs.isFile(file) || !utils.isJsFile(file)) {
var e = new CasperError(f("Cannot exec %s: can only exec() files with .js or .coffee extensions",
file));
e.fileName = e.file = e.sourceURL = file;
throw e;
}
this.currentTestFile = file;
phantom.injectJs(file);
};
/**
* Adds a failed test entry to the stack.
*
* @param String message
* @param Object Failure context (optional)
*/
Tester.prototype.fail = function fail(message, context) {
"use strict";
context = context || {};
return this.assert(false, message, utils.mergeObjects({
type: "fail",
standard: "explicit call to fail()"
}, context));
};
/**
* Recursively finds all test files contained in a given directory.
*
* @param String dir Path to some directory to scan
*/
Tester.prototype.findTestFiles = function findTestFiles(dir) {
"use strict";
var self = this;
if (!fs.isDirectory(dir)) {
return [];
}
var entries = fs.list(dir).filter(function _filter(entry) {
return entry !== '.' && entry !== '..';
}).map(function _map(entry) {
return fs.absolute(fs.pathJoin(dir, entry));
});
entries.forEach(function _forEach(entry) {
if (fs.isDirectory(entry)) {
entries = entries.concat(self.findTestFiles(entry));
}
});
return entries.filter(function _filter(entry) {
return utils.isJsFile(fs.absolute(fs.pathJoin(dir, entry)));
}).sort();
};
/**
* Computes current suite identifier.
*
* @return String
*/
Tester.prototype.getCurrentSuiteId = function getCurrentSuiteId() {
"use strict";
return this.casper.test.currentSuiteNum + "-" + this.casper.step;
};
/**
* Formats a message to highlight some parts of it.
*
* @param String message
* @param String style
*/
Tester.prototype.formatMessage = function formatMessage(message, style) {
"use strict";
var parts = /^([a-z0-9_\.]+\(\))(.*)/i.exec(message);
if (!parts) {
return message;
}
return this.colorize(parts[1], 'PARAMETER') + this.colorize(parts[2], style);
};
/**
* Writes an info-style formatted message to stdout.
*
* @param String message
*/
Tester.prototype.info = function info(message) {
"use strict";
this.casper.echo(message, 'PARAMETER');
};
/**
* Adds a succesful test entry to the stack.
*
* @param String message
*/
Tester.prototype.pass = function pass(message) {
"use strict";
return this.assert(true, message, {
type: "pass",
standard: "explicit call to pass()"
});
};
function getStackEntry(error, testFile) {
"use strict";
if ("stackArray" in error) {
// PhantomJS has changed the API of the Error object :-/
// https://github.com/ariya/phantomjs/commit/c9cf14f221f58a3daf585c47313da6fced0276bc
return error.stackArray.filter(function(entry) {
return testFile === entry.sourceURL;
})[0];
}
if (! ('stack' in error))
return null;
var r = /^\s*(.*)@(.*):(\d+)\s*$/gm;
var m;
while ((m = r.exec(error.stack))) {
var sourceURL = m[2];
if (sourceURL.indexOf('->') !== -1) {
sourceURL = sourceURL.split('->')[1].trim();
}
if (sourceURL === testFile) {
return { sourceURL: sourceURL, line: m[3]}
}
}
return null;
}
/**
* Processes an assertion error.
*
* @param AssertionError error
*/
Tester.prototype.processAssertionError = function(error) {
"use strict";
var result = error && error.result || {},
testFile = this.currentTestFile,
stackEntry;
try {
stackEntry = getStackEntry(error, testFile);
} catch (e) {}
if (stackEntry) {
result.line = stackEntry.line;
try {
result.lineContents = fs.read(this.currentTestFile).split('\n')[result.line - 1].trim();
} catch (e) {}
}
return this.processAssertionResult(result);
};
/**
* Processes an assertion result by emitting the appropriate event and
* printing result onto the console.
*
* @param Object result An assertion result object
* @return Object The passed assertion result Object
*/
Tester.prototype.processAssertionResult = function processAssertionResult(result) {
"use strict";
if (!this.currentSuite) {
// this is for BC when begin() didn't exist
this.currentSuite = new TestCaseResult({
name: "Untitled suite in " + this.currentTestFile,
file: this.currentTestFile,
planned: undefined
});
}
var eventName = 'success',
message = result.message || result.standard,
style = 'INFO',
status = this.options.passText;
if (null === result.success) {
eventName = 'skipped';
style = 'SKIP';
status = this.options.skipText;
} else if (!result.success) {
eventName = 'fail';
style = 'RED_BAR';
status = this.options.failText;
}
if (!this.options.concise) {
this.casper.echo([this.colorize(status, style), this.formatMessage(message)].join(' '));
}
this.emit(eventName, result);
return result;
};
/**
* Processes an error.
*
* @param Error error
*/
Tester.prototype.processError = function processError(error) {
"use strict";
if (error instanceof AssertionError) {
return this.processAssertionError(error);
}
if (error instanceof TerminationError) {
return this.terminate(error.message);
}
return this.uncaughtError(error, this.currentTestFile, error.line);
};
/**
* Processes a PhantomJS error, which is an error message and a backtrace.
*
* @param String message
* @param Array backtrace
*/
Tester.prototype.processPhantomError = function processPhantomError(msg, backtrace) {
"use strict";
if (/^AssertionError/.test(msg)) {
this.casper.warn('looks like you did not use begin(), which is mandatory since 1.1');
}
var termination = /^TerminationError:?\s?(.*)/.exec(msg);
if (termination) {
var message = termination[1];
if (backtrace && backtrace[0]) {
message += ' at ' + backtrace[0].file + backtrace[0].line;
}
return this.terminate(message);
}
this.fail(msg, {
type: "error",
doThrow: false,
values: {
error: msg,
stack: backtrace
}
});
this.done();
};
/**
* Renders a detailed report for each failed test.
*
*/
Tester.prototype.renderFailureDetails = function renderFailureDetails() {
"use strict";
if (!this.suiteResults.isFailed()) {
return;
}
var failures = this.suiteResults.getAllFailures();
this.casper.echo(f("\nDetails for the %d failed test%s:\n",
failures.length, failures.length > 1 ? "s" : ""), "PARAMETER");
failures.forEach(function _forEach(failure) {
this.casper.echo(f('In %s%s', failure.file, ~~failure.line ? ':' + ~~failure.line : ''));
if (failure.suite) {
this.casper.echo(f(' %s', failure.suite), "PARAMETER");
}
this.casper.echo(f(' %s: %s', failure.type || "unknown",
failure.message || failure.standard || "(no message was entered)"), "COMMENT");
}.bind(this));
};
/**
* Render tests results, an optionally exit phantomjs.
*
* @param Boolean exit
*/
Tester.prototype.renderResults = function renderResults(exit, status, save) {
"use strict";
/*jshint maxstatements:20*/
save = save || this.options.save;
var exitStatus = 0,
failed = this.suiteResults.countFailed(),
total = this.suiteResults.countExecuted(),
statusText,
style,
result;
if (total === 0) {
exitStatus = 1;
statusText = this.options.warnText;
style = 'WARN_BAR';
result = f("%s Looks like you didn't run any test.", statusText);
} else {
if (this.suiteResults.isFailed()) {
exitStatus = 1;
statusText = this.options.failText;
style = 'RED_BAR';
} else {
statusText = this.options.passText;
style = 'GREEN_BAR';
}
result = f('%s %d test%s executed in %ss, %d passed, %d failed, %d dubious, %d skipped.',
statusText,
total,
total > 1 ? "s" : "",
utils.ms2seconds(this.suiteResults.calculateDuration()),
this.suiteResults.countPassed(),
failed,
this.suiteResults.countDubious(),
this.suiteResults.countSkipped());
}
this.casper.echo(result, style, this.options.pad);
this.renderFailureDetails();
if (save) {
this.saveResults(save);
}
if (exit === true) {
this.casper.exit(status ? ~~status : exitStatus);
}
};
/**
* Runs al suites contained in the paths passed as arguments.
*
*/
Tester.prototype.runSuites = function runSuites() {
"use strict";
var testFiles = [], self = this;
if (arguments.length === 0) {
throw new CasperError("runSuites() needs at least one path argument");
}
this.loadIncludes.includes.forEach(function _forEachInclude(include) {
phantom.injectJs(include);
});
this.loadIncludes.pre.forEach(function _forEachPreTest(preTestFile) {
testFiles = testFiles.concat(preTestFile);
});
Array.prototype.forEach.call(arguments, function _forEachArgument(path) {
if (!fs.exists(path)) {
self.bar(f("Path %s doesn't exist", path), "RED_BAR");
}
if (fs.isDirectory(path)) {
testFiles = testFiles.concat(self.findTestFiles(path));
} else if (fs.isFile(path)) {
testFiles.push(path);
}
});
this.loadIncludes.post.forEach(function _forEachPostTest(postTestFile) {
testFiles = testFiles.concat(postTestFile);
});
if (testFiles.length === 0) {
this.bar(f("No test file found in %s, terminating.",
Array.prototype.slice.call(arguments)), "RED_BAR");
this.casper.exit(1);
}
self.currentSuiteNum = 0;
self.currentTestStartTime = new Date();
self.lastAssertTime = 0;
var interval = setInterval(function _check(self) {
if (self.running) {
return;
}
if (self.currentSuiteNum === testFiles.length || self.aborted) {
self.emit('tests.complete');
clearInterval(interval);
self.aborted = false;
} else {
self.runTest(testFiles[self.currentSuiteNum]);
self.currentSuiteNum++;
}
}, 20, this);
};
/**
* Runs a test file
*
*/
Tester.prototype.runTest = function runTest(testFile) {
"use strict";
this.bar(f('Test file: %s', testFile), 'INFO_BAR');
this.running = true; // this.running is set back to false with done()
this.executed = 0;
this.exec(testFile);
};
/**
* Terminates current suite.
*
*/
Tester.prototype.terminate = function(message) {
"use strict";
if (message) {
this.casper.warn(message);
}
this.done();
this.aborted = true;
this.emit('tests.complete');
};
/**
* Saves results to file.
*
* @param String filename Target file path.
*/
Tester.prototype.saveResults = function saveResults(filepath) {
"use strict";
var exporter = require('xunit').create();
exporter.setResults(this.suiteResults);
try {
fs.write(filepath, exporter.getXML(), 'w');
this.casper.echo(f('Result log stored in %s', filepath), 'INFO', 80);
} catch (e) {
this.casper.echo(f('Unable to write results to %s: %s', filepath, e), 'ERROR', 80);
}
};
/**
* Tests equality between the two passed arguments.
*
* @param Mixed v1
* @param Mixed v2
* @param Boolean
*/
Tester.prototype.testEquals = Tester.prototype.testEqual = function testEquals(v1, v2) {
"use strict";
return utils.equals(v1, v2);
};
/**
* Processes an error caught while running tests contained in a given test
* file.
*
* @param Error|String error The error
* @param String file Test file where the error occurred
* @param Number line Line number (optional)
* @param Array backtrace Error stack trace (optional)
*/
Tester.prototype.uncaughtError = function uncaughtError(error, file, line, backtrace) {
"use strict";
// XXX: this is NOT an assertion scratch that
return this.processAssertionResult({
success: false,
type: "uncaughtError",
file: file,
line: ~~line,
message: utils.isObject(error) ? error.message : error,
values: {
error: error,
stack: backtrace
}
});
};
/**
* Test suites array.
*
*/
function TestSuiteResult() {}
TestSuiteResult.prototype = [];
exports.TestSuiteResult = TestSuiteResult;
/**
* Returns the number of tests.
*
* @return Number
*/
TestSuiteResult.prototype.countTotal = function countTotal() {
"use strict";
return this.countPassed() + this.countFailed() + this.countDubious();
};
/**
* Returns the number of dubious results.
*
* @return Number
*/
TestSuiteResult.prototype.countDubious = function countDubious() {
"use strict";
return this.map(function(result) {
return result.dubious;
}).reduce(function(a, b) {
return a + b;
}, 0);
};
/**
* Returns the number of executed tests.
*
* @return Number
*/
TestSuiteResult.prototype.countExecuted = function countTotal() {
"use strict";
return this.countTotal() - this.countDubious();
};
/**
* Returns the number of errors.
*
* @return Number
*/
TestSuiteResult.prototype.countErrors = function countErrors() {
"use strict";
return this.map(function(result) {
return result.crashed;
}).reduce(function(a, b) {
return a + b;
}, 0);
};
/**
* Returns the number of failed tests.
*
* @return Number
*/
TestSuiteResult.prototype.countFailed = function countFailed() {
"use strict";
return this.map(function(result) {
return result.failed - result.dubious;
}).reduce(function(a, b) {
return a + b;
}, 0);
};
/**
* Returns the number of succesful tests.
*
* @return Number
*/
TestSuiteResult.prototype.countPassed = function countPassed() {
"use strict";
return this.map(function(result) {
return result.passed;
}).reduce(function(a, b) {
return a + b;
}, 0);
};
/**
* Returns the number of skipped tests.
*
* @return Number
*/
TestSuiteResult.prototype.countSkipped = function countSkipped() {
"use strict";
return this.map(function(result) {
return result.skipped;
}).reduce(function(a, b) {
return a + b;
}, 0);
};
/**
* Returns the number of warnings.
*
* @return Number
*/
TestSuiteResult.prototype.countWarnings = function countWarnings() {
"use strict";
return this.map(function(result) {
return result.warned;
}).reduce(function(a, b) {
return a + b;
}, 0);
};
/**
* Checks if the suite has failed.
*
* @return Number
*/
TestSuiteResult.prototype.isFailed = function isFailed() {
"use strict";
return this.countErrors() + this.countFailed() + this.countDubious() > 0;
};
/**
* Checks if the suite has skipped tests.
*
* @return Number
*/
TestSuiteResult.prototype.isSkipped = function isSkipped() {
"use strict";
return this.countSkipped() > 0;
};
/**
* Returns all failures from this suite.
*
* @return Array
*/
TestSuiteResult.prototype.getAllFailures = function getAllFailures() {
"use strict";
var failures = [];
this.forEach(function(result) {
failures = failures.concat(result.failures);
});
return failures;
};
/**
* Returns all succesful tests from this suite.
*
* @return Array
*/
TestSuiteResult.prototype.getAllPasses = function getAllPasses() {
"use strict";
var passes = [];
this.forEach(function(result) {
passes = passes.concat(result.passes);
});
return passes;
};
/**
* Returns all skipped tests from this suite.
*
* @return Array
*/
TestSuiteResult.prototype.getAllSkips = function getAllSkips() {
"use strict";
var skipped = [];
this.forEach(function(result) {
skipped = skipped.concat(result.skipped);
});
return skipped;
};
/**
* Returns all results from this suite.
*
* @return Array
*/
TestSuiteResult.prototype.getAllResults = function getAllResults() {
"use strict";
return this.getAllPasses().concat(this.getAllFailures());
};
/**
* Computes the sum of all durations of the tests which were executed in the
* current suite.
*
* @return Number
*/
TestSuiteResult.prototype.calculateDuration = function calculateDuration() {
"use strict";
return this.getAllResults().map(function(result) {
return ~~result.time;
}).reduce(function add(a, b) {
return a + b;
}, 0);
};
/**
* Test suite results object.
*
* @param Object options
*/
function TestCaseResult(options) {
"use strict";
this.name = options && options.name;
this.file = options && options.file;
this.planned = ~~(options && options.planned) || undefined;
this.errors = [];
this.failures = [];
this.passes = [];
this.skips = [];
this.warnings = [];
this.config = options && options.config;
this.__defineGetter__("assertions", function() {
return this.passed + this.failed;
});
this.__defineGetter__("crashed", function() {
return this.errors.length;
});
this.__defineGetter__("failed", function() {
return this.failures.length;
});
this.__defineGetter__("dubious", function() {
return this.failures.filter(function(failure) {
return failure.type === "dubious";
}).length;
});
this.__defineGetter__("passed", function() {
return this.passes.length;
});
this.__defineGetter__("skipped", function() {
return this.skips.map(function(skip) {
return skip.number;
}).reduce(function(a, b) {
return a + b;
}, 0);
});
}
exports.TestCaseResult = TestCaseResult;
/**
* Adds a failure record and its execution time.
*
* @param Object failure
* @param Number time
*/
TestCaseResult.prototype.addFailure = function addFailure(failure, time) {
"use strict";
failure.suite = this.name;
failure.time = time;
this.failures.push(failure);
};
/**
* Adds an error record.
*
* @param Object failure
*/
TestCaseResult.prototype.addError = function addFailure(error) {
"use strict";
error.suite = this.name;
this.errors.push(error);
};
/**
* Adds a success record and its execution time.
*
* @param Object success
* @param Number time
*/
TestCaseResult.prototype.addSuccess = function addSuccess(success, time) {
"use strict";
success.suite = this.name;
success.time = time;
this.passes.push(success);
};
/**
* Adds a success record and its execution time.
*
* @param Object success
* @param Number time
*/
TestCaseResult.prototype.addSkip = function addSkip(skipped, time) {
"use strict";
skipped.suite = this.name;
skipped.time = time;
this.skips.push(skipped);
};
/**
* Adds a warning record.
*
* @param Object warning
*/
TestCaseResult.prototype.addWarning = function addWarning(warning) {
"use strict";
warning.suite = this.name;
this.warnings.push(warning);
};
/**
* Computes total duration for this suite.
*
* @return Number
*/
TestCaseResult.prototype.calculateDuration = function calculateDuration() {
"use strict";
function add(a, b) {
return a + b;
}
var passedTimes = this.passes.map(function(success) {
return ~~success.time;
}).reduce(add, 0);
var failedTimes = this.failures.map(function(failure) {
return ~~failure.time;
}).reduce(add, 0);
return passedTimes + failedTimes;
};
| modules/tester.js | /*!
* Casper is a navigation utility for PhantomJS.
*
* Documentation: http://casperjs.org/
* Repository: http://github.com/n1k0/casperjs
*
* Copyright (c) 2011-2012 Nicolas Perriault
*
* Part of source code is Copyright Joyent, Inc. and other Node contributors.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
/*global CasperError, exports, phantom, __utils__, patchRequire, require:true*/
var require = patchRequire(require);
var fs = require('fs');
var events = require('events');
var utils = require('utils');
var f = utils.format;
function AssertionError(msg, result) {
"use strict";
Error.call(this);
this.message = msg;
this.name = 'AssertionError';
this.result = result;
}
AssertionError.prototype = new Error();
exports.AssertionError = AssertionError;
function TerminationError(msg) {
"use strict";
Error.call(this);
this.message = msg;
this.name = 'TerminationError';
}
TerminationError.prototype = new Error();
exports.TerminationError = TerminationError;
function TimedOutError(msg) {
"use strict";
Error.call(this);
this.message = msg;
this.name = 'TimedOutError';
}
TimedOutError.prototype = new Error();
exports.TimedOutError = TimedOutError;
/**
* Creates a tester instance.
*
* @param Casper casper A Casper instance
* @param Object options Tester options
* @return Tester
*/
exports.create = function create(casper, options) {
"use strict";
return new Tester(casper, options);
};
/**
* Casper tester: makes assertions, stores test results and display then.
*
* @param Casper casper A valid Casper instance
* @param Object|null options Options object
*/
var Tester = function Tester(casper, options) {
"use strict";
/*jshint maxstatements:99*/
if (!utils.isCasperObject(casper)) {
throw new CasperError("Tester needs a Casper instance");
}
// self reference
var self = this;
// casper reference
this.casper = casper;
// public properties
this._setUp = undefined;
this._tearDown = undefined;
this.aborted = false;
this.executed = 0;
this.currentTestFile = null;
this.currentTestStartTime = new Date();
this.currentSuite = undefined;
this.currentSuiteNum = 0;
this.lastAssertTime = 0;
this.loadIncludes = {
includes: [],
pre: [],
post: []
};
this.options = utils.mergeObjects({
concise: false, // concise output?
failFast: false, // terminates a suite as soon as a test fails?
failText: "FAIL", // text to use for a failed test
passText: "PASS", // text to use for a succesful test
skipText: "SKIP", // text to use for a skipped test
pad: 80 , // maximum number of chars for a result line
warnText: "WARN" // text to use for a dubious test
}, options);
this.queue = [];
this.running = false;
this.started = false;
this.suiteResults = new TestSuiteResult();
this.on('success', function onSuccess(success) {
var timeElapsed = new Date() - this.currentTestStartTime;
this.currentSuite.addSuccess(success, timeElapsed - this.lastAssertTime);
this.lastAssertTime = timeElapsed;
});
this.on('skipped', function onSkipped(skipped) {
var timeElapsed = new Date() - this.currentTestStartTime;
this.currentSuite.addSkip(skipped, timeElapsed - this.lastAssertTime);
this.lastAssertTime = timeElapsed;
});
this.on('fail', function onFail(failure) {
// export
var valueKeys = Object.keys(failure.values),
timeElapsed = new Date() - this.currentTestStartTime;
this.currentSuite.addFailure(failure, timeElapsed - this.lastAssertTime);
this.lastAssertTime = timeElapsed;
// special printing
if (failure.type) {
this.comment(' type: ' + failure.type);
}
if (failure.file) {
this.comment(' file: ' + failure.file + (failure.line ? ':' + failure.line : ''));
}
if (failure.lineContents) {
this.comment(' code: ' + failure.lineContents);
}
if (!failure.values || valueKeys.length === 0) {
return;
}
valueKeys.forEach(function(name) {
this.comment(f(' %s: %s', name, utils.formatTestValue(failure.values[name], name)));
}.bind(this));
// check for fast failing
if (this.options.failFast) {
return this.terminate('--fail-fast: aborted all remaining tests');
}
});
function errorHandler(error, backtrace) {
self.casper.unwait();
if (error instanceof Error) {
self.processError(error);
return;
}
if (utils.isString(error) && /^(Assertion|Termination|TimedOut)Error/.test(error)) {
return;
}
var line = 0;
try {
line = (backtrace || []).filter(function(entry) {
return self.currentTestFile === entry.file;
})[0].line;
} catch (e) {}
self.uncaughtError(error, self.currentTestFile, line, backtrace);
}
function errorHandlerAndDone(error, backtrace) {
errorHandler(error, backtrace);
self.done();
}
// casper events
this.casper.on('error', function onCasperError(msg, backtrace) {
self.processPhantomError(msg, backtrace);
});
[
'wait.error',
'waitFor.timeout.error',
'event.error',
'complete.error'
].forEach(function(event) {
self.casper.on(event, errorHandlerAndDone);
});
self.casper.on('step.error', errorHandler);
this.casper.on('warn', function(warning) {
if (self.currentSuite) {
self.currentSuite.addWarning(warning);
}
});
// Do not hook casper if we're not testing
if (!phantom.casperTest) {
return;
}
// specific timeout callbacks
this.casper.options.onStepTimeout = function test_onStepTimeout(timeout, step) {
throw new TimedOutError(f("Step timeout occured at step %s (%dms)", step, timeout));
};
this.casper.options.onTimeout = function test_onTimeout(timeout) {
throw new TimedOutError(f("Timeout occured (%dms)", timeout));
};
this.casper.options.onWaitTimeout = function test_onWaitTimeout(timeout, details) {
/*jshint maxcomplexity:10*/
var message = f("Wait timeout occured (%dms)", timeout);
details = details || {};
if (details.selector) {
message = f(details.waitWhile ? '"%s" never went away in %dms' : '"%s" still did not exist in %dms', details.selector, timeout);
}
else if (details.visible) {
message = f(details.waitWhile ? '"%s" never disappeared in %dms' : '"%s" never appeared in %dms', details.visible, timeout);
}
else if (details.url || details.resource) {
message = f('%s did not load in %dms', details.url || details.resource, timeout);
}
else if (details.popup) {
message = f('%s did not pop up in %dms', details.popup, timeout);
}
else if (details.text) {
message = f('"%s" did not appear in the page in %dms', details.text, timeout);
}
else if (details.selectorTextChange) {
message = f('"%s" did not have a text change in %dms', details.selectorTextChange, timeout);
}
else if (utils.isFunction(details.testFx)) {
message = f('"%s" did not evaluate to something truthy in %dms', details.testFx.toString(), timeout);
}
errorHandlerAndDone(new TimedOutError(message));
};
};
// Tester class is an EventEmitter
utils.inherits(Tester, events.EventEmitter);
exports.Tester = Tester;
/**
* Aborts current test suite.
*
* @param String message Warning message (optional)
*/
Tester.prototype.abort = function abort(message) {
"use strict";
throw new TerminationError(message || 'test suite aborted');
};
/**
* Skip `nb` tests.
*
* @param Integer nb Number of tests to skip
* @param String message Message to display
* @return Object
*/
Tester.prototype.skip = function skip(nb, message) {
"use strict";
return this.processAssertionResult({
success: null,
standard: f("%d test%s skipped", nb, nb > 1 ? "s" : ""),
message: message,
type: "skip",
number: nb,
skipped: true
});
};
/**
* Asserts that a condition strictly resolves to true. Also returns an
* "assertion object" containing useful informations about the test case
* results.
*
* This method is also used as the base one used for all other `assert*`
* family methods; supplementary informations are then passed using the
* `context` argument.
*
* Note: an AssertionError is thrown if the assertion fails.
*
* @param Boolean subject The condition to test
* @param String message Test description
* @param Object|null context Assertion context object (Optional)
* @return Object An assertion result object if test passed
* @throws AssertionError in case the test failed
*/
Tester.prototype.assert =
Tester.prototype.assertTrue = function assert(subject, message, context) {
"use strict";
this.executed++;
var result = utils.mergeObjects({
success: subject === true,
type: "assert",
standard: "Subject is strictly true",
message: message,
file: this.currentTestFile,
doThrow: true,
values: {
subject: utils.getPropertyPath(context, 'values.subject') || subject
}
}, context || {});
if (!result.success && result.doThrow) {
throw new AssertionError(message || result.standard, result);
}
return this.processAssertionResult(result);
};
/**
* Asserts that two values are strictly equals.
*
* @param Mixed subject The value to test
* @param Mixed expected The expected value
* @param String message Test description (Optional)
* @return Object An assertion result object
*/
Tester.prototype.assertEquals =
Tester.prototype.assertEqual = function assertEquals(subject, expected, message) {
"use strict";
return this.assert(utils.equals(subject, expected), message, {
type: "assertEquals",
standard: "Subject equals the expected value",
values: {
subject: subject,
expected: expected
}
});
};
/**
* Asserts that two values are strictly not equals.
*
* @param Mixed subject The value to test
* @param Mixed expected The unwanted value
* @param String|null message Test description (Optional)
* @return Object An assertion result object
*/
Tester.prototype.assertNotEquals = function assertNotEquals(subject, shouldnt, message) {
"use strict";
return this.assert(!this.testEquals(subject, shouldnt), message, {
type: "assertNotEquals",
standard: "Subject doesn't equal what it shouldn't be",
values: {
subject: subject,
shouldnt: shouldnt
}
});
};
/**
* Asserts that a selector expression matches n elements.
*
* @param Mixed selector A selector expression
* @param Number count Expected number of matching elements
* @param String message Test description (Optional)
* @return Object An assertion result object
*/
Tester.prototype.assertElementCount = function assertElementCount(selector, count, message) {
"use strict";
if (!utils.isNumber(count) || count < 0) {
throw new CasperError('assertElementCount() needs a positive integer count');
}
var elementCount = this.casper.evaluate(function(selector) {
try {
return __utils__.findAll(selector).length;
} catch (e) {
return -1;
}
}, selector);
return this.assert(elementCount === count, message, {
type: "assertElementCount",
standard: f('%d element%s matching selector "%s" found',
count,
count > 1 ? 's' : '',
selector),
values: {
selector: selector,
expected: count,
obtained: elementCount
}
});
};
/**
* Asserts that a code evaluation in remote DOM resolves to true.
*
* @param Function fn A function to be evaluated in remote DOM
* @param String message Test description
* @param Object params Object/Array containing the parameters to inject into
* the function (optional)
* @return Object An assertion result object
*/
Tester.prototype.assertEval =
Tester.prototype.assertEvaluate = function assertEval(fn, message, params) {
"use strict";
return this.assert(this.casper.evaluate(fn, params), message, {
type: "assertEval",
standard: "Evaluated function returns true",
values: {
fn: fn,
params: params
}
});
};
/**
* Asserts that the result of a code evaluation in remote DOM equals
* an expected value.
*
* @param Function fn The function to be evaluated in remote DOM
* @param Boolean expected The expected value
* @param String|null message Test description
* @param Object|null params Object containing the parameters to inject into the
* function (optional)
* @return Object An assertion result object
*/
Tester.prototype.assertEvalEquals =
Tester.prototype.assertEvalEqual = function assertEvalEquals(fn, expected, message, params) {
"use strict";
var subject = this.casper.evaluate(fn, params);
return this.assert(utils.equals(subject, expected), message, {
type: "assertEvalEquals",
standard: "Evaluated function returns the expected value",
values: {
fn: fn,
params: params,
subject: subject,
expected: expected
}
});
};
/**
* Asserts that the provided assertion fails (used for internal testing).
*
* @param Function fn A closure calling an assertion
* @param String|null message Test description
* @return Object An assertion result object
*/
Tester.prototype.assertFail = function assertFail(fn, message) {
"use strict";
var failed = false;
try {
fn();
} catch (e) {
failed = true;
}
return this.assert(failed, message, {
type: "assertFail",
standard: "Assertion fails as expected"
});
};
/**
* Asserts that a given input field has the provided value.
*
* @param String inputName The name attribute of the input element
* @param String expected The expected value of the input element
* @param String message Test description
* @param Object options ClientUtils#getFieldValue options (optional)
* @return Object An assertion result object
*/
Tester.prototype.assertField = function assertField(inputName, expected, message, options) {
"use strict";
var actual = this.casper.evaluate(function(inputName, options) {
return __utils__.getFieldValue(inputName, options);
}, inputName, options);
return this.assert(utils.equals(actual, expected), message, {
type: 'assertField',
standard: f('"%s" input field has the value "%s"', inputName, expected),
values: {
inputName: inputName,
actual: actual,
expected: expected
}
});
};
/**
* Asserts that an element matching the provided selector expression exists in
* remote DOM.
*
* @param String selector Selector expression
* @param String message Test description
* @return Object An assertion result object
*/
Tester.prototype.assertExists =
Tester.prototype.assertExist =
Tester.prototype.assertSelectorExists =
Tester.prototype.assertSelectorExist = function assertExists(selector, message) {
"use strict";
return this.assert(this.casper.exists(selector), message, {
type: "assertExists",
standard: f("Found an element matching: %s", selector),
values: {
selector: selector
}
});
};
/**
* Asserts that an element matching the provided selector expression does not
* exist in remote DOM.
*
* @param String selector Selector expression
* @param String message Test description
* @return Object An assertion result object
*/
Tester.prototype.assertDoesntExist =
Tester.prototype.assertNotExists = function assertDoesntExist(selector, message) {
"use strict";
return this.assert(!this.casper.exists(selector), message, {
type: "assertDoesntExist",
standard: f("No element found matching selector: %s", selector),
values: {
selector: selector
}
});
};
/**
* Asserts that current HTTP status is the one passed as argument.
*
* @param Number status HTTP status code
* @param String message Test description
* @return Object An assertion result object
*/
Tester.prototype.assertHttpStatus = function assertHttpStatus(status, message) {
"use strict";
var currentHTTPStatus = this.casper.currentHTTPStatus;
return this.assert(utils.equals(this.casper.currentHTTPStatus, status), message, {
type: "assertHttpStatus",
standard: f("HTTP status code is: %s", status),
values: {
current: currentHTTPStatus,
expected: status
}
});
};
/**
* Asserts that a provided string matches a provided RegExp pattern.
*
* @param String subject The string to test
* @param RegExp pattern A RegExp object instance
* @param String message Test description
* @return Object An assertion result object
*/
Tester.prototype.assertMatch =
Tester.prototype.assertMatches = function assertMatch(subject, pattern, message) {
"use strict";
if (utils.betterTypeOf(pattern) !== "regexp") {
throw new CasperError('Invalid regexp.');
}
return this.assert(pattern.test(subject), message, {
type: "assertMatch",
standard: "Subject matches the provided pattern",
values: {
subject: subject,
pattern: pattern.toString()
}
});
};
/**
* Asserts a condition resolves to false.
*
* @param Boolean condition The condition to test
* @param String message Test description
* @return Object An assertion result object
*/
Tester.prototype.assertNot =
Tester.prototype.assertFalse = function assertNot(condition, message) {
"use strict";
return this.assert(!condition, message, {
type: "assertNot",
standard: "Subject is falsy",
values: {
condition: condition
}
});
};
/**
* Asserts that a selector expression is not currently visible.
*
* @param String expected selector expression
* @param String message Test description
* @return Object An assertion result object
*/
Tester.prototype.assertNotVisible =
Tester.prototype.assertInvisible = function assertNotVisible(selector, message) {
"use strict";
return this.assert(!this.casper.visible(selector), message, {
type: "assertVisible",
standard: "Selector is not visible",
values: {
selector: selector
}
});
};
/**
* Asserts that the provided function called with the given parameters
* will raise an exception.
*
* @param Function fn The function to test
* @param Array args The arguments to pass to the function
* @param String message Test description
* @return Object An assertion result object
*/
Tester.prototype.assertRaises =
Tester.prototype.assertRaise =
Tester.prototype.assertThrows = function assertRaises(fn, args, message) {
"use strict";
var context = {
type: "assertRaises",
standard: "Function raises an error"
};
try {
fn.apply(null, args);
this.assert(false, message, context);
} catch (error) {
this.assert(true, message, utils.mergeObjects(context, {
values: {
error: error
}
}));
}
};
/**
* Asserts that the current page has a resource that matches the provided test
*
* @param Function/String test A test function that is called with every response
* @param String message Test description
* @return Object An assertion result object
*/
Tester.prototype.assertResourceExists =
Tester.prototype.assertResourceExist = function assertResourceExists(test, message) {
"use strict";
return this.assert(this.casper.resourceExists(test), message, {
type: "assertResourceExists",
standard: "Expected resource has been found",
values: {
test: test
}
});
};
/**
* Asserts that given text doesn't exist in the document body.
*
* @param String text Text not to be found
* @param String message Test description
* @return Object An assertion result object
*/
Tester.prototype.assertTextDoesntExist =
Tester.prototype.assertTextDoesntExist = function assertTextDoesntExist(text, message) {
"use strict";
var textFound = (this.casper.evaluate(function _evaluate() {
return document.body.textContent || document.body.innerText;
}).indexOf(text) === -1);
return this.assert(textFound, message, {
type: "assertTextDoesntExists",
standard: "Text doesn't exist within the document body",
values: {
text: text
}
});
};
/**
* Asserts that given text exists in the document body.
*
* @param String text Text to be found
* @param String message Test description
* @return Object An assertion result object
*/
Tester.prototype.assertTextExists =
Tester.prototype.assertTextExist = function assertTextExists(text, message) {
"use strict";
var textFound = (this.casper.evaluate(function _evaluate() {
return document.body.textContent || document.body.innerText;
}).indexOf(text) !== -1);
return this.assert(textFound, message, {
type: "assertTextExists",
standard: "Found expected text within the document body",
values: {
text: text
}
});
};
/**
* Asserts a subject is truthy.
*
* @param Mixed subject Test subject
* @param String message Test description
* @return Object An assertion result object
*/
Tester.prototype.assertTruthy = function assertTruthy(subject, message) {
"use strict";
/*jshint eqeqeq:false*/
return this.assert(utils.isTruthy(subject), message, {
type: "assertTruthy",
standard: "Subject is truthy",
values: {
subject: subject
}
});
};
/**
* Asserts a subject is falsy.
*
* @param Mixed subject Test subject
* @param String message Test description
* @return Object An assertion result object
*/
Tester.prototype.assertFalsy = function assertFalsy(subject, message) {
"use strict";
/*jshint eqeqeq:false*/
return this.assert(utils.isFalsy(subject), message, {
type: "assertFalsy",
standard: "Subject is falsy",
values: {
subject: subject
}
});
};
/**
* Asserts that given text exists in the provided selector.
*
* @param String selector Selector expression
* @param String text Text to be found
* @param String message Test description
* @return Object An assertion result object
*/
Tester.prototype.assertSelectorHasText =
Tester.prototype.assertSelectorContains = function assertSelectorHasText(selector, text, message) {
"use strict";
var got = this.casper.fetchText(selector);
var textFound = got.indexOf(text) !== -1;
return this.assert(textFound, message, {
type: "assertSelectorHasText",
standard: f('Found "%s" within the selector "%s"', text, selector),
values: {
selector: selector,
text: text,
actualContent: got
}
});
};
/**
* Asserts that given text does not exist in the provided selector.
*
* @param String selector Selector expression
* @param String text Text not to be found
* @param String message Test description
* @return Object An assertion result object
*/
Tester.prototype.assertSelectorDoesntHaveText =
Tester.prototype.assertSelectorDoesntContain = function assertSelectorDoesntHaveText(selector, text, message) {
"use strict";
var textFound = this.casper.fetchText(selector).indexOf(text) === -1;
return this.assert(textFound, message, {
type: "assertSelectorDoesntHaveText",
standard: f('Did not find "%s" within the selector "%s"', text, selector),
values: {
selector: selector,
text: text
}
});
};
/**
* Asserts that title of the remote page equals to the expected one.
*
* @param String expected The expected title string
* @param String message Test description
* @return Object An assertion result object
*/
Tester.prototype.assertTitle = function assertTitle(expected, message) {
"use strict";
var currentTitle = this.casper.getTitle();
return this.assert(utils.equals(currentTitle, expected), message, {
type: "assertTitle",
standard: f('Page title is: "%s"', expected),
values: {
subject: currentTitle,
expected: expected
}
});
};
/**
* Asserts that title of the remote page matched the provided pattern.
*
* @param RegExp pattern The pattern to test the title against
* @param String message Test description
* @return Object An assertion result object
*/
Tester.prototype.assertTitleMatch =
Tester.prototype.assertTitleMatches = function assertTitleMatch(pattern, message) {
"use strict";
if (utils.betterTypeOf(pattern) !== "regexp") {
throw new CasperError('Invalid regexp.');
}
var currentTitle = this.casper.getTitle();
return this.assert(pattern.test(currentTitle), message, {
type: "assertTitle",
details: "Page title does not match the provided pattern",
values: {
subject: currentTitle,
pattern: pattern.toString()
}
});
};
/**
* Asserts that the provided subject is of the given type.
*
* @param mixed subject The value to test
* @param String type The javascript type name
* @param String message Test description
* @return Object An assertion result object
*/
Tester.prototype.assertType = function assertType(subject, type, message) {
"use strict";
var actual = utils.betterTypeOf(subject);
return this.assert(utils.equals(actual, type), message, {
type: "assertType",
standard: f('Subject type is: "%s"', type),
values: {
subject: subject,
type: type,
actual: actual
}
});
};
/**
* Asserts that the provided subject has the provided constructor in its prototype hierarchy.
*
* @param mixed subject The value to test
* @param Function constructor The javascript type name
* @param String message Test description
* @return Object An assertion result object
*/
Tester.prototype.assertInstanceOf = function assertInstanceOf(subject, constructor, message) {
"use strict";
if (utils.betterTypeOf(constructor) !== "function") {
throw new CasperError('Subject is null or undefined.');
}
return this.assert(utils.betterInstanceOf(subject, constructor), message, {
type: "assertInstanceOf",
standard: f('Subject is instance of: "%s"', constructor.name),
values: {
subject: subject,
constructorName: constructor.name
}
});
};
/**
* Asserts that a the current page url matches a given pattern. A pattern may be
* either a RegExp object or a String. The method will test if the URL matches
* the pattern or contains the String.
*
* @param RegExp|String pattern The test pattern
* @param String message Test description
* @return Object An assertion result object
*/
Tester.prototype.assertUrlMatch =
Tester.prototype.assertUrlMatches = function assertUrlMatch(pattern, message) {
"use strict";
var currentUrl = this.casper.getCurrentUrl(),
patternType = utils.betterTypeOf(pattern),
result;
if (patternType === "regexp") {
result = pattern.test(currentUrl);
} else if (patternType === "string") {
result = currentUrl.indexOf(pattern) !== -1;
} else {
throw new CasperError("assertUrlMatch() only accepts strings or regexps");
}
return this.assert(result, message, {
type: "assertUrlMatch",
standard: "Current url matches the provided pattern",
values: {
currentUrl: currentUrl,
pattern: pattern.toString()
}
});
};
/**
* Asserts that a selector expression is currently visible.
*
* @param String expected selector expression
* @param String message Test description
* @return Object An assertion result object
*/
Tester.prototype.assertVisible = function assertVisible(selector, message) {
"use strict";
return this.assert(this.casper.visible(selector), message, {
type: "assertVisible",
standard: "Selector is visible",
values: {
selector: selector
}
});
};
/**
* Prints out a colored bar onto the console.
*
*/
Tester.prototype.bar = function bar(text, style) {
"use strict";
this.casper.echo(text, style, this.options.pad);
};
/**
* Defines a function which will be executed before every test.
*
* @param Function fn
*/
Tester.prototype.setUp = function setUp(fn) {
"use strict";
this._setUp = fn;
};
/**
* Defines a function which will be executed after every test.
*
* @param Function fn
*/
Tester.prototype.tearDown = function tearDown(fn) {
"use strict";
this._tearDown = fn;
};
/**
* Starts a suite.
*
* Can be invoked different ways:
*
* casper.test.begin("suite description", plannedTests, function(test){})
* casper.test.begin("suite description", function(test){})
*/
Tester.prototype.begin = function begin() {
"use strict";
if (this.started && this.running)
return this.queue.push(arguments);
function getConfig(args) {
var config = {
setUp: function(){},
tearDown: function(){}
};
if (utils.isFunction(args[1])) {
config.test = args[1];
} else if (utils.isObject(args[1])) {
config = utils.mergeObjects(config, args[1]);
} else if (utils.isNumber(args[1]) && utils.isFunction(args[2])) {
config.planned = ~~args[1] || undefined;
config.test = args[2];
} else if (utils.isNumber(args[1]) && utils.isObject(args[2])) {
config.config = utils.mergeObjects(config, args[2]);
config.planned = ~~args[1] || undefined;
} else {
throw new CasperError('Invalid call');
}
if (!utils.isFunction(config.test))
throw new CasperError('begin() is missing a mandatory test function');
return config;
}
var description = arguments[0] || f("Untitled suite in %s", this.currentTestFile),
config = getConfig([].slice.call(arguments)),
next = function() {
config.test(this, this.casper);
if (this.options.concise)
this.casper.echo([
this.colorize('PASS', 'INFO'),
this.formatMessage(description),
this.colorize(f('(%d test%s)',
config.planned,
config.planned > 1 ? 's' : ''), 'INFO')
].join(' '));
}.bind(this);
if (!this.options.concise)
this.comment(description);
this.currentSuite = new TestCaseResult({
name: description,
file: this.currentTestFile,
config: config,
planned: config.planned || undefined
});
this.executed = 0;
this.running = this.started = true;
try {
if (config.setUp)
config.setUp(this, this.casper);
if (!this._setUp)
return next();
if (this._setUp.length > 0)
return this._setUp.call(this, next); // async
this._setUp.call(this); // sync
next();
} catch (err) {
this.processError(err);
this.done();
}
};
/**
* Render a colorized output. Basically a proxy method for
* `Casper.Colorizer#colorize()`.
*
* @param String message
* @param String style The style name
* @return String
*/
Tester.prototype.colorize = function colorize(message, style) {
"use strict";
return this.casper.getColorizer().colorize(message, style);
};
/**
* Writes a comment-style formatted message to stdout.
*
* @param String message
*/
Tester.prototype.comment = function comment(message) {
"use strict";
this.casper.echo('# ' + message, 'COMMENT');
};
/**
* Declares the current test suite done.
*
*/
Tester.prototype.done = function done() {
"use strict";
/*jshint maxstatements:20, maxcomplexity:20*/
var planned, config = this.currentSuite && this.currentSuite.config || {};
if (arguments.length && utils.isNumber(arguments[0])) {
this.casper.warn('done() `planned` arg is deprecated as of 1.1');
planned = arguments[0];
}
if (config && config.tearDown && utils.isFunction(config.tearDown)) {
try {
config.tearDown(this, this.casper);
} catch (error) {
this.processError(error);
}
}
var next = function() {
if (this.currentSuite && this.currentSuite.planned &&
this.currentSuite.planned !== this.executed + this.currentSuite.skipped &&
!this.currentSuite.failed) {
this.dubious(this.currentSuite.planned, this.executed, this.currentSuite.name);
} else if (planned && planned !== this.executed) {
// BC
this.dubious(planned, this.executed);
}
if (this.currentSuite) {
this.suiteResults.push(this.currentSuite);
this.currentSuite = undefined;
this.executed = 0;
}
this.emit('test.done');
this.casper.currentHTTPResponse = {};
this.running = this.started = false;
var nextTest = this.queue.shift();
if (nextTest) {
this.begin.apply(this, nextTest);
}
}.bind(this);
if (!this._tearDown) {
return next();
}
try {
if (this._tearDown.length > 0) {
// async
this._tearDown.call(this, next);
} else {
// sync
this._tearDown.call(this);
next();
}
} catch (error) {
this.processError(error);
}
};
/**
* Marks a test as dubious, when the number of planned tests doesn't match the
* number of actually executed one.
*
* @param String message
*/
Tester.prototype.dubious = function dubious(planned, executed, suite) {
"use strict";
var message = f('%s: %d tests planned, %d tests executed', suite || 'global', planned, executed);
this.casper.warn(message);
if (!this.currentSuite) return;
this.currentSuite.addFailure({
type: "dubious",
file: this.currentTestFile,
standard: message
});
};
/**
* Writes an error-style formatted message to stdout.
*
* @param String message
*/
Tester.prototype.error = function error(message) {
"use strict";
this.casper.echo(message, 'ERROR');
};
/**
* Executes a file, wraping and evaluating its code in an isolated
* environment where only the current `casper` instance is passed.
*
* @param String file Absolute path to some js/coffee file
*/
Tester.prototype.exec = function exec(file) {
"use strict";
file = this.filter('exec.file', file) || file;
if (!fs.isFile(file) || !utils.isJsFile(file)) {
var e = new CasperError(f("Cannot exec %s: can only exec() files with .js or .coffee extensions",
file));
e.fileName = e.file = e.sourceURL = file;
throw e;
}
this.currentTestFile = file;
phantom.injectJs(file);
};
/**
* Adds a failed test entry to the stack.
*
* @param String message
* @param Object Failure context (optional)
*/
Tester.prototype.fail = function fail(message, context) {
"use strict";
context = context || {};
return this.assert(false, message, utils.mergeObjects({
type: "fail",
standard: "explicit call to fail()"
}, context));
};
/**
* Recursively finds all test files contained in a given directory.
*
* @param String dir Path to some directory to scan
*/
Tester.prototype.findTestFiles = function findTestFiles(dir) {
"use strict";
var self = this;
if (!fs.isDirectory(dir)) {
return [];
}
var entries = fs.list(dir).filter(function _filter(entry) {
return entry !== '.' && entry !== '..';
}).map(function _map(entry) {
return fs.absolute(fs.pathJoin(dir, entry));
});
entries.forEach(function _forEach(entry) {
if (fs.isDirectory(entry)) {
entries = entries.concat(self.findTestFiles(entry));
}
});
return entries.filter(function _filter(entry) {
return utils.isJsFile(fs.absolute(fs.pathJoin(dir, entry)));
}).sort();
};
/**
* Computes current suite identifier.
*
* @return String
*/
Tester.prototype.getCurrentSuiteId = function getCurrentSuiteId() {
"use strict";
return this.casper.test.currentSuiteNum + "-" + this.casper.step;
};
/**
* Formats a message to highlight some parts of it.
*
* @param String message
* @param String style
*/
Tester.prototype.formatMessage = function formatMessage(message, style) {
"use strict";
var parts = /^([a-z0-9_\.]+\(\))(.*)/i.exec(message);
if (!parts) {
return message;
}
return this.colorize(parts[1], 'PARAMETER') + this.colorize(parts[2], style);
};
/**
* Writes an info-style formatted message to stdout.
*
* @param String message
*/
Tester.prototype.info = function info(message) {
"use strict";
this.casper.echo(message, 'PARAMETER');
};
/**
* Adds a succesful test entry to the stack.
*
* @param String message
*/
Tester.prototype.pass = function pass(message) {
"use strict";
return this.assert(true, message, {
type: "pass",
standard: "explicit call to pass()"
});
};
function getStackEntry(error, testFile) {
"use strict";
if ("stackArray" in error) {
// PhantomJS has changed the API of the Error object :-/
// https://github.com/ariya/phantomjs/commit/c9cf14f221f58a3daf585c47313da6fced0276bc
return error.stackArray.filter(function(entry) {
return testFile === entry.sourceURL;
})[0];
}
if (! ('stack' in error))
return null;
var r = /^\s*(.*)@(.*):(\d+)\s*$/gm;
var m;
while ((m = r.exec(error.stack))) {
var sourceURL = m[2];
if (sourceURL.indexOf('->') !== -1) {
sourceURL = sourceURL.split('->')[1].trim();
}
if (sourceURL === testFile) {
return { sourceURL: sourceURL, line: m[3]}
}
}
return null;
}
/**
* Processes an assertion error.
*
* @param AssertionError error
*/
Tester.prototype.processAssertionError = function(error) {
"use strict";
var result = error && error.result || {},
testFile = this.currentTestFile,
stackEntry;
try {
stackEntry = getStackEntry(error, testFile);
} catch (e) {}
if (stackEntry) {
result.line = stackEntry.line;
try {
result.lineContents = fs.read(this.currentTestFile).split('\n')[result.line - 1].trim();
} catch (e) {}
}
return this.processAssertionResult(result);
};
/**
* Processes an assertion result by emitting the appropriate event and
* printing result onto the console.
*
* @param Object result An assertion result object
* @return Object The passed assertion result Object
*/
Tester.prototype.processAssertionResult = function processAssertionResult(result) {
"use strict";
if (!this.currentSuite) {
// this is for BC when begin() didn't exist
this.currentSuite = new TestCaseResult({
name: "Untitled suite in " + this.currentTestFile,
file: this.currentTestFile,
planned: undefined
});
}
var eventName = 'success',
message = result.message || result.standard,
style = 'INFO',
status = this.options.passText;
if (null === result.success) {
eventName = 'skipped';
style = 'SKIP';
status = this.options.skipText;
} else if (!result.success) {
eventName = 'fail';
style = 'RED_BAR';
status = this.options.failText;
}
if (!this.options.concise) {
this.casper.echo([this.colorize(status, style), this.formatMessage(message)].join(' '));
}
this.emit(eventName, result);
return result;
};
/**
* Processes an error.
*
* @param Error error
*/
Tester.prototype.processError = function processError(error) {
"use strict";
if (error instanceof AssertionError) {
return this.processAssertionError(error);
}
if (error instanceof TerminationError) {
return this.terminate(error.message);
}
return this.uncaughtError(error, this.currentTestFile, error.line);
};
/**
* Processes a PhantomJS error, which is an error message and a backtrace.
*
* @param String message
* @param Array backtrace
*/
Tester.prototype.processPhantomError = function processPhantomError(msg, backtrace) {
"use strict";
if (/^AssertionError/.test(msg)) {
this.casper.warn('looks like you did not use begin(), which is mandatory since 1.1');
}
var termination = /^TerminationError:?\s?(.*)/.exec(msg);
if (termination) {
var message = termination[1];
if (backtrace && backtrace[0]) {
message += ' at ' + backtrace[0].file + backtrace[0].line;
}
return this.terminate(message);
}
this.fail(msg, {
type: "error",
doThrow: false,
values: {
error: msg,
stack: backtrace
}
});
this.done();
};
/**
* Renders a detailed report for each failed test.
*
*/
Tester.prototype.renderFailureDetails = function renderFailureDetails() {
"use strict";
if (!this.suiteResults.isFailed()) {
return;
}
var failures = this.suiteResults.getAllFailures();
this.casper.echo(f("\nDetails for the %d failed test%s:\n",
failures.length, failures.length > 1 ? "s" : ""), "PARAMETER");
failures.forEach(function _forEach(failure) {
this.casper.echo(f('In %s%s', failure.file, ~~failure.line ? ':' + ~~failure.line : ''));
if (failure.suite) {
this.casper.echo(f(' %s', failure.suite), "PARAMETER");
}
this.casper.echo(f(' %s: %s', failure.type || "unknown",
failure.message || failure.standard || "(no message was entered)"), "COMMENT");
}.bind(this));
};
/**
* Render tests results, an optionally exit phantomjs.
*
* @param Boolean exit
*/
Tester.prototype.renderResults = function renderResults(exit, status, save) {
"use strict";
/*jshint maxstatements:20*/
save = save || this.options.save;
var exitStatus = 0,
failed = this.suiteResults.countFailed(),
total = this.suiteResults.countExecuted(),
statusText,
style,
result;
if (total === 0) {
exitStatus = 1;
statusText = this.options.warnText;
style = 'WARN_BAR';
result = f("%s Looks like you didn't run any test.", statusText);
} else {
if (this.suiteResults.isFailed()) {
exitStatus = 1;
statusText = this.options.failText;
style = 'RED_BAR';
} else {
statusText = this.options.passText;
style = 'GREEN_BAR';
}
result = f('%s %d test%s executed in %ss, %d passed, %d failed, %d dubious, %d skipped.',
statusText,
total,
total > 1 ? "s" : "",
utils.ms2seconds(this.suiteResults.calculateDuration()),
this.suiteResults.countPassed(),
failed,
this.suiteResults.countDubious(),
this.suiteResults.countSkipped());
}
this.casper.echo(result, style, this.options.pad);
this.renderFailureDetails();
if (save) {
this.saveResults(save);
}
if (exit === true) {
this.casper.exit(status ? ~~status : exitStatus);
}
};
/**
* Runs al suites contained in the paths passed as arguments.
*
*/
Tester.prototype.runSuites = function runSuites() {
"use strict";
var testFiles = [], self = this;
if (arguments.length === 0) {
throw new CasperError("runSuites() needs at least one path argument");
}
this.loadIncludes.includes.forEach(function _forEachInclude(include) {
phantom.injectJs(include);
});
this.loadIncludes.pre.forEach(function _forEachPreTest(preTestFile) {
testFiles = testFiles.concat(preTestFile);
});
Array.prototype.forEach.call(arguments, function _forEachArgument(path) {
if (!fs.exists(path)) {
self.bar(f("Path %s doesn't exist", path), "RED_BAR");
}
if (fs.isDirectory(path)) {
testFiles = testFiles.concat(self.findTestFiles(path));
} else if (fs.isFile(path)) {
testFiles.push(path);
}
});
this.loadIncludes.post.forEach(function _forEachPostTest(postTestFile) {
testFiles = testFiles.concat(postTestFile);
});
if (testFiles.length === 0) {
this.bar(f("No test file found in %s, terminating.",
Array.prototype.slice.call(arguments)), "RED_BAR");
this.casper.exit(1);
}
self.currentSuiteNum = 0;
self.currentTestStartTime = new Date();
self.lastAssertTime = 0;
var interval = setInterval(function _check(self) {
if (self.running) {
return;
}
if (self.currentSuiteNum === testFiles.length || self.aborted) {
self.emit('tests.complete');
clearInterval(interval);
self.aborted = false;
} else {
self.runTest(testFiles[self.currentSuiteNum]);
self.currentSuiteNum++;
}
}, 20, this);
};
/**
* Runs a test file
*
*/
Tester.prototype.runTest = function runTest(testFile) {
"use strict";
this.bar(f('Test file: %s', testFile), 'INFO_BAR');
this.running = true; // this.running is set back to false with done()
this.executed = 0;
this.exec(testFile);
};
/**
* Terminates current suite.
*
*/
Tester.prototype.terminate = function(message) {
"use strict";
if (message) {
this.casper.warn(message);
}
this.done();
this.aborted = true;
this.emit('tests.complete');
};
/**
* Saves results to file.
*
* @param String filename Target file path.
*/
Tester.prototype.saveResults = function saveResults(filepath) {
"use strict";
var exporter = require('xunit').create();
exporter.setResults(this.suiteResults);
try {
fs.write(filepath, exporter.getXML(), 'w');
this.casper.echo(f('Result log stored in %s', filepath), 'INFO', 80);
} catch (e) {
this.casper.echo(f('Unable to write results to %s: %s', filepath, e), 'ERROR', 80);
}
};
/**
* Tests equality between the two passed arguments.
*
* @param Mixed v1
* @param Mixed v2
* @param Boolean
*/
Tester.prototype.testEquals = Tester.prototype.testEqual = function testEquals(v1, v2) {
"use strict";
return utils.equals(v1, v2);
};
/**
* Processes an error caught while running tests contained in a given test
* file.
*
* @param Error|String error The error
* @param String file Test file where the error occurred
* @param Number line Line number (optional)
* @param Array backtrace Error stack trace (optional)
*/
Tester.prototype.uncaughtError = function uncaughtError(error, file, line, backtrace) {
"use strict";
// XXX: this is NOT an assertion scratch that
return this.processAssertionResult({
success: false,
type: "uncaughtError",
file: file,
line: ~~line,
message: utils.isObject(error) ? error.message : error,
values: {
error: error,
stack: backtrace
}
});
};
/**
* Test suites array.
*
*/
function TestSuiteResult() {}
TestSuiteResult.prototype = [];
exports.TestSuiteResult = TestSuiteResult;
/**
* Returns the number of tests.
*
* @return Number
*/
TestSuiteResult.prototype.countTotal = function countTotal() {
"use strict";
return this.countPassed() + this.countFailed() + this.countDubious();
};
/**
* Returns the number of dubious results.
*
* @return Number
*/
TestSuiteResult.prototype.countDubious = function countDubious() {
"use strict";
return this.map(function(result) {
return result.dubious;
}).reduce(function(a, b) {
return a + b;
}, 0);
};
/**
* Returns the number of executed tests.
*
* @return Number
*/
TestSuiteResult.prototype.countExecuted = function countTotal() {
"use strict";
return this.countTotal() - this.countDubious();
};
/**
* Returns the number of errors.
*
* @return Number
*/
TestSuiteResult.prototype.countErrors = function countErrors() {
"use strict";
return this.map(function(result) {
return result.crashed;
}).reduce(function(a, b) {
return a + b;
}, 0);
};
/**
* Returns the number of failed tests.
*
* @return Number
*/
TestSuiteResult.prototype.countFailed = function countFailed() {
"use strict";
return this.map(function(result) {
return result.failed - result.dubious;
}).reduce(function(a, b) {
return a + b;
}, 0);
};
/**
* Returns the number of succesful tests.
*
* @return Number
*/
TestSuiteResult.prototype.countPassed = function countPassed() {
"use strict";
return this.map(function(result) {
return result.passed;
}).reduce(function(a, b) {
return a + b;
}, 0);
};
/**
* Returns the number of skipped tests.
*
* @return Number
*/
TestSuiteResult.prototype.countSkipped = function countSkipped() {
"use strict";
return this.map(function(result) {
return result.skipped;
}).reduce(function(a, b) {
return a + b;
}, 0);
};
/**
* Returns the number of warnings.
*
* @return Number
*/
TestSuiteResult.prototype.countWarnings = function countWarnings() {
"use strict";
return this.map(function(result) {
return result.warned;
}).reduce(function(a, b) {
return a + b;
}, 0);
};
/**
* Checks if the suite has failed.
*
* @return Number
*/
TestSuiteResult.prototype.isFailed = function isFailed() {
"use strict";
return this.countErrors() + this.countFailed() + this.countDubious() > 0;
};
/**
* Checks if the suite has skipped tests.
*
* @return Number
*/
TestSuiteResult.prototype.isSkipped = function isSkipped() {
"use strict";
return this.countSkipped() > 0;
};
/**
* Returns all failures from this suite.
*
* @return Array
*/
TestSuiteResult.prototype.getAllFailures = function getAllFailures() {
"use strict";
var failures = [];
this.forEach(function(result) {
failures = failures.concat(result.failures);
});
return failures;
};
/**
* Returns all succesful tests from this suite.
*
* @return Array
*/
TestSuiteResult.prototype.getAllPasses = function getAllPasses() {
"use strict";
var passes = [];
this.forEach(function(result) {
passes = passes.concat(result.passes);
});
return passes;
};
/**
* Returns all skipped tests from this suite.
*
* @return Array
*/
TestSuiteResult.prototype.getAllSkips = function getAllSkips() {
"use strict";
var skipped = [];
this.forEach(function(result) {
skipped = skipped.concat(result.skipped);
});
return skipped;
};
/**
* Returns all results from this suite.
*
* @return Array
*/
TestSuiteResult.prototype.getAllResults = function getAllResults() {
"use strict";
return this.getAllPasses().concat(this.getAllFailures());
};
/**
* Computes the sum of all durations of the tests which were executed in the
* current suite.
*
* @return Number
*/
TestSuiteResult.prototype.calculateDuration = function calculateDuration() {
"use strict";
return this.getAllResults().map(function(result) {
return ~~result.time;
}).reduce(function add(a, b) {
return a + b;
}, 0);
};
/**
* Test suite results object.
*
* @param Object options
*/
function TestCaseResult(options) {
"use strict";
this.name = options && options.name;
this.file = options && options.file;
this.planned = ~~(options && options.planned) || undefined;
this.errors = [];
this.failures = [];
this.passes = [];
this.skips = [];
this.warnings = [];
this.config = options && options.config;
this.__defineGetter__("assertions", function() {
return this.passed + this.failed;
});
this.__defineGetter__("crashed", function() {
return this.errors.length;
});
this.__defineGetter__("failed", function() {
return this.failures.length;
});
this.__defineGetter__("dubious", function() {
return this.failures.filter(function(failure) {
return failure.type === "dubious";
}).length;
});
this.__defineGetter__("passed", function() {
return this.passes.length;
});
this.__defineGetter__("skipped", function() {
return this.skips.map(function(skip) {
return skip.number;
}).reduce(function(a, b) {
return a + b;
}, 0);
});
}
exports.TestCaseResult = TestCaseResult;
/**
* Adds a failure record and its execution time.
*
* @param Object failure
* @param Number time
*/
TestCaseResult.prototype.addFailure = function addFailure(failure, time) {
"use strict";
failure.suite = this.name;
failure.time = time;
this.failures.push(failure);
};
/**
* Adds an error record.
*
* @param Object failure
*/
TestCaseResult.prototype.addError = function addFailure(error) {
"use strict";
error.suite = this.name;
this.errors.push(error);
};
/**
* Adds a success record and its execution time.
*
* @param Object success
* @param Number time
*/
TestCaseResult.prototype.addSuccess = function addSuccess(success, time) {
"use strict";
success.suite = this.name;
success.time = time;
this.passes.push(success);
};
/**
* Adds a success record and its execution time.
*
* @param Object success
* @param Number time
*/
TestCaseResult.prototype.addSkip = function addSkip(skipped, time) {
"use strict";
skipped.suite = this.name;
skipped.time = time;
this.skips.push(skipped);
};
/**
* Adds a warning record.
*
* @param Object warning
*/
TestCaseResult.prototype.addWarning = function addWarning(warning) {
"use strict";
warning.suite = this.name;
this.warnings.push(warning);
};
/**
* Computes total duration for this suite.
*
* @return Number
*/
TestCaseResult.prototype.calculateDuration = function calculateDuration() {
"use strict";
function add(a, b) {
return a + b;
}
var passedTimes = this.passes.map(function(success) {
return ~~success.time;
}).reduce(add, 0);
var failedTimes = this.failures.map(function(failure) {
return ~~failure.time;
}).reduce(add, 0);
return passedTimes + failedTimes;
};
| standardized tense of test failure/pass messages
| modules/tester.js | standardized tense of test failure/pass messages | <ide><path>odules/tester.js
<ide> "use strict";
<ide> return this.assert(this.casper.exists(selector), message, {
<ide> type: "assertExists",
<del> standard: f("Found an element matching: %s", selector),
<add> standard: f("Find an element matching: %s", selector),
<ide> values: {
<ide> selector: selector
<ide> }
<ide> "use strict";
<ide> return this.assert(!this.casper.exists(selector), message, {
<ide> type: "assertDoesntExist",
<del> standard: f("No element found matching selector: %s", selector),
<add> standard: f("Fail to find element matching selector: %s", selector),
<ide> values: {
<ide> selector: selector
<ide> }
<ide> "use strict";
<ide> return this.assert(this.casper.resourceExists(test), message, {
<ide> type: "assertResourceExists",
<del> standard: "Expected resource has been found",
<add> standard: "Confirm page has resource",
<ide> values: {
<ide> test: test
<ide> }
<ide> }).indexOf(text) !== -1);
<ide> return this.assert(textFound, message, {
<ide> type: "assertTextExists",
<del> standard: "Found expected text within the document body",
<add> standard: "Find text within the document body",
<ide> values: {
<ide> text: text
<ide> }
<ide> var textFound = got.indexOf(text) !== -1;
<ide> return this.assert(textFound, message, {
<ide> type: "assertSelectorHasText",
<del> standard: f('Found "%s" within the selector "%s"', text, selector),
<add> standard: f('Find "%s" within the selector "%s"', text, selector),
<ide> values: {
<ide> selector: selector,
<ide> text: text, |
|
Java | apache-2.0 | 8e8be4bb5bb9754c99c32ffc2e5d90f59aa9de70 | 0 | tharikaGitHub/carbon-apimgt,ruks/carbon-apimgt,tharikaGitHub/carbon-apimgt,uvindra/carbon-apimgt,uvindra/carbon-apimgt,bhathiya/carbon-apimgt,bhathiya/carbon-apimgt,chamindias/carbon-apimgt,Rajith90/carbon-apimgt,wso2/carbon-apimgt,sanjeewa-malalgoda/carbon-apimgt,sanjeewa-malalgoda/carbon-apimgt,isharac/carbon-apimgt,bhathiya/carbon-apimgt,tharindu1st/carbon-apimgt,chamindias/carbon-apimgt,jaadds/carbon-apimgt,tharikaGitHub/carbon-apimgt,uvindra/carbon-apimgt,Rajith90/carbon-apimgt,chamindias/carbon-apimgt,malinthaprasan/carbon-apimgt,jaadds/carbon-apimgt,wso2/carbon-apimgt,wso2/carbon-apimgt,Rajith90/carbon-apimgt,isharac/carbon-apimgt,isharac/carbon-apimgt,sanjeewa-malalgoda/carbon-apimgt,fazlan-nazeem/carbon-apimgt,prasa7/carbon-apimgt,fazlan-nazeem/carbon-apimgt,ruks/carbon-apimgt,isharac/carbon-apimgt,chamindias/carbon-apimgt,ruks/carbon-apimgt,praminda/carbon-apimgt,fazlan-nazeem/carbon-apimgt,tharikaGitHub/carbon-apimgt,fazlan-nazeem/carbon-apimgt,uvindra/carbon-apimgt,tharindu1st/carbon-apimgt,prasa7/carbon-apimgt,tharindu1st/carbon-apimgt,ruks/carbon-apimgt,malinthaprasan/carbon-apimgt,praminda/carbon-apimgt,jaadds/carbon-apimgt,Rajith90/carbon-apimgt,praminda/carbon-apimgt,jaadds/carbon-apimgt,prasa7/carbon-apimgt,chamilaadhi/carbon-apimgt,chamilaadhi/carbon-apimgt,chamilaadhi/carbon-apimgt,wso2/carbon-apimgt,sanjeewa-malalgoda/carbon-apimgt,chamilaadhi/carbon-apimgt,bhathiya/carbon-apimgt,prasa7/carbon-apimgt,malinthaprasan/carbon-apimgt,malinthaprasan/carbon-apimgt,tharindu1st/carbon-apimgt | /*
* Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.wso2.carbon.apimgt.rest.api.admin.v1.utils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.wso2.carbon.apimgt.api.APIAdmin;
import org.wso2.carbon.apimgt.api.APIManagementException;
import org.wso2.carbon.apimgt.api.ExceptionCodes;
import org.wso2.carbon.apimgt.api.model.BlockConditionsDTO;
import org.wso2.carbon.apimgt.api.model.policy.Policy;
import org.wso2.carbon.apimgt.impl.APIAdminImpl;
import org.wso2.carbon.apimgt.impl.APIConstants;
import org.wso2.carbon.apimgt.impl.utils.APIUtil;
import org.wso2.carbon.apimgt.rest.api.admin.v1.dto.CustomRuleDTO;
import org.wso2.carbon.apimgt.rest.api.admin.v1.dto.ThrottleConditionDTO;
import org.wso2.carbon.apimgt.rest.api.admin.v1.dto.ThrottleLimitDTO;
import org.wso2.carbon.apimgt.rest.api.util.RestApiConstants;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class RestApiAdminUtils {
//using a set for file extensions white list since it will be faster to search
private static final Set<String> EXTENSION_WHITELIST = new HashSet<String>(Arrays.asList(
"css", "jpg", "png", "gif", "svg", "ttf", "html", "js", "json", "ico"));
/**
* Checks whether given policy is allowed to access to user
*
* @param user username with tenant domain
* @param policy policy to check
* @return true if user is allowed to access the policy
*/
public static boolean isPolicyAccessibleToUser(String user, Policy policy) {
//This block checks whether policy's tenant domain and user's tenant domain are same
String userTenantDomain = MultitenantUtils.getTenantDomain(user);
if (!StringUtils.isBlank(policy.getTenantDomain())) {
return policy.getTenantDomain().equals(userTenantDomain);
} else {
String tenantDomainFromId = APIUtil.getTenantDomainFromTenantId(policy.getTenantId());
return !StringUtils.isBlank(tenantDomainFromId) && tenantDomainFromId.equals(userTenantDomain);
}
}
/**
* Checks whether given block condition is allowed to access to user
*
* @param user username with tenant domain
* @param blockCondition Block condition to check
* @return true if user is allowed to access the block condition
*/
public static boolean isBlockConditionAccessibleToUser(String user, BlockConditionsDTO blockCondition) {
String userTenantDomain = MultitenantUtils.getTenantDomain(user);
return !StringUtils.isBlank(blockCondition.getTenantDomain()) && blockCondition.getTenantDomain()
.equals(userTenantDomain);
}
/**
* Validate the required properties of Custom Rule Policy
*
* @param customRuleDTO custom rule object to check
* @param httpMethod HTTP method of the request
* @throws APIManagementException if a required property validation fails
*/
public static void validateCustomRuleRequiredProperties(CustomRuleDTO customRuleDTO, String httpMethod)
throws APIManagementException {
String propertyName;
//policyName property is validated only for POST request
if (httpMethod.equalsIgnoreCase(APIConstants.HTTP_POST)) {
if (StringUtils.isBlank(customRuleDTO.getPolicyName())) {
propertyName = "policyName";
throw new APIManagementException(propertyName + " property value of payload cannot be blank",
ExceptionCodes.from(ExceptionCodes.BLANK_PROPERTY_VALUE, propertyName));
}
}
if (StringUtils.isBlank(customRuleDTO.getSiddhiQuery())) {
propertyName = "siddhiQuery";
throw new APIManagementException(propertyName + " property value of payload cannot be blank",
ExceptionCodes.from(ExceptionCodes.BLANK_PROPERTY_VALUE, propertyName));
}
if (StringUtils.isBlank(customRuleDTO.getKeyTemplate())) {
propertyName = "keyTemplate";
throw new APIManagementException(propertyName + " property value of payload cannot be blank",
ExceptionCodes.from(ExceptionCodes.BLANK_PROPERTY_VALUE, propertyName));
}
}
/**
* Validate the policy name property of Throttle Policy
*
* @param policyName policy name value of throttle policy
*/
public static void validateThrottlePolicyNameProperty(String policyName)
throws APIManagementException {
if (StringUtils.isBlank(policyName)) {
String propertyName = "policyName";
throw new APIManagementException(propertyName + " property value of payload cannot be blank",
ExceptionCodes.from(ExceptionCodes.BLANK_PROPERTY_VALUE, propertyName));
}
}
/**
* Constructs an error message to indicate that the object corresponding to the specified type has not been provided
*
* @param typeEnum enum representing the particular type
* @return constructed error message
*/
public static String constructMissingThrottleObjectErrorMessage(Enum<?> typeEnum) {
String propertyName = null;
if (typeEnum.equals(ThrottleConditionDTO.TypeEnum.HEADERCONDITION)) {
propertyName = "headerCondition";
}
if (typeEnum.equals(ThrottleConditionDTO.TypeEnum.IPCONDITION)) {
propertyName = "ipCondition";
}
if (typeEnum.equals(ThrottleConditionDTO.TypeEnum.QUERYPARAMETERCONDITION)) {
propertyName = "queryParameter";
}
if (typeEnum.equals(ThrottleConditionDTO.TypeEnum.JWTCLAIMSCONDITION)) {
propertyName = "jwtClaimsCondition";
}
if (typeEnum.equals(ThrottleLimitDTO.TypeEnum.REQUESTCOUNTLIMIT)) {
propertyName = "requestCount";
}
if (typeEnum.equals(ThrottleLimitDTO.TypeEnum.BANDWIDTHLIMIT)) {
propertyName = "bandwidth";
}
return propertyName + " object corresponding to type " + typeEnum + " not provided\n";
}
/**
* Import the content of the provided tenant theme archive to the file system
*
* @param themeContent content relevant to the tenant theme
* @param tenantDomain tenant to which the theme is imported
* @throws APIManagementException if an error occurs while importing the tenant theme to the file system
* @throws IOException if an error occurs while deleting an incomplete tenant theme directory
*/
public static void importTenantTheme(InputStream themeContent, String tenantDomain, InputStream existingTenantTheme)
throws APIManagementException, IOException {
ZipInputStream zipInputStream = null;
byte[] buffer = new byte[1024];
File tenantThemeDirectory = null;
File backupDirectory = null;
String outputFolder = getTenantThemeDirectoryPath(tenantDomain);
try {
//create output directory if it does not exist
tenantThemeDirectory = new File(outputFolder);
if (!tenantThemeDirectory.exists()) {
if (!tenantThemeDirectory.mkdirs()) {
APIUtil.handleException("Unable to create tenant theme directory at " + outputFolder);
}
} else {
//Copy the existing tenant theme as a backup in case a restoration is needed to take place
String tempPath = getTenantThemeBackupDirectoryPath(tenantDomain);
backupDirectory = new File(tempPath);
FileUtils.copyDirectory(tenantThemeDirectory, backupDirectory);
//remove existing files inside the directory
FileUtils.cleanDirectory(tenantThemeDirectory);
}
//get the zip file content
zipInputStream = new ZipInputStream(themeContent);
//get the zipped file list entry
ZipEntry zipEntry = zipInputStream.getNextEntry();
while (zipEntry != null) {
String fileName = zipEntry.getName();
APIUtil.validateFileName(fileName);
File newFile = new File(outputFolder + File.separator + fileName);
String canonicalizedNewFilePath = newFile.getCanonicalPath();
String canonicalizedDestinationPath = new File(outputFolder).getCanonicalPath();
if (!canonicalizedNewFilePath.startsWith(canonicalizedDestinationPath)) {
APIUtil.handleException(
"Attempt to upload invalid zip archive with file at " + fileName + ". File path is " +
"outside target directory");
}
if (zipEntry.isDirectory()) {
if (!newFile.exists()) {
boolean status = newFile.mkdir();
if (!status) {
APIUtil.handleException("Error while creating " + newFile.getName() + " directory");
}
}
} else {
String ext = FilenameUtils.getExtension(zipEntry.getName());
if (EXTENSION_WHITELIST.contains(ext)) {
//create all non exists folders
//else you will hit FileNotFoundException for compressed folder
new File(newFile.getParent()).mkdirs();
FileOutputStream fileOutputStream = new FileOutputStream(newFile);
int len;
while ((len = zipInputStream.read(buffer)) > 0) {
fileOutputStream.write(buffer, 0, len);
}
fileOutputStream.close();
} else {
APIUtil.handleException(
"Unsupported file is uploaded with tenant theme by " + tenantDomain + " : file name : "
+ zipEntry.getName());
}
}
zipEntry = zipInputStream.getNextEntry();
}
zipInputStream.closeEntry();
zipInputStream.close();
if (backupDirectory != null) {
FileUtils.deleteDirectory(backupDirectory);
}
} catch (APIManagementException | IOException e) {
revertTenantThemeImportChanges(tenantDomain, existingTenantTheme);
throw new APIManagementException(e.getMessage(),
ExceptionCodes.from(ExceptionCodes.TENANT_THEME_IMPORT_FAILED, tenantDomain, tenantDomain));
} finally {
IOUtils.closeQuietly(zipInputStream);
IOUtils.closeQuietly(themeContent);
}
}
/**
* Retrieves the directory location in the file system where the tenant theme is imported
*
* @param tenantDomain tenant to which the theme is imported
* @return directory location in the file system where the tenant theme is imported
*/
public static String getTenantThemeDirectoryPath(String tenantDomain) {
return "repository" + File.separator + "deployment" + File.separator + "server" + File.separator + "jaggeryapps"
+ File.separator + "devportal" + File.separator + "site" + File.separator + "public"
+ File.separator + "tenant_themes" + File.separator + tenantDomain;
}
/**
* Retrieves the directory location in the file system where the tenant theme is temporarily backed-up
*
* @param tenantDomain tenant to which the theme is imported
* @return directory location in the file system where the tenant theme is temporarily backed-up
*/
public static String getTenantThemeBackupDirectoryPath(String tenantDomain) {
return System.getProperty(RestApiConstants.JAVA_IO_TMPDIR) + File.separator + tenantDomain;
}
/**
* Reverts the changes that occurred when importing a tenant theme
*
* @param tenantDomain tenant to which the theme is imported
* @param existingTenantTheme tenant theme which existed before the current import operation
* @throws APIManagementException if an error occurs when reverting the changes
* @throws IOException if an error occurs when reverting the changes
*/
public static void revertTenantThemeImportChanges(String tenantDomain, InputStream existingTenantTheme)
throws APIManagementException, IOException {
int tenantId = APIUtil.getTenantIdFromTenantDomain(tenantDomain);
String tenantThemeDirectoryPath = getTenantThemeDirectoryPath(tenantDomain);
File tenantThemeDirectory = new File(tenantThemeDirectoryPath);
if (existingTenantTheme == null) {
removeTenantTheme(tenantId, tenantThemeDirectory);
} else {
String tenantThemeBackupDirectoryPath = getTenantThemeBackupDirectoryPath(tenantDomain);
File backupDirectory = new File(tenantThemeBackupDirectoryPath);
restoreTenantTheme(tenantId, tenantThemeDirectory, backupDirectory, existingTenantTheme);
}
}
/**
* Deletes a tenant theme from the file system and deletes the tenant theme from the database
*
* @param tenantId tenant ID of the tenant to which the theme is imported
* @param tenantThemeDirectory directory in the file system to where the tenant theme is imported
* @throws APIManagementException if an error occurs when deleting the tenant theme from the database
* @throws IOException if an error occurs when deleting the tenant theme directory
*/
public static void removeTenantTheme(int tenantId, File tenantThemeDirectory)
throws APIManagementException, IOException {
APIAdmin apiAdmin = new APIAdminImpl();
FileUtils.deleteDirectory(tenantThemeDirectory);
apiAdmin.deleteTenantTheme(tenantId);
}
/**
* Restores the tenant theme which existed before the current import operation was performed
*
* @param tenantId tenant ID of the tenant to which the theme is imported
* @param tenantThemeDirectory directory in the file system to where the tenant theme is imported
* @param backupDirectory directory in the file system where the tenant theme is temporarily backed-up
* @param existingTenantTheme tenant theme which existed before the current import operation
* @throws APIManagementException if an error occurs when updating the tenant theme in the database
* @throws IOException if an error occurs when restoring the tenant theme directory
*/
public static void restoreTenantTheme(int tenantId, File tenantThemeDirectory, File backupDirectory,
InputStream existingTenantTheme) throws APIManagementException, IOException {
APIAdmin apiAdmin = new APIAdminImpl();
FileUtils.copyDirectory(backupDirectory, tenantThemeDirectory);
FileUtils.deleteDirectory(backupDirectory);
apiAdmin.updateTenantTheme(tenantId, existingTenantTheme);
}
}
| components/apimgt/org.wso2.carbon.apimgt.rest.api.admin.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/admin/v1/utils/RestApiAdminUtils.java | /*
* Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.wso2.carbon.apimgt.rest.api.admin.v1.utils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.wso2.carbon.apimgt.api.APIAdmin;
import org.wso2.carbon.apimgt.api.APIManagementException;
import org.wso2.carbon.apimgt.api.ExceptionCodes;
import org.wso2.carbon.apimgt.api.model.BlockConditionsDTO;
import org.wso2.carbon.apimgt.api.model.policy.Policy;
import org.wso2.carbon.apimgt.impl.APIAdminImpl;
import org.wso2.carbon.apimgt.impl.APIConstants;
import org.wso2.carbon.apimgt.impl.utils.APIUtil;
import org.wso2.carbon.apimgt.rest.api.admin.v1.dto.CustomRuleDTO;
import org.wso2.carbon.apimgt.rest.api.admin.v1.dto.ThrottleConditionDTO;
import org.wso2.carbon.apimgt.rest.api.admin.v1.dto.ThrottleLimitDTO;
import org.wso2.carbon.apimgt.rest.api.util.RestApiConstants;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class RestApiAdminUtils {
//using a set for file extensions white list since it will be faster to search
private static final Set<String> EXTENSION_WHITELIST = new HashSet<String>(Arrays.asList(
"css", "jpg", "png", "gif", "svg", "ttf", "html", "js", "json", "ico"));
/**
* Checks whether given policy is allowed to access to user
*
* @param user username with tenant domain
* @param policy policy to check
* @return true if user is allowed to access the policy
*/
public static boolean isPolicyAccessibleToUser(String user, Policy policy) {
//This block checks whether policy's tenant domain and user's tenant domain are same
String userTenantDomain = MultitenantUtils.getTenantDomain(user);
if (!StringUtils.isBlank(policy.getTenantDomain())) {
return policy.getTenantDomain().equals(userTenantDomain);
} else {
String tenantDomainFromId = APIUtil.getTenantDomainFromTenantId(policy.getTenantId());
return !StringUtils.isBlank(tenantDomainFromId) && tenantDomainFromId.equals(userTenantDomain);
}
}
/**
* Checks whether given block condition is allowed to access to user
*
* @param user username with tenant domain
* @param blockCondition Block condition to check
* @return true if user is allowed to access the block condition
*/
public static boolean isBlockConditionAccessibleToUser(String user, BlockConditionsDTO blockCondition) {
String userTenantDomain = MultitenantUtils.getTenantDomain(user);
return !StringUtils.isBlank(blockCondition.getTenantDomain()) && blockCondition.getTenantDomain()
.equals(userTenantDomain);
}
/**
* Validate the required properties of Custom Rule Policy
*
* @param customRuleDTO custom rule object to check
* @param httpMethod HTTP method of the request
* @throws APIManagementException if a required property validation fails
*/
public static void validateCustomRuleRequiredProperties(CustomRuleDTO customRuleDTO, String httpMethod)
throws APIManagementException {
String propertyName;
//policyName property is validated only for POST request
if (httpMethod.equalsIgnoreCase(APIConstants.HTTP_POST)) {
if (StringUtils.isBlank(customRuleDTO.getPolicyName())) {
propertyName = "policyName";
throw new APIManagementException(propertyName + " property value of payload cannot be blank",
ExceptionCodes.from(ExceptionCodes.BLANK_PROPERTY_VALUE, propertyName));
}
}
if (StringUtils.isBlank(customRuleDTO.getSiddhiQuery())) {
propertyName = "siddhiQuery";
throw new APIManagementException(propertyName + " property value of payload cannot be blank",
ExceptionCodes.from(ExceptionCodes.BLANK_PROPERTY_VALUE, propertyName));
}
if (StringUtils.isBlank(customRuleDTO.getKeyTemplate())) {
propertyName = "keyTemplate";
throw new APIManagementException(propertyName + " property value of payload cannot be blank",
ExceptionCodes.from(ExceptionCodes.BLANK_PROPERTY_VALUE, propertyName));
}
}
/**
* Validate the policy name property of Throttle Policy
*
* @param policyName policy name value of throttle policy
*/
public static void validateThrottlePolicyNameProperty(String policyName)
throws APIManagementException {
if (StringUtils.isBlank(policyName)) {
String propertyName = "policyName";
throw new APIManagementException(propertyName + " property value of payload cannot be blank",
ExceptionCodes.from(ExceptionCodes.BLANK_PROPERTY_VALUE, propertyName));
}
}
/**
* Constructs an error message to indicate that the object corresponding to the specified type has not been provided
*
* @param typeEnum enum representing the particular type
* @return constructed error message
*/
public static String constructMissingThrottleObjectErrorMessage(Enum<?> typeEnum) {
String propertyName = null;
if (typeEnum.equals(ThrottleConditionDTO.TypeEnum.HEADERCONDITION)) {
propertyName = "headerCondition";
}
if (typeEnum.equals(ThrottleConditionDTO.TypeEnum.IPCONDITION)) {
propertyName = "ipCondition";
}
if (typeEnum.equals(ThrottleConditionDTO.TypeEnum.QUERYPARAMETERCONDITION)) {
propertyName = "queryParameter";
}
if (typeEnum.equals(ThrottleConditionDTO.TypeEnum.JWTCLAIMSCONDITION)) {
propertyName = "jwtClaimsCondition";
}
if (typeEnum.equals(ThrottleLimitDTO.TypeEnum.REQUESTCOUNTLIMIT)) {
propertyName = "requestCount";
}
if (typeEnum.equals(ThrottleLimitDTO.TypeEnum.BANDWIDTHLIMIT)) {
propertyName = "bandwidth";
}
return propertyName + " object corresponding to type " + typeEnum + " not provided\n";
}
/**
* Import the content of the provided tenant theme archive to the file system
*
* @param themeContent content relevant to the tenant theme
* @param tenantDomain tenant to which the theme is imported
* @throws APIManagementException if an error occurs while importing the tenant theme to the file system
* @throws IOException if an error occurs while deleting an incomplete tenant theme directory
*/
public static void importTenantTheme(InputStream themeContent, String tenantDomain, InputStream existingTenantTheme)
throws APIManagementException, IOException {
ZipInputStream zipInputStream = null;
byte[] buffer = new byte[1024];
File tenantThemeDirectory = null;
File backupDirectory = null;
String outputFolder = getTenantThemeDirectoryPath(tenantDomain);
try {
//create output directory if it does not exist
tenantThemeDirectory = new File(outputFolder);
if (!tenantThemeDirectory.exists()) {
if (!tenantThemeDirectory.mkdirs()) {
APIUtil.handleException("Unable to create tenant theme directory at " + outputFolder);
}
} else {
//Copy the existing tenant theme as a backup in case a restoration is needed to take place
String tempPath = getTenantThemeBackupDirectoryPath(tenantDomain);
backupDirectory = new File(tempPath);
FileUtils.copyDirectory(tenantThemeDirectory, backupDirectory);
//remove existing files inside the directory
FileUtils.cleanDirectory(tenantThemeDirectory);
}
//get the zip file content
zipInputStream = new ZipInputStream(themeContent);
//get the zipped file list entry
ZipEntry zipEntry = zipInputStream.getNextEntry();
while (zipEntry != null) {
String fileName = zipEntry.getName();
APIUtil.validateFileName(fileName);
File newFile = new File(outputFolder + File.separator + fileName);
String canonicalizedNewFilePath = newFile.getCanonicalPath();
String canonicalizedDestinationPath = new File(outputFolder).getCanonicalPath();
if (!canonicalizedNewFilePath.startsWith(canonicalizedDestinationPath)) {
APIUtil.handleException(
"Attempt to upload invalid zip archive with file at " + fileName + ". File path is " +
"outside target directory");
}
if (zipEntry.isDirectory()) {
if (!newFile.exists()) {
boolean status = newFile.mkdir();
if (!status) {
APIUtil.handleException("Error while creating " + newFile.getName() + " directory");
}
}
} else {
String ext = FilenameUtils.getExtension(zipEntry.getName());
if (EXTENSION_WHITELIST.contains(ext)) {
//create all non exists folders
//else you will hit FileNotFoundException for compressed folder
new File(newFile.getParent()).mkdirs();
FileOutputStream fileOutputStream = new FileOutputStream(newFile);
int len;
while ((len = zipInputStream.read(buffer)) > 0) {
fileOutputStream.write(buffer, 0, len);
}
fileOutputStream.close();
} else {
APIUtil.handleException(
"Unsupported file is uploaded with tenant theme by " + tenantDomain + " : file name : "
+ zipEntry.getName());
}
}
zipEntry = zipInputStream.getNextEntry();
}
zipInputStream.closeEntry();
zipInputStream.close();
FileUtils.deleteDirectory(backupDirectory);
} catch (APIManagementException | IOException e) {
revertTenantThemeImportChanges(tenantDomain, existingTenantTheme);
throw new APIManagementException(e.getMessage(),
ExceptionCodes.from(ExceptionCodes.TENANT_THEME_IMPORT_FAILED, tenantDomain, tenantDomain));
} finally {
IOUtils.closeQuietly(zipInputStream);
IOUtils.closeQuietly(themeContent);
}
}
/**
* Retrieves the directory location in the file system where the tenant theme is imported
*
* @param tenantDomain tenant to which the theme is imported
* @return directory location in the file system where the tenant theme is imported
*/
public static String getTenantThemeDirectoryPath(String tenantDomain) {
return "repository" + File.separator + "deployment" + File.separator + "server" + File.separator + "jaggeryapps"
+ File.separator + "devportal" + File.separator + "site" + File.separator + "public"
+ File.separator + "tenant_themes" + File.separator + tenantDomain;
}
/**
* Retrieves the directory location in the file system where the tenant theme is temporarily backed-up
*
* @param tenantDomain tenant to which the theme is imported
* @return directory location in the file system where the tenant theme is temporarily backed-up
*/
public static String getTenantThemeBackupDirectoryPath(String tenantDomain) {
return System.getProperty(RestApiConstants.JAVA_IO_TMPDIR) + File.separator + tenantDomain;
}
/**
* Reverts the changes that occurred when importing a tenant theme
*
* @param tenantDomain tenant to which the theme is imported
* @param existingTenantTheme tenant theme which existed before the current import operation
* @throws APIManagementException if an error occurs when reverting the changes
* @throws IOException if an error occurs when reverting the changes
*/
public static void revertTenantThemeImportChanges(String tenantDomain, InputStream existingTenantTheme)
throws APIManagementException, IOException {
int tenantId = APIUtil.getTenantIdFromTenantDomain(tenantDomain);
String tenantThemeDirectoryPath = getTenantThemeDirectoryPath(tenantDomain);
File tenantThemeDirectory = new File(tenantThemeDirectoryPath);
if (existingTenantTheme == null) {
removeTenantTheme(tenantId, tenantThemeDirectory);
} else {
String tenantThemeBackupDirectoryPath = getTenantThemeBackupDirectoryPath(tenantDomain);
File backupDirectory = new File(tenantThemeBackupDirectoryPath);
restoreTenantTheme(tenantId, tenantThemeDirectory, backupDirectory, existingTenantTheme);
}
}
/**
* Deletes a tenant theme from the file system and deletes the tenant theme from the database
*
* @param tenantId tenant ID of the tenant to which the theme is imported
* @param tenantThemeDirectory directory in the file system to where the tenant theme is imported
* @throws APIManagementException if an error occurs when deleting the tenant theme from the database
* @throws IOException if an error occurs when deleting the tenant theme directory
*/
public static void removeTenantTheme(int tenantId, File tenantThemeDirectory)
throws APIManagementException, IOException {
APIAdmin apiAdmin = new APIAdminImpl();
FileUtils.deleteDirectory(tenantThemeDirectory);
apiAdmin.deleteTenantTheme(tenantId);
}
/**
* Restores the tenant theme which existed before the current import operation was performed
*
* @param tenantId tenant ID of the tenant to which the theme is imported
* @param tenantThemeDirectory directory in the file system to where the tenant theme is imported
* @param backupDirectory directory in the file system where the tenant theme is temporarily backed-up
* @param existingTenantTheme tenant theme which existed before the current import operation
* @throws APIManagementException if an error occurs when updating the tenant theme in the database
* @throws IOException if an error occurs when restoring the tenant theme directory
*/
public static void restoreTenantTheme(int tenantId, File tenantThemeDirectory, File backupDirectory,
InputStream existingTenantTheme) throws APIManagementException, IOException {
APIAdmin apiAdmin = new APIAdminImpl();
FileUtils.copyDirectory(backupDirectory, tenantThemeDirectory);
FileUtils.deleteDirectory(backupDirectory);
apiAdmin.updateTenantTheme(tenantId, existingTenantTheme);
}
}
| Add null check before deleting backup directory
| components/apimgt/org.wso2.carbon.apimgt.rest.api.admin.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/admin/v1/utils/RestApiAdminUtils.java | Add null check before deleting backup directory | <ide><path>omponents/apimgt/org.wso2.carbon.apimgt.rest.api.admin.v1/src/main/java/org/wso2/carbon/apimgt/rest/api/admin/v1/utils/RestApiAdminUtils.java
<ide> }
<ide> zipInputStream.closeEntry();
<ide> zipInputStream.close();
<del> FileUtils.deleteDirectory(backupDirectory);
<add> if (backupDirectory != null) {
<add> FileUtils.deleteDirectory(backupDirectory);
<add> }
<ide> } catch (APIManagementException | IOException e) {
<ide> revertTenantThemeImportChanges(tenantDomain, existingTenantTheme);
<ide> throw new APIManagementException(e.getMessage(), |
|
Java | apache-2.0 | 904528030aec88881fa28ed3d1ffb755ef74525f | 0 | ReactiveX/RxJavaFX,ReactiveX/RxJavaFX | /**
* Copyright 2016 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package rx.javafx.sources;
import rx.Observable;
import rx.Subscription;
import rx.annotations.Beta;
import rx.subjects.PublishSubject;
import rx.subjects.SerializedSubject;
import rx.subscriptions.CompositeSubscription;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
/**
* A CompositeObservable can merge multiple event source Observables that can be added/removed at any time,
* affecting all Subscribers regardless of when they subscribed. This is especially helpful for merging
* multiple UI event sources. You can also pass a Transformer to perform
* further operations on the combined Observable that is returned
*
* @param <T>
*/
public final class CompositeObservable<T> {
private final SerializedSubject<T,T> subject;
private final Observable<T> output;
/**
* Creates a new CompositeObservable
*/
public CompositeObservable() {
this(null);
}
/**
* Creates a new CompositeObservable with the provided transformations applied to the returned Observable
* yield from `toObservable()`. For instance, you can pass `obs -> obs.replay(1).refCount()` to make this CompositeObservable
* @param transformer
*/
public CompositeObservable(Observable.Transformer<T,T> transformer) {
subject = PublishSubject.<T>create().toSerialized();
Observable<T> updatingSource = subject.asObservable();
if (transformer == null) {
output = updatingSource;
} else {
output = updatingSource.compose(transformer);
}
}
/**
* Returns the `Observable` combining all the source Observables, with any transformations that were specified
* on construction.
* @return
*/
public Observable<T> toObservable() {
return output;
}
public Subscription add(Observable<T> observable) {
return observable.subscribe(subject);
}
public CompositeSubscription addAll(Observable<T>... observables) {
final CompositeSubscription subscriptions = new CompositeSubscription();
Arrays.stream(observables).map(this::add).forEach(subscriptions::add);
return subscriptions;
}
}
| src/main/java/rx/javafx/sources/CompositeObservable.java | /**
* Copyright 2016 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package rx.javafx.sources;
import rx.Observable;
import rx.Subscription;
import rx.annotations.Beta;
import rx.subjects.PublishSubject;
import rx.subjects.SerializedSubject;
import rx.subscriptions.CompositeSubscription;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
/**
* A CompositeObservable can merge multiple event source Observables that can be added/removed at any time,
* affecting all Subscribers regardless of when they subscribed. This is especially helpful for merging
* multiple UI event sources. You can also pass a Transformer to perform
* further operations on the combined Observable that is returned
*
* @param <T>
*/
@Beta
public final class CompositeObservable<T> {
private final SerializedSubject<T,T> subject;
private final Observable<T> output;
/**
* Creates a new CompositeObservable
*/
public CompositeObservable() {
this(null);
}
/**
* Creates a new CompositeObservable with the provided transformations applied to the returned Observable
* yield from `toObservable()`. For instance, you can pass `obs -> obs.replay(1).refCount()` to make this CompositeObservable
* @param transformer
*/
public CompositeObservable(Observable.Transformer<T,T> transformer) {
subject = PublishSubject.<T>create().toSerialized();
Observable<T> updatingSource = subject.asObservable();
if (transformer == null) {
output = updatingSource;
} else {
output = updatingSource.compose(transformer);
}
}
/**
* Returns the `Observable` combining all the source Observables, with any transformations that were specified
* on construction.
* @return
*/
public Observable<T> toObservable() {
return output;
}
public Subscription add(Observable<T> observable) {
return observable.subscribe(subject);
}
public CompositeSubscription addAll(Observable<T>... observables) {
final CompositeSubscription subscriptions = new CompositeSubscription();
Arrays.stream(observables).map(this::add).forEach(subscriptions::add);
return subscriptions;
}
}
| remove @Beta tag for CompositeObservable
| src/main/java/rx/javafx/sources/CompositeObservable.java | remove @Beta tag for CompositeObservable | <ide><path>rc/main/java/rx/javafx/sources/CompositeObservable.java
<ide> *
<ide> * @param <T>
<ide> */
<del>@Beta
<add>
<ide> public final class CompositeObservable<T> {
<ide>
<ide> private final SerializedSubject<T,T> subject; |
|
Java | mit | bc16e958d360fa631188c42f9f5787de939af36c | 0 | emacslisp/Java,emacslisp/Java,emacslisp/Java,emacslisp/Java | package com.dw.lib.cli;
import java.util.HashSet;
import java.util.UUID;
public class BallCLI {
public static int BallRandom() {
String uuid = UUID.randomUUID().toString();
uuid = uuid.replace("-", "");
int counter = 0;
int total = 0;
for (int i = 0; i < uuid.length(); i++) {
char c = uuid.charAt(i);
int num = 0;
if (c >= '0' && c <= '9') {
num = c - '0';
}
if (c >= 'a' && c <= 'z') {
num = c - 'a' + 10;
}
int base = 1;
for (int j = 0; j < counter; j++) {
base *= 16;
base %= 35;
}
counter++;
total += num * base;
}
return total;
}
public static void generate() {
HashSet<Integer> hash = new HashSet<>();
for (int k = 0; k < 8; k++) {
int total = BallRandom();
if (k < 7) {
int result = total % 35;
if (result == 0) {
k--;
continue;
}
if (!hash.contains(result)) {
System.out.print(result + " ");
hash.add(result);
} else {
k--;
continue;
}
} else {
int result = total % 20;
if (result == 0) {
k--;
continue;
}
System.out.print(total % 20 + " ");
}
}
System.out.println();
}
public static void main(String[] args) {
try {
if (args.length != 1) {
System.out.println("ball to generate 8 number");
System.out.println("ball <how many you want to generate>");
return;
}
int num = Integer.parseInt(args[0]);
for (int i = 0; i < num; i++) {
generate();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
| JavaMain/src/com/dw/lib/cli/BallCLI.java | package com.dw.lib.cli;
import java.util.HashSet;
import java.util.UUID;
public class BallCLI {
public static int BallRandom() {
String uuid = UUID.randomUUID().toString();
uuid = uuid.replace("-", "");
int counter = 0;
int total = 0;
for (int i = 0; i < uuid.length(); i++) {
char c = uuid.charAt(i);
int num = 0;
if (c >= '0' && c <= '9') {
num = c - '0';
}
if (c >= 'a' && c <= 'z') {
num = c - 'a' + 10;
}
int base = 1;
for (int j = 0; j < counter; j++) {
base *= 16;
base %= 35;
}
counter++;
total += num * base;
}
return total;
}
public static void generate() {
HashSet<Integer> hash = new HashSet<>();
for (int k = 0; k < 8; k++) {
int total = BallRandom();
if (k < 7) {
int result = total % 35;
if (result == 0) {
k--;
continue;
}
if (!hash.contains(result)) {
System.out.print(result + " ");
hash.add(result);
} else {
k--;
continue;
}
} else {
int result = total % 20;
if (result == 0) {
k--;
continue;
}
System.out.print(total % 20 + " ");
}
}
}
public static void main(String[] args) {
try {
if (args.length != 1) {
System.out.println("ball to view a text file");
System.out.println("ball <how many you want to generate>");
return;
}
int num = Integer.parseInt(args[0]);
for (int i = 0; i < num; i++) {
generate();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
| #Ball - change text help | JavaMain/src/com/dw/lib/cli/BallCLI.java | #Ball - change text help | <ide><path>avaMain/src/com/dw/lib/cli/BallCLI.java
<ide> System.out.print(total % 20 + " ");
<ide> }
<ide> }
<add>
<add> System.out.println();
<ide> }
<ide>
<ide> public static void main(String[] args) {
<ide> try {
<ide> if (args.length != 1) {
<del> System.out.println("ball to view a text file");
<add> System.out.println("ball to generate 8 number");
<ide> System.out.println("ball <how many you want to generate>");
<ide> return;
<ide> } |
|
JavaScript | mit | b592e0e592bb80141b0b4f880dc3b0069e21301c | 0 | ghacksuserjs/ghacks-user.js,ghacksuserjs/ghacks-user.js | /******
* name: arkenfox user.js
* date: 02 March 2021
* version 87-alpha
* url: https://github.com/arkenfox/user.js
* license: MIT: https://github.com/arkenfox/user.js/blob/master/LICENSE.txt
* README:
1. Consider using Tor Browser if it meets your needs or fits your threat model better
* https://www.torproject.org/about/torusers.html.en
2. Required reading: Overview, Backing Up, Implementing, and Maintenance entries
* https://github.com/arkenfox/user.js/wiki
3. If you skipped step 2, return to step 2
4. Make changes
* There are often trade-offs and conflicts between security vs privacy vs anti-fingerprinting
and these need to be balanced against functionality & convenience & breakage
* Some site breakage and unintended consequences will happen. Everyone's experience will differ
e.g. some user data is erased on close (section 2800), change this to suit your needs
* While not 100% definitive, search for "[SETUP" tags
e.g. third party images/videos not loading on some sites? check 1603
* Take the wiki link in step 2 and read the Troubleshooting entry
5. Some tag info
[SETUP-SECURITY] it's one item, read it
[SETUP-WEB] can cause some websites to break
[SETUP-CHROME] changes how Firefox itself behaves (i.e. not directly website related)
[SETUP-PERF] may impact performance
[WARNING] used sparingly, heed them
6. Override Recipes: https://github.com/arkenfox/user.js/issues/1080
* RELEASES: https://github.com/arkenfox/user.js/releases
* It is best to use the arkenfox release that is optimized for and matches your Firefox version
* EVERYONE: each release
- run prefsCleaner or reset deprecated prefs (9999s) and prefs made redundant by RPF (4600s)
- re-enable section 4600 if you don't use RFP
ESR78
- If you are not using arkenfox v78... (not a definitive list)
- 1244: HTTPS-Only mode is enabled
- 1401: document fonts is inactive as it is now covered by RFP in FF80+
- 4600: some prefs may apply even if you use RFP
- 9999: switch the appropriate deprecated section(s) back on
* INDEX:
0100: STARTUP
0200: GEOLOCATION / LANGUAGE / LOCALE
0300: QUIET FOX
0400: BLOCKLISTS / SAFE BROWSING
0500: SYSTEM ADD-ONS / EXPERIMENTS
0600: BLOCK IMPLICIT OUTBOUND
0700: HTTP* / TCP/IP / DNS / PROXY / SOCKS etc
0800: LOCATION BAR / SEARCH BAR / SUGGESTIONS / HISTORY / FORMS
0900: PASSWORDS
1000: CACHE / SESSION (RE)STORE / FAVICONS
1200: HTTPS (SSL/TLS / OCSP / CERTS / HPKP / CIPHERS)
1400: FONTS
1600: HEADERS / REFERERS
1700: CONTAINERS
1800: PLUGINS
2000: MEDIA / CAMERA / MIC
2200: WINDOW MEDDLING & LEAKS / POPUPS
2300: WEB WORKERS
2400: DOM (DOCUMENT OBJECT MODEL) & JAVASCRIPT
2500: HARDWARE FINGERPRINTING
2600: MISCELLANEOUS
2700: PERSISTENT STORAGE
2800: SHUTDOWN
4000: FPI (FIRST PARTY ISOLATION)
4500: RFP (RESIST FINGERPRINTING)
4600: RFP ALTERNATIVES
4700: RFP ALTERNATIVES (USER AGENT SPOOFING)
5000: PERSONAL
9999: DEPRECATED / REMOVED / LEGACY / RENAMED
******/
/* START: internal custom pref to test for syntax errors
* [NOTE] In FF60+, not all syntax errors cause parsing to abort i.e. reaching the last debug
* pref no longer necessarily means that all prefs have been applied. Check the console right
* after startup for any warnings/error messages related to non-applied prefs
* [1] https://blog.mozilla.org/nnethercote/2018/03/09/a-new-preferences-parser-for-firefox/ ***/
user_pref("_user.js.parrot", "START: Oh yes, the Norwegian Blue... what's wrong with it?");
/* 0000: disable about:config warning
* FF73-86: chrome://global/content/config.xhtml ***/
user_pref("general.warnOnAboutConfig", false); // XHTML version
user_pref("browser.aboutConfig.showWarning", false); // HTML version [FF71+]
/*** [SECTION 0100]: STARTUP ***/
user_pref("_user.js.parrot", "0100 syntax error: the parrot's dead!");
/* 0101: disable default browser check
* [SETTING] General>Startup>Always check if Firefox is your default browser ***/
user_pref("browser.shell.checkDefaultBrowser", false);
/* 0102: set START page (0=blank, 1=home, 2=last visited page, 3=resume previous session)
* [NOTE] Session Restore is not used in PB mode (0110) and is cleared with history (2803, 2804)
* [SETTING] General>Startup>Restore previous session ***/
user_pref("browser.startup.page", 0);
/* 0103: set HOME+NEWWINDOW page
* about:home=Activity Stream (default, see 0105), custom URL, about:blank
* [SETTING] Home>New Windows and Tabs>Homepage and new windows ***/
user_pref("browser.startup.homepage", "about:blank");
/* 0104: set NEWTAB page
* true=Activity Stream (default, see 0105), false=blank page
* [SETTING] Home>New Windows and Tabs>New tabs ***/
user_pref("browser.newtabpage.enabled", false);
user_pref("browser.newtab.preload", false);
/* 0105: disable Activity Stream stuff (AS)
* AS is the default homepage/newtab in FF57+, based on metadata and browsing behavior.
* **NOT LISTING ALL OF THESE: USE THE PREFERENCES UI**
* [SETTING] Home>Firefox Home Content>... to show/hide what you want ***/
/* 0105a: disable Activity Stream telemetry ***/
user_pref("browser.newtabpage.activity-stream.feeds.telemetry", false);
user_pref("browser.newtabpage.activity-stream.telemetry", false);
/* 0105b: disable Activity Stream Snippets
* Runs code received from a server (aka Remote Code Execution) and sends information back to a metrics server
* [1] https://abouthome-snippets-service.readthedocs.io/ ***/
user_pref("browser.newtabpage.activity-stream.feeds.snippets", false);
/* 0105c: disable Activity Stream Top Stories, Pocket-based and/or sponsored content ***/
user_pref("browser.newtabpage.activity-stream.feeds.section.topstories", false);
user_pref("browser.newtabpage.activity-stream.section.highlights.includePocket", false);
user_pref("browser.newtabpage.activity-stream.showSponsored", false);
user_pref("browser.newtabpage.activity-stream.feeds.discoverystreamfeed", false); // [FF66+]
/* 0105e: clear default topsites
* [NOTE] This does not block you from adding your own ***/
user_pref("browser.newtabpage.activity-stream.default.sites", "");
/* 0110: start Firefox in PB (Private Browsing) mode
* [NOTE] In this mode *all* windows are "private windows" and the PB mode icon is not displayed
* [WARNING] The P in PB mode is misleading: it means no "persistent" disk storage such as history,
* caches, searches, cookies, localStorage, IndexedDB etc (which you can achieve in normal mode).
* In fact, PB mode limits or removes the ability to control some of these, and you need to quit
* Firefox to clear them. PB is best used as a one off window (File>New Private Window) to provide
* a temporary self-contained new session. Close all Private Windows to clear the PB mode session.
* [SETTING] Privacy & Security>History>Custom Settings>Always use private browsing mode
* [1] https://wiki.mozilla.org/Private_Browsing
* [2] https://spreadprivacy.com/is-private-browsing-really-private/ ***/
// user_pref("browser.privatebrowsing.autostart", true);
/*** [SECTION 0200]: GEOLOCATION / LANGUAGE / LOCALE ***/
user_pref("_user.js.parrot", "0200 syntax error: the parrot's definitely deceased!");
/** GEOLOCATION ***/
/* 0201: disable Location-Aware Browsing
* [NOTE] Best left at default "true", fingerprintable, already behind a prompt (see 0202)
* [1] https://www.mozilla.org/firefox/geolocation/ ***/
// user_pref("geo.enabled", false);
/* 0202: set a default permission for Location (see 0201) [FF58+]
* 0=always ask (default), 1=allow, 2=block
* [NOTE] Best left at default "always ask", fingerprintable via Permissions API
* [SETTING] to add site exceptions: Ctrl+I>Permissions>Access Your Location
* [SETTING] to manage site exceptions: Options>Privacy & Security>Permissions>Location>Settings ***/
// user_pref("permissions.default.geo", 2);
/* 0203: use Mozilla geolocation service instead of Google when geolocation is enabled [FF74+]
* Optionally enable logging to the console (defaults to false) ***/
user_pref("geo.provider.network.url", "https://location.services.mozilla.com/v1/geolocate?key=%MOZILLA_API_KEY%");
// user_pref("geo.provider.network.logging.enabled", true); // [HIDDEN PREF]
/* 0204: disable using the OS's geolocation service ***/
user_pref("geo.provider.ms-windows-location", false); // [WINDOWS]
user_pref("geo.provider.use_corelocation", false); // [MAC]
user_pref("geo.provider.use_gpsd", false); // [LINUX]
/* 0207: disable region updates
* [1] https://firefox-source-docs.mozilla.org/toolkit/modules/toolkit_modules/Region.html ***/
user_pref("browser.region.network.url", ""); // [FF78+]
user_pref("browser.region.update.enabled", false); // [[FF79+]
/* 0208: set search region
* [NOTE] May not be hidden if Firefox has changed your settings due to your region (see 0207) ***/
// user_pref("browser.search.region", "US"); // [HIDDEN PREF]
/** LANGUAGE / LOCALE ***/
/* 0210: set preferred language for displaying web pages
* [TEST] https://addons.mozilla.org/about ***/
user_pref("intl.accept_languages", "en-US, en");
/* 0211: enforce US English locale regardless of the system locale
* [SETUP-WEB] May break some input methods e.g xim/ibus for CJK languages [1]
* [1] https://bugzilla.mozilla.org/buglist.cgi?bug_id=867501,1629630 ***/
user_pref("javascript.use_us_english_locale", true); // [HIDDEN PREF]
/*** [SECTION 0300]: QUIET FOX
We only disable the auto-INSTALL of Firefox (app) updates. You still get prompts to update,
and it only takes one click. We highly discourage disabling auto-CHECKING for updates.
Legitimate reasons to disable auto-INSTALLS include hijacked/monetized extensions, time
constraints, legacy issues, dev/testing, and fear of breakage/bugs. It is still important
to do updates for security reasons, please do so manually if you make changes.
***/
user_pref("_user.js.parrot", "0300 syntax error: the parrot's not pinin' for the fjords!");
/* 0301b: disable auto-CHECKING for extension and theme updates ***/
// user_pref("extensions.update.enabled", false);
/* 0302a: disable auto-INSTALLING Firefox updates [NON-WINDOWS FF65+]
* [NOTE] In FF65+ on Windows this SETTING (below) is now stored in a file and the pref was removed
* [SETTING] General>Firefox Updates>Check for updates but let you choose to install them ***/
user_pref("app.update.auto", false);
/* 0302b: disable auto-INSTALLING extension and theme updates (after the check in 0301b)
* [SETTING] about:addons>Extensions>[cog-wheel-icon]>Update Add-ons Automatically (toggle) ***/
// user_pref("extensions.update.autoUpdateDefault", false);
/* 0306: disable extension metadata
* used when installing/updating an extension, and in daily background update checks:
* when false, extension detail tabs will have no description ***/
// user_pref("extensions.getAddons.cache.enabled", false);
/* 0308: disable search engine updates (e.g. OpenSearch)
* [NOTE] This does not affect Mozilla's built-in or Web Extension search engines ***/
user_pref("browser.search.update", false);
/* 0309: disable sending Flash crash reports ***/
user_pref("dom.ipc.plugins.flash.subprocess.crashreporter.enabled", false);
/* 0310: disable sending the URL of the website where a plugin crashed ***/
user_pref("dom.ipc.plugins.reportCrashURL", false);
/* 0320: disable about:addons' Recommendations pane (uses Google Analytics) ***/
user_pref("extensions.getAddons.showPane", false); // [HIDDEN PREF]
/* 0321: disable recommendations in about:addons' Extensions and Themes panes [FF68+] ***/
user_pref("extensions.htmlaboutaddons.recommendations.enabled", false);
/* 0330: disable telemetry
* the pref (.unified) affects the behaviour of the pref (.enabled)
* IF unified=false then .enabled controls the telemetry module
* IF unified=true then .enabled ONLY controls whether to record extended data
* so make sure to have both set as false
* [NOTE] FF58+ 'toolkit.telemetry.enabled' is now LOCKED to reflect prerelease
* or release builds (true and false respectively) [2]
* [1] https://firefox-source-docs.mozilla.org/toolkit/components/telemetry/telemetry/internals/preferences.html
* [2] https://medium.com/georg-fritzsche/data-preference-changes-in-firefox-58-2d5df9c428b5 ***/
user_pref("toolkit.telemetry.unified", false);
user_pref("toolkit.telemetry.enabled", false); // see [NOTE]
user_pref("toolkit.telemetry.server", "data:,");
user_pref("toolkit.telemetry.archive.enabled", false);
user_pref("toolkit.telemetry.newProfilePing.enabled", false); // [FF55+]
user_pref("toolkit.telemetry.shutdownPingSender.enabled", false); // [FF55+]
user_pref("toolkit.telemetry.updatePing.enabled", false); // [FF56+]
user_pref("toolkit.telemetry.bhrPing.enabled", false); // [FF57+] Background Hang Reporter
user_pref("toolkit.telemetry.firstShutdownPing.enabled", false); // [FF57+]
/* 0331: disable Telemetry Coverage
* [1] https://blog.mozilla.org/data/2018/08/20/effectively-measuring-search-in-firefox/ ***/
user_pref("toolkit.telemetry.coverage.opt-out", true); // [HIDDEN PREF]
user_pref("toolkit.coverage.opt-out", true); // [FF64+] [HIDDEN PREF]
user_pref("toolkit.coverage.endpoint.base", "");
/* 0340: disable Health Reports
* [SETTING] Privacy & Security>Firefox Data Collection & Use>Allow Firefox to send technical... data ***/
user_pref("datareporting.healthreport.uploadEnabled", false);
/* 0341: disable new data submission, master kill switch [FF41+]
* If disabled, no policy is shown or upload takes place, ever
* [1] https://bugzilla.mozilla.org/1195552 ***/
user_pref("datareporting.policy.dataSubmissionEnabled", false);
/* 0342: disable Studies (see 0503)
* [SETTING] Privacy & Security>Firefox Data Collection & Use>Allow Firefox to install and run studies ***/
user_pref("app.shield.optoutstudies.enabled", false);
/* 0343: disable personalized Extension Recommendations in about:addons and AMO [FF65+]
* [NOTE] This pref has no effect when Health Reports (0340) are disabled
* [SETTING] Privacy & Security>Firefox Data Collection & Use>Allow Firefox to make personalized extension recommendations
* [1] https://support.mozilla.org/kb/personalized-extension-recommendations ***/
user_pref("browser.discovery.enabled", false);
/* 0350: disable Crash Reports ***/
user_pref("breakpad.reportURL", "");
user_pref("browser.tabs.crashReporting.sendReport", false); // [FF44+]
// user_pref("browser.crashReports.unsubmittedCheck.enabled", false); // [FF51+] [DEFAULT: false]
/* 0351: enforce no submission of backlogged Crash Reports [FF58+]
* [SETTING] Privacy & Security>Firefox Data Collection & Use>Allow Firefox to send backlogged crash reports ***/
user_pref("browser.crashReports.unsubmittedCheck.autoSubmit2", false); // [DEFAULT: false]
/* 0390: disable Captive Portal detection
* [1] https://www.eff.org/deeplinks/2017/08/how-captive-portals-interfere-wireless-security-and-privacy
* [2] https://wiki.mozilla.org/Necko/CaptivePortal ***/
user_pref("captivedetect.canonicalURL", "");
user_pref("network.captive-portal-service.enabled", false); // [FF52+]
/* 0391: disable Network Connectivity checks [FF65+]
* [1] https://bugzilla.mozilla.org/1460537 ***/
user_pref("network.connectivity-service.enabled", false);
/*** [SECTION 0400]: BLOCKLISTS / SAFE BROWSING (SB) ***/
user_pref("_user.js.parrot", "0400 syntax error: the parrot's passed on!");
/** BLOCKLISTS ***/
/* 0401: enforce Firefox blocklist
* [NOTE] It includes updates for "revoked certificates"
* [1] https://blog.mozilla.org/security/2015/03/03/revoking-intermediate-certificates-introducing-onecrl/ ***/
user_pref("extensions.blocklist.enabled", true); // [DEFAULT: true]
/** SAFE BROWSING (SB)
Safe Browsing has taken many steps to preserve privacy. *IF* required, a full url is never
sent to Google, only a PART-hash of the prefix, and this is hidden with noise of other real
PART-hashes. Google also swear it is anonymized and only used to flag malicious sites.
Firefox also takes measures such as striping out identifying parameters and since SBv4 (FF57+)
doesn't even use cookies. (#Turn on browser.safebrowsing.debug to monitor this activity)
#Required reading [#] https://feeding.cloud.geek.nz/posts/how-safe-browsing-works-in-firefox/
[1] https://wiki.mozilla.org/Security/Safe_Browsing
[2] https://support.mozilla.org/en-US/kb/how-does-phishing-and-malware-protection-work
***/
/* 0410: disable SB (Safe Browsing)
* [WARNING] Do this at your own risk! These are the master switches.
* [SETTING] Privacy & Security>Security>... "Block dangerous and deceptive content" ***/
// user_pref("browser.safebrowsing.malware.enabled", false);
// user_pref("browser.safebrowsing.phishing.enabled", false);
/* 0411: disable SB checks for downloads (both local lookups + remote)
* This is the master switch for the safebrowsing.downloads* prefs (0412, 0413)
* [SETTING] Privacy & Security>Security>... "Block dangerous downloads" ***/
// user_pref("browser.safebrowsing.downloads.enabled", false);
/* 0412: disable SB checks for downloads (remote)
* To verify the safety of certain executable files, Firefox may submit some information about the
* file, including the name, origin, size and a cryptographic hash of the contents, to the Google
* Safe Browsing service which helps Firefox determine whether or not the file should be blocked
* [SETUP-SECURITY] If you do not understand this, or you want this protection, then override it ***/
user_pref("browser.safebrowsing.downloads.remote.enabled", false);
user_pref("browser.safebrowsing.downloads.remote.url", "");
/* 0413: disable SB checks for unwanted software
* [SETTING] Privacy & Security>Security>... "Warn you about unwanted and uncommon software" ***/
// user_pref("browser.safebrowsing.downloads.remote.block_potentially_unwanted", false);
// user_pref("browser.safebrowsing.downloads.remote.block_uncommon", false);
/* 0419: disable 'ignore this warning' on SB warnings [FF45+]
* If clicked, it bypasses the block for that session. This is a means for admins to enforce SB
* [TEST] see github wiki APPENDIX A: Test Sites: Section 5
* [1] https://bugzilla.mozilla.org/1226490 ***/
// user_pref("browser.safebrowsing.allowOverride", false);
/*** [SECTION 0500]: SYSTEM ADD-ONS / EXPERIMENTS
System Add-ons are a method for shipping extensions, considered to be
built-in features to Firefox, that are hidden from the about:addons UI.
To view your System Add-ons go to about:support, they are listed under "Firefox Features"
Some System Add-ons have no on-off prefs. Instead you can manually remove them. Note that app
updates will restore them. They may also be updated and possibly restored automatically (see 0505)
* Portable: "...\App\Firefox64\browser\features\" (or "App\Firefox\etc" for 32bit)
* Windows: "...\Program Files\Mozilla\browser\features" (or "Program Files (X86)\etc" for 32bit)
* Mac: "...\Applications\Firefox\Contents\Resources\browser\features\"
[NOTE] On Mac you can right-click on the application and select "Show Package Contents"
* Linux: "/usr/lib/firefox/browser/features" (or similar)
[1] https://firefox-source-docs.mozilla.org/toolkit/mozapps/extensions/addon-manager/SystemAddons.html
[2] https://dxr.mozilla.org/mozilla-central/source/browser/extensions
***/
user_pref("_user.js.parrot", "0500 syntax error: the parrot's cashed in 'is chips!");
/* 0503: disable Normandy/Shield [FF60+]
* Shield is an telemetry system (including Heartbeat) that can also push and test "recipes"
* [1] https://wiki.mozilla.org/Firefox/Shield
* [2] https://github.com/mozilla/normandy ***/
user_pref("app.normandy.enabled", false);
user_pref("app.normandy.api_url", "");
/* 0505: disable System Add-on updates ***/
user_pref("extensions.systemAddon.update.enabled", false); // [FF62+]
user_pref("extensions.systemAddon.update.url", ""); // [FF44+]
/* 0506: disable PingCentre telemetry (used in several System Add-ons) [FF57+]
* Currently blocked by 'datareporting.healthreport.uploadEnabled' (see 0340) ***/
user_pref("browser.ping-centre.telemetry", false);
/* 0515: disable Screenshots ***/
// user_pref("extensions.screenshots.disabled", true); // [FF55+]
/* 0517: disable Form Autofill
* [NOTE] Stored data is NOT secure (uses a JSON file)
* [NOTE] Heuristics controls Form Autofill on forms without @autocomplete attributes
* [SETTING] Privacy & Security>Forms and Autofill>Autofill addresses
* [1] https://wiki.mozilla.org/Firefox/Features/Form_Autofill ***/
user_pref("extensions.formautofill.addresses.enabled", false); // [FF55+]
user_pref("extensions.formautofill.available", "off"); // [FF56+]
user_pref("extensions.formautofill.creditCards.available", false); // [FF57+]
user_pref("extensions.formautofill.creditCards.enabled", false); // [FF56+]
user_pref("extensions.formautofill.heuristics.enabled", false); // [FF55+]
/* 0518: enforce disabling of Web Compatibility Reporter [FF56+]
* Web Compatibility Reporter adds a "Report Site Issue" button to send data to Mozilla ***/
user_pref("extensions.webcompat-reporter.enabled", false); // [DEFAULT: false]
/*** [SECTION 0600]: BLOCK IMPLICIT OUTBOUND [not explicitly asked for - e.g. clicked on] ***/
user_pref("_user.js.parrot", "0600 syntax error: the parrot's no more!");
/* 0601: disable link prefetching
* [1] https://developer.mozilla.org/docs/Web/HTTP/Link_prefetching_FAQ ***/
user_pref("network.prefetch-next", false);
/* 0602: disable DNS prefetching
* [1] https://developer.mozilla.org/docs/Web/HTTP/Headers/X-DNS-Prefetch-Control ***/
user_pref("network.dns.disablePrefetch", true);
user_pref("network.dns.disablePrefetchFromHTTPS", true); // [DEFAULT: true]
/* 0603: disable predictor / prefetching ***/
user_pref("network.predictor.enabled", false);
user_pref("network.predictor.enable-prefetch", false); // [FF48+] [DEFAULT: false]
/* 0605: disable link-mouseover opening connection to linked server
* [1] https://news.slashdot.org/story/15/08/14/2321202/how-to-quash-firefoxs-silent-requests ***/
user_pref("network.http.speculative-parallel-limit", 0);
/* 0606: enforce no "Hyperlink Auditing" (click tracking)
* [1] https://www.bleepingcomputer.com/news/software/major-browsers-to-prevent-disabling-of-click-tracking-privacy-risk/ ***/
user_pref("browser.send_pings", false); // [DEFAULT: false]
user_pref("browser.send_pings.require_same_host", true); // defense-in-depth
/*** [SECTION 0700]: HTTP* / TCP/IP / DNS / PROXY / SOCKS etc ***/
user_pref("_user.js.parrot", "0700 syntax error: the parrot's given up the ghost!");
/* 0701: disable IPv6
* IPv6 can be abused, especially with MAC addresses, and can leak with VPNs. That's even
* assuming your ISP and/or router and/or website can handle it. Sites will fall back to IPv4
* [STATS] Firefox telemetry (Dec 2020) shows ~8% of all connections are IPv6
* [NOTE] This is just an application level fallback. Disabling IPv6 is best done at an
* OS/network level, and/or configured properly in VPN setups. If you are not masking your IP,
* then this won't make much difference. If you are masking your IP, then it can only help.
* [NOTE] PHP defaults to IPv6 with "localhost". Use "php -S 127.0.0.1:PORT"
* [TEST] https://ipleak.org/
* [1] https://www.internetsociety.org/tag/ipv6-security/ (see Myths 2,4,5,6) ***/
user_pref("network.dns.disableIPv6", true);
/* 0702: disable HTTP2
* HTTP2 raises concerns with "multiplexing" and "server push", does nothing to
* enhance privacy, and opens up a number of server-side fingerprinting opportunities.
* [WARNING] Disabling this made sense in the past, and doesn't break anything, but HTTP2 is
* at 40% (December 2019) and growing [5]. Don't be that one person using HTTP1.1 on HTTP2 sites
* [1] https://http2.github.io/faq/
* [2] https://blog.scottlogic.com/2014/11/07/http-2-a-quick-look.html
* [3] https://http2.github.io/http2-spec/#rfc.section.10.8
* [4] https://queue.acm.org/detail.cfm?id=2716278
* [5] https://w3techs.com/technologies/details/ce-http2/all/all ***/
// user_pref("network.http.spdy.enabled", false);
// user_pref("network.http.spdy.enabled.deps", false);
// user_pref("network.http.spdy.enabled.http2", false);
// user_pref("network.http.spdy.websockets", false); // [FF65+]
/* 0703: disable HTTP Alternative Services [FF37+]
* [SETUP-PERF] Relax this if you have FPI enabled (see 4000) *AND* you understand the
* consequences. FPI isolates these, but it was designed with the Tor protocol in mind,
* and the Tor Browser has extra protection, including enhanced sanitizing per Identity.
* [1] https://tools.ietf.org/html/rfc7838#section-9
* [2] https://www.mnot.net/blog/2016/03/09/alt-svc ***/
user_pref("network.http.altsvc.enabled", false);
user_pref("network.http.altsvc.oe", false);
/* 0704: enforce the proxy server to do any DNS lookups when using SOCKS
* e.g. in Tor, this stops your local DNS server from knowing your Tor destination
* as a remote Tor node will handle the DNS request
* [1] https://trac.torproject.org/projects/tor/wiki/doc/TorifyHOWTO/WebBrowsers ***/
user_pref("network.proxy.socks_remote_dns", true);
/* 0708: disable FTP [FF60+] ***/
// user_pref("network.ftp.enabled", false); // [DEFAULT: false FF88+]
/* 0709: disable using UNC (Uniform Naming Convention) paths [FF61+]
* [SETUP-CHROME] Can break extensions for profiles on network shares
* [1] https://gitlab.torproject.org/tpo/applications/tor-browser/-/issues/26424 ***/
user_pref("network.file.disable_unc_paths", true); // [HIDDEN PREF]
/* 0710: disable GIO as a potential proxy bypass vector
* Gvfs/GIO has a set of supported protocols like obex, network, archive, computer, dav, cdda,
* gphoto2, trash, etc. By default only smb and sftp protocols are accepted so far (as of FF64)
* [1] https://bugzilla.mozilla.org/1433507
* [2] https://gitlab.torproject.org/tpo/applications/tor-browser/-/issues/23044
* [3] https://en.wikipedia.org/wiki/GVfs
* [4] https://en.wikipedia.org/wiki/GIO_(software) ***/
user_pref("network.gio.supported-protocols", ""); // [HIDDEN PREF]
/*** [SECTION 0800]: LOCATION BAR / SEARCH BAR / SUGGESTIONS / HISTORY / FORMS
Change items 0850 and above to suit for privacy vs convenience and functionality. Consider
your environment (no unwanted eyeballs), your device (restricted access), your device's
unattended state (locked, encrypted, forensic hardened). Likewise, you may want to check
the items cleared on shutdown in section 2800.
[NOTE] The urlbar is also commonly referred to as the location bar and address bar
#Required reading [#] https://xkcd.com/538/
***/
user_pref("_user.js.parrot", "0800 syntax error: the parrot's ceased to be!");
/* 0801: disable location bar using search
* Don't leak URL typos to a search engine, give an error message instead.
* Examples: "secretplace,com", "secretplace/com", "secretplace com", "secret place.com"
* [NOTE] This does **not** affect explicit user action such as using search buttons in the
* dropdown, or using keyword search shortcuts you configure in options (e.g. 'd' for DuckDuckGo)
* [SETUP-CHROME] If you don't, or rarely, type URLs, or you use a default search
* engine that respects privacy, then you probably don't need this ***/
user_pref("keyword.enabled", false);
/* 0802: disable location bar domain guessing
* domain guessing intercepts DNS "hostname not found errors" and resends a
* request (e.g. by adding www or .com). This is inconsistent use (e.g. FQDNs), does not work
* via Proxy Servers (different error), is a flawed use of DNS (TLDs: why treat .com
* as the 411 for DNS errors?), privacy issues (why connect to sites you didn't
* intend to), can leak sensitive data (e.g. query strings: e.g. Princeton attack),
* and is a security risk (e.g. common typos & malicious sites set up to exploit this) ***/
user_pref("browser.fixup.alternate.enabled", false);
/* 0803: display all parts of the url in the location bar ***/
user_pref("browser.urlbar.trimURLs", false);
/* 0805: disable coloring of visited links - CSS history leak
* [SETUP-HARDEN] Bulk rapid history sniffing was mitigated in 2010 [1][2]. Slower and more expensive
* redraw timing attacks were largely mitigated in FF77+ [3]. Using RFP (4501) further hampers timing
* attacks. Don't forget clearing history on close (2803). However, social engineering [2#limits][4][5]
* and advanced targeted timing attacks could still produce usable results
* [1] https://developer.mozilla.org/docs/Web/CSS/Privacy_and_the_:visited_selector
* [2] https://dbaron.org/mozilla/visited-privacy
* [3] https://bugzilla.mozilla.org/1632765
* [4] https://earthlng.github.io/testpages/visited_links.html (see github wiki APPENDIX A on how to use)
* [5] https://lcamtuf.blogspot.com/2016/08/css-mix-blend-mode-is-bad-for-keeping.html ***/
// user_pref("layout.css.visited_links_enabled", false);
/* 0807: disable live search suggestions
/* [NOTE] Both must be true for the location bar to work
* [SETUP-CHROME] Change these if you trust and use a privacy respecting search engine
* [SETTING] Search>Provide search suggestions | Show search suggestions in address bar results ***/
user_pref("browser.search.suggest.enabled", false);
user_pref("browser.urlbar.suggest.searches", false);
/* 0810: disable location bar making speculative connections [FF56+]
* [1] https://bugzilla.mozilla.org/1348275 ***/
user_pref("browser.urlbar.speculativeConnect.enabled", false);
/* 0811: disable location bar leaking single words to a DNS provider **after searching** [FF78+]
* 0=never resolve single words, 1=heuristic (default), 2=always resolve
* [NOTE] For FF78 value 1 and 2 are the same and always resolve but that will change in future versions
* [1] https://bugzilla.mozilla.org/1642623 ***/
user_pref("browser.urlbar.dnsResolveSingleWordsAfterSearch", 0);
/* 0850a: disable location bar suggestion types
* [SETTING] Privacy & Security>Address Bar>When using the address bar, suggest ***/
// user_pref("browser.urlbar.suggest.history", false);
// user_pref("browser.urlbar.suggest.bookmark", false);
// user_pref("browser.urlbar.suggest.openpage", false);
// user_pref("browser.urlbar.suggest.topsites", false); // [FF78+]
/* 0850b: disable tab-to-search [FF85+]
* Alternatively, you can exclude on a per-engine basis by unchecking them in Options>Search
* [SETTING] Privacy & Security>Address Bar>When using the address bar, suggest>Search engines ***/
// user_pref("browser.urlbar.suggest.engines", false);
/* 0850c: disable location bar dropdown
* This value controls the total number of entries to appear in the location bar dropdown ***/
// user_pref("browser.urlbar.maxRichResults", 0);
/* 0850d: disable location bar autofill
* [1] https://support.mozilla.org/en-US/kb/address-bar-autocomplete-firefox#w_url-autocomplete ***/
// user_pref("browser.urlbar.autoFill", false);
/* 0860: disable search and form history
* [SETUP-WEB] Be aware that autocomplete form data can be read by third parties [1][2]
* [NOTE] We also clear formdata on exit (see 2803)
* [SETTING] Privacy & Security>History>Custom Settings>Remember search and form history
* [1] https://blog.mindedsecurity.com/2011/10/autocompleteagain.html
* [2] https://bugzilla.mozilla.org/381681 ***/
user_pref("browser.formfill.enable", false);
/* 0862: disable browsing and download history
* [NOTE] We also clear history and downloads on exiting Firefox (see 2803)
* [SETTING] Privacy & Security>History>Custom Settings>Remember browsing and download history ***/
// user_pref("places.history.enabled", false);
/* 0870: disable Windows jumplist [WINDOWS] ***/
user_pref("browser.taskbar.lists.enabled", false);
user_pref("browser.taskbar.lists.frequent.enabled", false);
user_pref("browser.taskbar.lists.recent.enabled", false);
user_pref("browser.taskbar.lists.tasks.enabled", false);
/* 0871: disable Windows taskbar preview [WINDOWS] ***/
// user_pref("browser.taskbar.previews.enable", false); // [DEFAULT: false]
/*** [SECTION 0900]: PASSWORDS ***/
user_pref("_user.js.parrot", "0900 syntax error: the parrot's expired!");
/* 0901: disable saving passwords
* [NOTE] This does not clear any passwords already saved
* [SETTING] Privacy & Security>Logins and Passwords>Ask to save logins and passwords for websites ***/
// user_pref("signon.rememberSignons", false);
/* 0902: use a primary password
* There are no preferences for this. It is all handled internally.
* [SETTING] Privacy & Security>Logins and Passwords>Use a Primary Password
* [1] https://support.mozilla.org/kb/use-primary-password-protect-stored-logins-and-pas ***/
/* 0903: set how often Firefox should ask for the primary password
* 0=the first time (default), 1=every time it's needed, 2=every n minutes (see 0904) ***/
user_pref("security.ask_for_password", 2);
/* 0904: set how often in minutes Firefox should ask for the primary password (see 0903)
* in minutes, default is 30 ***/
user_pref("security.password_lifetime", 5);
/* 0905: disable auto-filling username & password form fields
* can leak in cross-site forms *and* be spoofed
* [NOTE] Username & password is still available when you enter the field
* [SETTING] Privacy & Security>Logins and Passwords>Autofill logins and passwords
* [1] https://freedom-to-tinker.com/2017/12/27/no-boundaries-for-user-identities-web-trackers-exploit-browser-login-managers/ ***/
user_pref("signon.autofillForms", false);
/* 0909: disable formless login capture for Password Manager [FF51+] ***/
user_pref("signon.formlessCapture.enabled", false);
/* 0912: limit (or disable) HTTP authentication credentials dialogs triggered by sub-resources [FF41+]
* hardens against potential credentials phishing
* 0=don't allow sub-resources to open HTTP authentication credentials dialogs
* 1=don't allow cross-origin sub-resources to open HTTP authentication credentials dialogs
* 2=allow sub-resources to open HTTP authentication credentials dialogs (default) ***/
user_pref("network.auth.subresource-http-auth-allow", 1);
/*** [SECTION 1000]: CACHE / SESSION (RE)STORE / FAVICONS
Cache tracking/fingerprinting techniques [1][2][3] require a cache. Disabling disk (1001)
*and* memory (1003) caches is one solution; but that's extreme and fingerprintable. A hardened
Temporary Containers configuration can effectively do the same thing, by isolating every tab [4].
We consider avoiding disk cache (1001) so cache is session/memory only (like Private Browsing
mode), and isolating cache to first party (4001) is sufficient and a good balance between
risk and performance. ETAGs can also be neutralized by modifying response headers [5], and
you can clear the cache manually or on a regular basis with an extension.
[1] https://en.wikipedia.org/wiki/HTTP_ETag#Tracking_using_ETags
[2] https://robertheaton.com/2014/01/20/cookieless-user-tracking-for-douchebags/
[3] https://www.grepular.com/Preventing_Web_Tracking_via_the_Browser_Cache
[4] https://medium.com/@stoically/enhance-your-privacy-in-firefox-with-temporary-containers-33925cd6cd21
[5] https://github.com/arkenfox/user.js/wiki/4.2.4-Header-Editor
***/
user_pref("_user.js.parrot", "1000 syntax error: the parrot's gone to meet 'is maker!");
/** CACHE ***/
/* 1001: disable disk cache
* [SETUP-PERF] If you think disk cache may help (heavy tab user, high-res video),
* or you use a hardened Temporary Containers, then feel free to override this
* [NOTE] We also clear cache on exiting Firefox (see 2803) ***/
user_pref("browser.cache.disk.enable", false);
/* 1003: disable memory cache
* capacity: -1=determine dynamically (default), 0=none, n=memory capacity in kibibytes ***/
// user_pref("browser.cache.memory.enable", false);
// user_pref("browser.cache.memory.capacity", 0);
/* 1006: disable permissions manager from writing to disk [RESTART]
* [NOTE] This means any permission changes are session only
* [1] https://bugzilla.mozilla.org/967812 ***/
// user_pref("permissions.memory_only", true); // [HIDDEN PREF]
/* 1007: disable media cache from writing to disk in Private Browsing
* [NOTE] MSE (Media Source Extensions) are already stored in-memory in PB
* [SETUP-WEB] ESR78: playback might break on subsequent loading (1650281) ***/
user_pref("browser.privatebrowsing.forceMediaMemoryCache", true); // [FF75+]
user_pref("media.memory_cache_max_size", 65536);
/** SESSIONS & SESSION RESTORE ***/
/* 1020: exclude "Undo Closed Tabs" in Session Restore ***/
// user_pref("browser.sessionstore.max_tabs_undo", 0);
/* 1021: disable storing extra session data [SETUP-CHROME]
* extra session data contains contents of forms, scrollbar positions, cookies and POST data
* define on which sites to save extra session data:
* 0=everywhere, 1=unencrypted sites, 2=nowhere ***/
user_pref("browser.sessionstore.privacy_level", 2);
/* 1022: disable resuming session from crash ***/
// user_pref("browser.sessionstore.resume_from_crash", false);
/* 1023: set the minimum interval between session save operations
* Increasing this can help on older machines and some websites, as well as reducing writes [1]
* Default is 15000 (15 secs). Try 30000 (30 secs), 60000 (1 min) etc
* [SETUP-CHROME] This can also affect entries in the "Recently Closed Tabs" feature:
* i.e. the longer the interval the more chance a quick tab open/close won't be captured.
* This longer interval *may* affect history but we cannot replicate any history not recorded
* [1] https://bugzilla.mozilla.org/1304389 ***/
user_pref("browser.sessionstore.interval", 30000);
/* 1024: disable automatic Firefox start and session restore after reboot [FF62+] [WINDOWS]
* [1] https://bugzilla.mozilla.org/603903 ***/
user_pref("toolkit.winRegisterApplicationRestart", false);
/** FAVICONS ***/
/* 1030: disable favicons in shortcuts
* URL shortcuts use a cached randomly named .ico file which is stored in your
* profile/shortcutCache directory. The .ico remains after the shortcut is deleted.
* If set to false then the shortcuts use a generic Firefox icon ***/
user_pref("browser.shell.shortcutFavicons", false);
/* 1031: disable favicons in history and bookmarks
* Stored as data blobs in favicons.sqlite, these don't reveal anything that your
* actual history (and bookmarks) already do. Your history is more detailed, so
* control that instead; e.g. disable history, clear history on close, use PB mode
* [NOTE] favicons.sqlite is sanitized on Firefox close, not in-session ***/
// user_pref("browser.chrome.site_icons", false);
/* 1032: disable favicons in web notifications ***/
// user_pref("alerts.showFavicons", false); // [DEFAULT: false]
/*** [SECTION 1200]: HTTPS (SSL/TLS / OCSP / CERTS / HPKP / CIPHERS)
Your cipher and other settings can be used in server side fingerprinting
[TEST] https://www.ssllabs.com/ssltest/viewMyClient.html
[TEST] https://browserleaks.com/ssl
[TEST] https://ja3er.com/
[1] https://www.securityartwork.es/2017/02/02/tls-client-fingerprinting-with-bro/
***/
user_pref("_user.js.parrot", "1200 syntax error: the parrot's a stiff!");
/** SSL (Secure Sockets Layer) / TLS (Transport Layer Security) ***/
/* 1201: require safe negotiation
* Blocks connections (SSL_ERROR_UNSAFE_NEGOTIATION) to servers that don't support RFC 5746 [2]
* as they're potentially vulnerable to a MiTM attack [3]. A server without RFC 5746 can be
* safe from the attack if it disables renegotiations but the problem is that the browser can't
* know that. Setting this pref to true is the only way for the browser to ensure there will be
* no unsafe renegotiations on the channel between the browser and the server.
* [STATS] SSL Labs (Dec 2020) reports 99.0% of sites have secure renegotiation [4]
* [1] https://wiki.mozilla.org/Security:Renegotiation
* [2] https://tools.ietf.org/html/rfc5746
* [3] https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2009-3555
* [4] https://www.ssllabs.com/ssl-pulse/ ***/
user_pref("security.ssl.require_safe_negotiation", true);
/* 1202: control TLS versions with min and max
* 1=TLS 1.0, 2=TLS 1.1, 3=TLS 1.2, 4=TLS 1.3
* [WARNING] Leave these at default, otherwise you alter your TLS fingerprint.
* [1] https://www.ssllabs.com/ssl-pulse/ ***/
// user_pref("security.tls.version.min", 3); // [DEFAULT: 3]
// user_pref("security.tls.version.max", 4);
/* 1203: enforce TLS 1.0 and 1.1 downgrades as session only ***/
user_pref("security.tls.version.enable-deprecated", false);
/* 1204: disable SSL session tracking [FF36+]
* SSL Session IDs are unique and last up to 24hrs in Firefox (or longer with prolongation attacks)
* [NOTE] These are not used in PB mode. In normal windows they are isolated when using FPI (4001)
* and/or containers. In FF85+ they are isolated by default (privacy.partition.network_state)
* [WARNING] There are perf and passive fingerprinting costs, for little to no gain. Preventing
* tracking via this method does not address IPs, nor handle any sanitizing of current identifiers
* [1] https://tools.ietf.org/html/rfc5077
* [2] https://bugzilla.mozilla.org/967977
* [3] https://arxiv.org/abs/1810.07304 ***/
// user_pref("security.ssl.disable_session_identifiers", true); // [HIDDEN PREF]
/* 1206: disable TLS1.3 0-RTT (round-trip time) [FF51+]
* [1] https://github.com/tlswg/tls13-spec/issues/1001
* [2] https://blog.cloudflare.com/tls-1-3-overview-and-q-and-a/ ***/
user_pref("security.tls.enable_0rtt_data", false);
/** OCSP (Online Certificate Status Protocol)
#Required reading [#] https://scotthelme.co.uk/revocation-is-broken/ ***/
/* 1210: enable OCSP Stapling
* [1] https://blog.mozilla.org/security/2013/07/29/ocsp-stapling-in-firefox/ ***/
user_pref("security.ssl.enable_ocsp_stapling", true);
/* 1211: control when to use OCSP fetching (to confirm current validity of certificates)
* 0=disabled, 1=enabled (default), 2=enabled for EV certificates only
* OCSP (non-stapled) leaks information about the sites you visit to the CA (cert authority)
* It's a trade-off between security (checking) and privacy (leaking info to the CA)
* [NOTE] This pref only controls OCSP fetching and does not affect OCSP stapling
* [1] https://en.wikipedia.org/wiki/Ocsp ***/
user_pref("security.OCSP.enabled", 1);
/* 1212: set OCSP fetch failures (non-stapled, see 1211) to hard-fail [SETUP-WEB]
* When a CA cannot be reached to validate a cert, Firefox just continues the connection (=soft-fail)
* Setting this pref to true tells Firefox to instead terminate the connection (=hard-fail)
* It is pointless to soft-fail when an OCSP fetch fails: you cannot confirm a cert is still valid (it
* could have been revoked) and/or you could be under attack (e.g. malicious blocking of OCSP servers)
* [1] https://blog.mozilla.org/security/2013/07/29/ocsp-stapling-in-firefox/
* [2] https://www.imperialviolet.org/2014/04/19/revchecking.html ***/
user_pref("security.OCSP.require", true);
/** CERTS / HPKP (HTTP Public Key Pinning) ***/
/* 1220: disable or limit SHA-1 certificates
* 0=all SHA1 certs are allowed
* 1=all SHA1 certs are blocked
* 2=deprecated option that now maps to 1
* 3=only allowed for locally-added roots (e.g. anti-virus)
* 4=only allowed for locally-added roots or for certs in 2015 and earlier
* [SETUP-CHROME] When disabled, some man-in-the-middle devices (e.g. security scanners and
* antivirus products, may fail to connect to HTTPS sites. SHA-1 is *almost* obsolete.
* [1] https://blog.mozilla.org/security/2016/10/18/phasing-out-sha-1-on-the-public-web/ ***/
user_pref("security.pki.sha1_enforcement_level", 1);
/* 1221: disable Windows 8.1's Microsoft Family Safety cert [FF50+] [WINDOWS]
* 0=disable detecting Family Safety mode and importing the root
* 1=only attempt to detect Family Safety mode (don't import the root)
* 2=detect Family Safety mode and import the root
* [1] https://gitlab.torproject.org/tpo/applications/tor-browser/-/issues/21686 ***/
user_pref("security.family_safety.mode", 0);
/* 1222: disable intermediate certificate caching (fingerprinting attack vector) [FF41+] [RESTART]
* [NOTE] This affects login/cert/key dbs. The effect is all credentials are session-only.
* Saved logins and passwords are not available. Reset the pref and restart to return them.
* [1] https://shiftordie.de/blog/2017/02/21/fingerprinting-firefox-users-with-cached-intermediate-ca-certificates-fiprinca/ ***/
// user_pref("security.nocertdb", true); // [HIDDEN PREF]
/* 1223: enforce strict pinning
* PKP (Public Key Pinning) 0=disabled 1=allow user MiTM (such as your antivirus), 2=strict
* [SETUP-WEB] If you rely on an AV (antivirus) to protect your web browsing
* by inspecting ALL your web traffic, then leave at current default=1
* [1] https://gitlab.torproject.org/tpo/applications/tor-browser/-/issues/16206 ***/
user_pref("security.cert_pinning.enforcement_level", 2);
/* 1224: enforce CRLite [FF73+]
* In FF84+ it covers valid certs and in mode 2 doesn't fall back to OCSP
* [1] https://bugzilla.mozilla.org/buglist.cgi?bug_id=1429800,1670985
* [2] https://blog.mozilla.org/security/tag/crlite/ ***/
user_pref("security.remote_settings.crlite_filters.enabled", true);
user_pref("security.pki.crlite_mode", 2);
/** MIXED CONTENT ***/
/* 1240: enforce no insecure active content on https pages
* [1] https://gitlab.torproject.org/tpo/applications/tor-browser/-/issues/21323 ***/
user_pref("security.mixed_content.block_active_content", true); // [DEFAULT: true]
/* 1241: disable insecure passive content (such as images) on https pages [SETUP-WEB] ***/
user_pref("security.mixed_content.block_display_content", true);
/* 1243: block unencrypted requests from Flash on encrypted pages to mitigate MitM attacks [FF59+]
* [1] https://bugzilla.mozilla.org/1190623 ***/
user_pref("security.mixed_content.block_object_subrequest", true);
/* 1244: enable HTTPS-Only mode [FF76+]
* When "https_only_mode" (all windows) is true, "https_only_mode_pbm" (private windows only) is ignored
* [SETTING] to add site exceptions: Padlock>HTTPS-Only mode>On/Off/Off temporarily
* [SETTING] Privacy & Security>HTTPS-Only Mode
* [TEST] http://example.com [upgrade]
* [TEST] http://neverssl.org/ [no upgrade]
* [1] https://bugzilla.mozilla.org/1613063 [META] ***/
user_pref("dom.security.https_only_mode", true); // [FF76+]
// user_pref("dom.security.https_only_mode_pbm", true); // [FF80+]
/* 1245: enable HTTPS-Only mode for local resources [FF77+] ***/
// user_pref("dom.security.https_only_mode.upgrade_local", true);
/* 1246: disable HTTP background requests [FF82+]
* When attempting to upgrade, if the server doesn't respond within 3 seconds, firefox
* sends HTTP requests in order to check if the server supports HTTPS or not.
* This is done to avoid waiting for a timeout which takes 90 seconds
* [1] https://bugzilla.mozilla.org/buglist.cgi?bug_id=1642387,1660945 ***/
user_pref("dom.security.https_only_mode_send_http_background_request", false);
/** CIPHERS [WARNING: do not meddle with your cipher suite: see the section 1200 intro]
* These are all the ciphers still using SHA-1 and CBC which are weaker than the available alternatives. (see "Cipher Suites" in [1])
* Additionally some have other weaknesses like key sizes of 128 (or lower) [2] and/or no Perfect Forward Secrecy [3].
* [1] https://browserleaks.com/ssl
* [2] https://en.wikipedia.org/wiki/Key_size
* [3] https://en.wikipedia.org/wiki/Forward_secrecy
***/
/* 1261: disable 3DES (effective key size < 128 and no PFS)
* [1] https://en.wikipedia.org/wiki/3des#Security
* [2] https://en.wikipedia.org/wiki/Meet-in-the-middle_attack
* [3] https://www-archive.mozilla.org/projects/security/pki/nss/ssl/fips-ssl-ciphersuites.html ***/
// user_pref("security.ssl3.rsa_des_ede3_sha", false);
/* 1264: disable the remaining non-modern cipher suites as of FF78 (in order of preferred by FF) ***/
// user_pref("security.ssl3.ecdhe_ecdsa_aes_256_sha", false);
// user_pref("security.ssl3.ecdhe_ecdsa_aes_128_sha", false);
// user_pref("security.ssl3.ecdhe_rsa_aes_128_sha", false);
// user_pref("security.ssl3.ecdhe_rsa_aes_256_sha", false);
// user_pref("security.ssl3.rsa_aes_128_sha", false); // no PFS
// user_pref("security.ssl3.rsa_aes_256_sha", false); // no PFS
/** UI (User Interface) ***/
/* 1270: display warning on the padlock for "broken security" (if 1201 is false)
* Bug: warning padlock not indicated for subresources on a secure page! [2]
* [1] https://wiki.mozilla.org/Security:Renegotiation
* [2] https://bugzilla.mozilla.org/1353705 ***/
user_pref("security.ssl.treat_unsafe_negotiation_as_broken", true);
/* 1271: control "Add Security Exception" dialog on SSL warnings
* 0=do neither 1=pre-populate url 2=pre-populate url + pre-fetch cert (default)
* [1] https://github.com/pyllyukko/user.js/issues/210 ***/
user_pref("browser.ssl_override_behavior", 1);
/* 1272: display advanced information on Insecure Connection warning pages
* only works when it's possible to add an exception
* i.e. it doesn't work for HSTS discrepancies (https://subdomain.preloaded-hsts.badssl.com/)
* [TEST] https://expired.badssl.com/ ***/
user_pref("browser.xul.error_pages.expert_bad_cert", true);
/* 1273: display "insecure" icon and "Not Secure" text on HTTP sites ***/
// user_pref("security.insecure_connection_icon.enabled", true); // [FF59+] [DEFAULT: true]
user_pref("security.insecure_connection_text.enabled", true); // [FF60+]
/*** [SECTION 1400]: FONTS ***/
user_pref("_user.js.parrot", "1400 syntax error: the parrot's bereft of life!");
/* 1401: disable websites choosing fonts (0=block, 1=allow)
* This can limit most (but not all) JS font enumeration which is a high entropy fingerprinting vector
* [WARNING] **DO NOT USE**: in FF80+ RFP covers this, and non-RFP users should use font vis (4618)
* [SETTING] General>Language and Appearance>Fonts & Colors>Advanced>Allow pages to choose... ***/
// user_pref("browser.display.use_document_fonts", 0);
/* 1403: disable icon fonts (glyphs) and local fallback rendering
* [1] https://bugzilla.mozilla.org/789788
* [2] https://gitlab.torproject.org/legacy/trac/-/issues/8455 ***/
// user_pref("gfx.downloadable_fonts.enabled", false); // [FF41+]
// user_pref("gfx.downloadable_fonts.fallback_delay", -1);
/* 1404: disable rendering of SVG OpenType fonts
* [1] https://wiki.mozilla.org/SVGOpenTypeFonts - iSECPartnersReport recommends to disable this ***/
user_pref("gfx.font_rendering.opentype_svg.enabled", false);
/* 1408: disable graphite
* Graphite has had many critical security issues in the past [1]
* [1] https://www.mozilla.org/security/advisories/mfsa2017-15/#CVE-2017-7778
* [2] https://en.wikipedia.org/wiki/Graphite_(SIL) ***/
user_pref("gfx.font_rendering.graphite.enabled", false);
/* 1409: limit system font exposure to a whitelist [FF52+] [RESTART]
* If the whitelist is empty, then whitelisting is considered disabled and all fonts are allowed
* [NOTE] In FF81+ the whitelist **overrides** RFP's font visibility (see 4618)
* [WARNING] **DO NOT USE**: in FF80+ RFP covers this, and non-RFP users should use font vis (4618)
* [1] https://bugzilla.mozilla.org/1121643 ***/
// user_pref("font.system.whitelist", ""); // [HIDDEN PREF]
/*** [SECTION 1600]: HEADERS / REFERERS
Only *cross domain* referers need controlling: leave 1601, 1602, 1605 and 1606 alone
---
Expect some breakage: Use an extension if you need precise control
---
full URI: https://example.com:8888/foo/bar.html?id=1234
scheme+host+port+path: https://example.com:8888/foo/bar.html
scheme+host+port: https://example.com:8888
---
#Required reading [#] https://feeding.cloud.geek.nz/posts/tweaking-referrer-for-privacy-in-firefox/
***/
user_pref("_user.js.parrot", "1600 syntax error: the parrot rests in peace!");
/* 1601: ALL: control when images/links send a referer
* 0=never, 1=send only when links are clicked, 2=for links and images (default) ***/
// user_pref("network.http.sendRefererHeader", 2);
/* 1602: ALL: control the amount of information to send
* 0=send full URI (default), 1=scheme+host+port+path, 2=scheme+host+port ***/
// user_pref("network.http.referer.trimmingPolicy", 0);
/* 1603: CROSS ORIGIN: control when to send a referer
* 0=always (default), 1=only if base domains match, 2=only if hosts match
* [SETUP-WEB] Known to cause issues with older modems/routers and some sites e.g vimeo, icloud ***/
user_pref("network.http.referer.XOriginPolicy", 2);
/* 1604: CROSS ORIGIN: control the amount of information to send [FF52+]
* 0=send full URI (default), 1=scheme+host+port+path, 2=scheme+host+port ***/
user_pref("network.http.referer.XOriginTrimmingPolicy", 2);
/* 1605: ALL: disable spoofing a referer
* [WARNING] Do not set this to true, as spoofing effectively disables the anti-CSRF
* (Cross-Site Request Forgery) protections that some sites may rely on ***/
// user_pref("network.http.referer.spoofSource", false); // [DEFAULT: false]
/* 1606: ALL: set the default Referrer Policy [FF59+]
* 0=no-referer, 1=same-origin, 2=strict-origin-when-cross-origin, 3=no-referrer-when-downgrade
* [NOTE] This is only a default, it can be overridden by a site-controlled Referrer Policy
* [1] https://www.w3.org/TR/referrer-policy/
* [2] https://developer.mozilla.org/docs/Web/HTTP/Headers/Referrer-Policy
* [3] https://blog.mozilla.org/security/2018/01/31/preventing-data-leaks-by-stripping-path-information-in-http-referrers/
* [4] https://blog.mozilla.org/security/2021/03/22/firefox-87-trims-http-referrers-by-default-to-protect-user-privacy/ ***/
// user_pref("network.http.referer.defaultPolicy", 2); // [DEFAULT: 2 FF87+]
// user_pref("network.http.referer.defaultPolicy.pbmode", 2); // [DEFAULT: 2]
/* 1607: TOR: hide (not spoof) referrer when leaving a .onion domain [FF54+]
* [NOTE] Firefox cannot access .onion sites by default. We recommend you use
* the Tor Browser which is specifically designed for hidden services
* [1] https://bugzilla.mozilla.org/1305144 ***/
user_pref("network.http.referer.hideOnionSource", true);
/* 1610: ALL: enable the DNT (Do Not Track) HTTP header
* [NOTE] DNT is enforced with Enhanced Tracking Protection regardless of this pref
* [SETTING] Privacy & Security>Enhanced Tracking Protection>Send websites a "Do Not Track" signal... ***/
user_pref("privacy.donottrackheader.enabled", true);
/*** [SECTION 1700]: CONTAINERS
If you want to *really* leverage containers, we highly recommend Temporary Containers [2].
Read the article by the extension author [3], and check out the github wiki/repo [4].
[1] https://wiki.mozilla.org/Security/Contextual_Identity_Project/Containers
[2] https://addons.mozilla.org/firefox/addon/temporary-containers/
[3] https://medium.com/@stoically/enhance-your-privacy-in-firefox-with-temporary-containers-33925cd6cd21
[4] https://github.com/stoically/temporary-containers/wiki
***/
user_pref("_user.js.parrot", "1700 syntax error: the parrot's bit the dust!");
/* 1701: enable Container Tabs setting in preferences (see 1702) [FF50+]
* [1] https://bugzilla.mozilla.org/1279029 ***/
user_pref("privacy.userContext.ui.enabled", true);
/* 1702: enable Container Tabs [FF50+]
* [SETTING] General>Tabs>Enable Container Tabs ***/
user_pref("privacy.userContext.enabled", true);
/* 1703: set behaviour on "+ Tab" button to display container menu on left click [FF74+]
* [NOTE] The menu is always shown on long press and right click
* [SETTING] General>Tabs>Enable Container Tabs>Settings>Select a container for each new tab ***/
// user_pref("privacy.userContext.newTabContainerOnLeftClick.enabled", true);
/*** [SECTION 1800]: PLUGINS ***/
user_pref("_user.js.parrot", "1800 syntax error: the parrot's pushing up daisies!");
/* 1803: disable Flash plugin
* 0=deactivated, 1=ask, 2=enabled
* ESR52.x is the last branch to *fully* support NPAPI, FF52+ stable only supports Flash
* [NOTE] You can still override individual sites via site permissions ***/
user_pref("plugin.state.flash", 0);
/* 1820: disable GMP (Gecko Media Plugins)
* [1] https://wiki.mozilla.org/GeckoMediaPlugins ***/
// user_pref("media.gmp-provider.enabled", false);
/* 1825: disable widevine CDM (Content Decryption Module)
* [NOTE] This is covered by the EME master switch (1830) ***/
// user_pref("media.gmp-widevinecdm.enabled", false);
/* 1830: disable all DRM content (EME: Encryption Media Extension)
* [SETUP-WEB] e.g. Netflix, Amazon Prime, Hulu, HBO, Disney+, Showtime, Starz, DirectTV
* [SETTING] General>DRM Content>Play DRM-controlled content
* [1] https://www.eff.org/deeplinks/2017/10/drms-dead-canary-how-we-just-lost-web-what-we-learned-it-and-what-we-need-do-next ***/
user_pref("media.eme.enabled", false);
/*** [SECTION 2000]: MEDIA / CAMERA / MIC ***/
user_pref("_user.js.parrot", "2000 syntax error: the parrot's snuffed it!");
/* 2001: disable WebRTC (Web Real-Time Communication)
* [SETUP-WEB] WebRTC can leak your IP address from behind your VPN, but if this is not
* in your threat model, and you want Real-Time Communication, this is the pref for you
* [1] https://www.privacytools.io/#webrtc ***/
user_pref("media.peerconnection.enabled", false);
/* 2002: limit WebRTC IP leaks if using WebRTC
* In FF70+ these settings match Mode 4 (Mode 3 in older versions) [3]
* [TEST] https://browserleaks.com/webrtc
* [1] https://bugzilla.mozilla.org/buglist.cgi?bug_id=1189041,1297416,1452713
* [2] https://wiki.mozilla.org/Media/WebRTC/Privacy
* [3] https://tools.ietf.org/html/draft-ietf-rtcweb-ip-handling-12#section-5.2 ***/
user_pref("media.peerconnection.ice.default_address_only", true);
user_pref("media.peerconnection.ice.no_host", true); // [FF51+]
user_pref("media.peerconnection.ice.proxy_only_if_behind_proxy", true); // [FF70+]
/* 2010: disable WebGL (Web Graphics Library)
* [SETUP-WEB] When disabled, may break some websites. When enabled, provides high entropy,
* especially with readPixels(). Some of the other entropy is lessened with RFP (see 4501)
* [1] https://www.contextis.com/resources/blog/webgl-new-dimension-browser-exploitation/
* [2] https://security.stackexchange.com/questions/13799/is-webgl-a-security-concern ***/
user_pref("webgl.disabled", true);
user_pref("webgl.enable-webgl2", false);
/* 2012: limit WebGL ***/
// user_pref("webgl.min_capability_mode", true);
user_pref("webgl.disable-fail-if-major-performance-caveat", true); // [DEFAULT: true FF86+]
/* 2022: disable screensharing ***/
user_pref("media.getusermedia.screensharing.enabled", false);
user_pref("media.getusermedia.browser.enabled", false);
user_pref("media.getusermedia.audiocapture.enabled", false);
/* 2024: set a default permission for Camera/Microphone [FF58+]
* 0=always ask (default), 1=allow, 2=block
* [SETTING] to add site exceptions: Ctrl+I>Permissions>Use the Camera/Microphone
* [SETTING] to manage site exceptions: Options>Privacy & Security>Permissions>Camera/Microphone>Settings ***/
// user_pref("permissions.default.camera", 2);
// user_pref("permissions.default.microphone", 2);
/* 2030: disable autoplay of HTML5 media [FF63+]
* 0=Allow all, 1=Block non-muted media (default in FF67+), 2=Prompt (removed in FF66), 5=Block all (FF69+)
* [NOTE] You can set exceptions under site permissions
* [SETTING] Privacy & Security>Permissions>Autoplay>Settings>Default for all websites ***/
// user_pref("media.autoplay.default", 5);
/* 2031: disable autoplay of HTML5 media if you interacted with the site [FF78+]
* 0=sticky (default), 1=transient, 2=user
* Firefox's Autoplay Policy Documentation [PDF] is linked below via SUMO
* [NOTE] If you have trouble with some video sites, then add an exception (see 2030)
* [1] https://support.mozilla.org/questions/1293231 ***/
user_pref("media.autoplay.blocking_policy", 2);
/*** [SECTION 2200]: WINDOW MEDDLING & LEAKS / POPUPS ***/
user_pref("_user.js.parrot", "2200 syntax error: the parrot's 'istory!");
/* 2202: prevent scripts from moving and resizing open windows ***/
user_pref("dom.disable_window_move_resize", true);
/* 2203: open links targeting new windows in a new tab instead
* This stops malicious window sizes and some screen resolution leaks.
* You can still right-click a link and open in a new window.
* [TEST] https://arkenfox.github.io/TZP/tzp.html#screen
* [1] https://gitlab.torproject.org/tpo/applications/tor-browser/-/issues/9881 ***/
user_pref("browser.link.open_newwindow", 3); // 1=most recent window or tab 2=new window, 3=new tab
user_pref("browser.link.open_newwindow.restriction", 0);
/* 2204: disable Fullscreen API (requires user interaction) to prevent screen-resolution leaks
* [NOTE] You can still manually toggle the browser's fullscreen state (F11),
* but this pref will disable embedded video/game fullscreen controls, e.g. youtube
* [TEST] https://arkenfox.github.io/TZP/tzp.html#screen ***/
// user_pref("full-screen-api.enabled", false);
/* 2210: block popup windows
* [SETTING] Privacy & Security>Permissions>Block pop-up windows ***/
user_pref("dom.disable_open_during_load", true);
/* 2212: limit events that can cause a popup [SETUP-WEB]
* default FF86+: "change click dblclick auxclick mousedown mouseup pointerdown pointerup notificationclick reset submit touchend contextmenu ***/
user_pref("dom.popup_allowed_events", "click dblclick mousedown pointerdown");
/*** [SECTION 2300]: WEB WORKERS
A worker is a JS "background task" running in a global context, i.e. it is different from
the current window. Workers can spawn new workers (must be the same origin & scheme),
including service and shared workers. Shared workers can be utilized by multiple scripts and
communicate between browsing contexts (windows/tabs/iframes) and can even control your cache.
[1] Web Workers: https://developer.mozilla.org/docs/Web/API/Web_Workers_API
[2] Worker: https://developer.mozilla.org/docs/Web/API/Worker
[3] Service Worker: https://developer.mozilla.org/docs/Web/API/Service_Worker_API
[4] SharedWorker: https://developer.mozilla.org/docs/Web/API/SharedWorker
[5] ChromeWorker: https://developer.mozilla.org/docs/Web/API/ChromeWorker
[6] Notifications: https://support.mozilla.org/questions/1165867#answer-981820
***/
user_pref("_user.js.parrot", "2300 syntax error: the parrot's off the twig!");
/* 2302: disable service workers [FF32, FF44-compat]
* Service workers essentially act as proxy servers that sit between web apps, and the
* browser and network, are event driven, and can control the web page/site it is associated
* with, intercepting and modifying navigation and resource requests, and caching resources.
* [NOTE] Service worker APIs are hidden (in Firefox) and cannot be used when in PB mode.
* [NOTE] Service workers only run over HTTPS. Service workers have no DOM access.
* [SETUP-WEB] Disabling service workers will break some sites. This pref is required true for
* service worker notifications (2304), push notifications (disabled, 2305) and service worker
* cache (2740). If you enable this pref, then check those settings as well ***/
user_pref("dom.serviceWorkers.enabled", false);
/* 2304: disable Web Notifications
* [NOTE] Web Notifications can also use service workers (2302) and are behind a prompt (2306)
* [1] https://developer.mozilla.org/docs/Web/API/Notifications_API ***/
// user_pref("dom.webnotifications.enabled", false); // [FF22+]
// user_pref("dom.webnotifications.serviceworker.enabled", false); // [FF44+]
/* 2305: disable Push Notifications [FF44+]
* Push is an API that allows websites to send you (subscribed) messages even when the site
* isn't loaded, by pushing messages to your userAgentID through Mozilla's Push Server.
* [NOTE] Push requires service workers (2302) to subscribe to and display, and is behind
* a prompt (2306). Disabling service workers alone doesn't stop Firefox polling the
* Mozilla Push Server. To remove all subscriptions, reset your userAgentID (in about:config
* or on start), and you will get a new one within a few seconds.
* [1] https://support.mozilla.org/en-US/kb/push-notifications-firefox
* [2] https://developer.mozilla.org/en-US/docs/Web/API/Push_API ***/
user_pref("dom.push.enabled", false);
// user_pref("dom.push.userAgentID", "");
/* 2306: set a default permission for Notifications (both 2304 and 2305) [FF58+]
* 0=always ask (default), 1=allow, 2=block
* [NOTE] Best left at default "always ask", fingerprintable via Permissions API
* [SETTING] to add site exceptions: Ctrl+I>Permissions>Receive Notifications
* [SETTING] to manage site exceptions: Options>Privacy & Security>Permissions>Notifications>Settings ***/
// user_pref("permissions.default.desktop-notification", 2);
/*** [SECTION 2400]: DOM (DOCUMENT OBJECT MODEL) & JAVASCRIPT ***/
user_pref("_user.js.parrot", "2400 syntax error: the parrot's kicked the bucket!");
/* 2401: disable website control over browser right-click context menu
* [NOTE] Shift-Right-Click will always bring up the browser right-click context menu ***/
// user_pref("dom.event.contextmenu.enabled", false);
/* 2402: disable website access to clipboard events/content [SETUP-HARDEN]
* [NOTE] This will break some sites' functionality e.g. Outlook, Twitter, Facebook, Wordpress
* This applies to onCut/onCopy/onPaste events - i.e. it requires interaction with the website
* [WARNING] If both 'middlemouse.paste' and 'general.autoScroll' are true (at least one
* is default false) then enabling this pref can leak clipboard content [1]
* [1] https://bugzilla.mozilla.org/1528289 ***/
// user_pref("dom.event.clipboardevents.enabled", false);
/* 2404: disable clipboard commands (cut/copy) from "non-privileged" content [FF41+]
* this disables document.execCommand("cut"/"copy") to protect your clipboard
* [1] https://bugzilla.mozilla.org/1170911 ***/
user_pref("dom.allow_cut_copy", false);
/* 2405: disable "Confirm you want to leave" dialog on page close
* Does not prevent JS leaks of the page close event.
* [1] https://developer.mozilla.org/docs/Web/Events/beforeunload
* [2] https://support.mozilla.org/questions/1043508 ***/
user_pref("dom.disable_beforeunload", true);
/* 2414: disable shaking the screen ***/
user_pref("dom.vibrator.enabled", false);
/* 2420: disable asm.js [FF22+] [SETUP-PERF]
* [1] http://asmjs.org/
* [2] https://www.mozilla.org/security/advisories/mfsa2015-29/
* [3] https://www.mozilla.org/security/advisories/mfsa2015-50/
* [4] https://www.mozilla.org/security/advisories/mfsa2017-01/#CVE-2017-5375
* [5] https://www.mozilla.org/security/advisories/mfsa2017-05/#CVE-2017-5400
* [6] https://rh0dev.github.io/blog/2017/the-return-of-the-jit/ ***/
user_pref("javascript.options.asmjs", false);
/* 2421: disable Ion and baseline JIT to harden against JS exploits [SETUP-HARDEN]
* [NOTE] In FF75+, when **both** Ion and JIT are disabled, **and** the new
* hidden pref is enabled, then Ion can still be used by extensions (1599226)
* [WARNING] Disabling Ion/JIT can cause some site issues and performance loss
* [1] https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2015-0817 ***/
// user_pref("javascript.options.ion", false);
// user_pref("javascript.options.baselinejit", false);
// user_pref("javascript.options.jit_trustedprincipals", true); // [FF75+] [HIDDEN PREF]
/* 2422: disable WebAssembly [FF52+]
* Vulnerabilities have increasingly been found, including those known and fixed
* in native programs years ago [2]. WASM has powerful low-level access, making
* certain attacks (brute-force) and vulnerabilities more possible
* [STATS] ~0.2% of websites, about half of which are for crytopmining / malvertising [2][3]
* [1] https://developer.mozilla.org/docs/WebAssembly
* [2] https://spectrum.ieee.org/tech-talk/telecom/security/more-worries-over-the-security-of-web-assembly
* [3] https://www.zdnet.com/article/half-of-the-websites-using-webassembly-use-it-for-malicious-purposes ***/
user_pref("javascript.options.wasm", false);
/* 2429: enable (limited but sufficient) window.opener protection [FF65+]
* Makes rel=noopener implicit for target=_blank in anchor and area elements when no rel attribute is set ***/
user_pref("dom.targetBlankNoOpener.enabled", true); // [DEFAULT: true FF79+]
/*** [SECTION 2500]: HARDWARE FINGERPRINTING ***/
user_pref("_user.js.parrot", "2500 syntax error: the parrot's shuffled off 'is mortal coil!");
/* 2502: disable Battery Status API
* Initially a Linux issue (high precision readout) that was fixed.
* However, it is still another metric for fingerprinting, used to raise entropy.
* e.g. do you have a battery or not, current charging status, charge level, times remaining etc
* [NOTE] From FF52+ Battery Status API is only available in chrome/privileged code [1]
* [1] https://bugzilla.mozilla.org/1313580 ***/
// user_pref("dom.battery.enabled", false);
/* 2505: disable media device enumeration [FF29+]
* [NOTE] media.peerconnection.enabled should also be set to false (see 2001)
* [1] https://wiki.mozilla.org/Media/getUserMedia
* [2] https://developer.mozilla.org/docs/Web/API/MediaDevices/enumerateDevices ***/
user_pref("media.navigator.enabled", false);
/* 2508: disable hardware acceleration to reduce graphics fingerprinting [SETUP-HARDEN]
* [WARNING] Affects text rendering (fonts will look different), impacts video performance,
* and parts of Quantum that utilize the GPU will also be affected as they are rolled out
* [SETTING] General>Performance>Custom>Use hardware acceleration when available
* [1] https://wiki.mozilla.org/Platform/GFX/HardwareAcceleration ***/
// user_pref("gfx.direct2d.disabled", true); // [WINDOWS]
// user_pref("layers.acceleration.disabled", true);
/* 2510: disable Web Audio API [FF51+]
* [1] https://bugzilla.mozilla.org/1288359 ***/
user_pref("dom.webaudio.enabled", false);
/* 2517: disable Media Capabilities API [FF63+]
* [WARNING] This *may* affect media performance if disabled, no one is sure
* [1] https://github.com/WICG/media-capabilities
* [2] https://wicg.github.io/media-capabilities/#security-privacy-considerations ***/
// user_pref("media.media-capabilities.enabled", false);
/* 2520: disable virtual reality devices
* Optional protection depending on your connected devices
* [1] https://developer.mozilla.org/docs/Web/API/WebVR_API ***/
// user_pref("dom.vr.enabled", false);
/* 2521: set a default permission for Virtual Reality (see 2520) [FF73+]
* 0=always ask (default), 1=allow, 2=block
* [SETTING] to add site exceptions: Ctrl+I>Permissions>Access Virtual Reality Devices
* [SETTING] to manage site exceptions: Options>Privacy & Security>Permissions>Virtual Reality>Settings ***/
// user_pref("permissions.default.xr", 2);
/*** [SECTION 2600]: MISCELLANEOUS ***/
user_pref("_user.js.parrot", "2600 syntax error: the parrot's run down the curtain!");
/* 2601: prevent accessibility services from accessing your browser [RESTART]
* [SETTING] Privacy & Security>Permissions>Prevent accessibility services from accessing your browser (FF80 or lower)
* [1] https://support.mozilla.org/kb/accessibility-services ***/
user_pref("accessibility.force_disabled", 1);
/* 2602: disable sending additional analytics to web servers
* [1] https://developer.mozilla.org/docs/Web/API/Navigator/sendBeacon ***/
user_pref("beacon.enabled", false);
/* 2603: remove temp files opened with an external application
* [1] https://bugzilla.mozilla.org/302433 ***/
user_pref("browser.helperApps.deleteTempFileOnExit", true);
/* 2604: disable page thumbnail collection ***/
user_pref("browser.pagethumbnails.capturing_disabled", true); // [HIDDEN PREF]
/* 2606: disable UITour backend so there is no chance that a remote page can use it ***/
user_pref("browser.uitour.enabled", false);
user_pref("browser.uitour.url", "");
/* 2607: disable various developer tools in browser context
* [SETTING] Devtools>Advanced Settings>Enable browser chrome and add-on debugging toolboxes
* [1] https://github.com/pyllyukko/user.js/issues/179#issuecomment-246468676 ***/
user_pref("devtools.chrome.enabled", false);
/* 2608: reset remote debugging to disabled
* [1] https://gitlab.torproject.org/tpo/applications/tor-browser/-/issues/16222 ***/
user_pref("devtools.debugger.remote-enabled", false); // [DEFAULT: false]
/* 2609: disable MathML (Mathematical Markup Language) [FF51+] [SETUP-HARDEN]
* [TEST] https://arkenfox.github.io/TZP/tzp.html#misc
* [1] https://bugzilla.mozilla.org/1173199 ***/
// user_pref("mathml.disabled", true);
/* 2610: disable in-content SVG (Scalable Vector Graphics) [FF53+]
* [WARNING] Expect breakage incl. youtube player controls. Best left for a "hardened" profile.
* [1] https://bugzilla.mozilla.org/1216893 ***/
// user_pref("svg.disabled", true);
/* 2611: disable middle mouse click opening links from clipboard
* [1] https://gitlab.torproject.org/tpo/applications/tor-browser/-/issues/10089 ***/
user_pref("middlemouse.contentLoadURL", false);
/* 2615: disable websites overriding Firefox's keyboard shortcuts [FF58+]
* 0 (default) or 1=allow, 2=block
* [SETTING] to add site exceptions: Ctrl+I>Permissions>Override Keyboard Shortcuts ***/
// user_pref("permissions.default.shortcuts", 2);
/* 2616: remove special permissions for certain mozilla domains [FF35+]
* [1] resource://app/defaults/permissions ***/
user_pref("permissions.manager.defaultsUrl", "");
/* 2617: remove webchannel whitelist ***/
user_pref("webchannel.allowObject.urlWhitelist", "");
/* 2619: enforce Punycode for Internationalized Domain Names to eliminate possible spoofing
* Firefox has *some* protections, but it is better to be safe than sorry
* [SETUP-WEB] Might be undesirable for non-latin alphabet users since legitimate IDN's are also punycoded
* [TEST] https://www.xn--80ak6aa92e.com/ (www.apple.com)
* [1] https://wiki.mozilla.org/IDN_Display_Algorithm
* [2] https://en.wikipedia.org/wiki/IDN_homograph_attack
* [3] CVE-2017-5383: https://www.mozilla.org/security/advisories/mfsa2017-02/
* [4] https://www.xudongz.com/blog/2017/idn-phishing/ ***/
user_pref("network.IDN_show_punycode", true);
/* 2620: enforce Firefox's built-in PDF reader [SETUP-CHROME]
* This setting controls if the option "Display in Firefox" is available in the setting below
* and by effect controls whether PDFs are handled in-browser or externally ("Ask" or "Open With")
* PROS: pdfjs is lightweight, open source, and as secure/vetted as any pdf reader out there (more than most)
* Exploits are rare (1 serious case in 4 yrs), treated seriously and patched quickly.
* It doesn't break "state separation" of browser content (by not sharing with OS, independent apps).
* It maintains disk avoidance and application data isolation. It's convenient. You can still save to disk.
* CONS: You may prefer a different pdf reader for security reasons
* CAVEAT: JS can still force a pdf to open in-browser by bundling its own code (rare)
* [SETTING] General>Applications>Portable Document Format (PDF) ***/
user_pref("pdfjs.disabled", false); // [DEFAULT: false]
/* 2621: disable links launching Windows Store on Windows 8/8.1/10 [WINDOWS] ***/
user_pref("network.protocol-handler.external.ms-windows-store", false);
/* 2622: enforce no system colors; they can be fingerprinted
* [SETTING] General>Language and Appearance>Fonts and Colors>Colors>Use system colors ***/
user_pref("browser.display.use_system_colors", false); // [DEFAULT: false]
/* 2623: disable permissions delegation [FF73+]
* Currently applies to cross-origin geolocation, camera, mic and screen-sharing
* permissions, and fullscreen requests. Disabling delegation means any prompts
* for these will show/use their correct 3rd party origin
* [1] https://groups.google.com/forum/#!topic/mozilla.dev.platform/BdFOMAuCGW8/discussion ***/
user_pref("permissions.delegation.enabled", false);
/* 2624: enable "window.name" protection [FF82+]
* If a new page from another domain is loaded into a tab, then window.name is set to an empty string. The original
* string is restored if the tab reverts back to the original page. This change prevents some cross-site attacks
* [TEST] https://arkenfox.github.io/TZP/tests/windownamea.html ***/
user_pref("privacy.window.name.update.enabled", true); // [DEFAULT: true FF86+]
/* 2625: disable bypassing 3rd party extension install prompts [FF82+]
* [1] https://bugzilla.mozilla.org/buglist.cgi?bug_id=1659530,1681331 ***/
user_pref("extensions.postDownloadThirdPartyPrompt", false);
/** DOWNLOADS ***/
/* 2650: discourage downloading to desktop
* 0=desktop, 1=downloads (default), 2=last used
* [SETTING] To set your default "downloads": General>Downloads>Save files to ***/
// user_pref("browser.download.folderList", 2);
/* 2651: enforce user interaction for security by always asking where to download
* [SETUP-CHROME] On Android this blocks longtapping and saving images
* [SETTING] General>Downloads>Always ask you where to save files ***/
user_pref("browser.download.useDownloadDir", false);
/* 2652: disable adding downloads to the system's "recent documents" list ***/
user_pref("browser.download.manager.addToRecentDocs", false);
/* 2654: disable "open with" in download dialog [FF50+] [SETUP-HARDEN]
* This is very useful to enable when the browser is sandboxed (e.g. via AppArmor)
* in such a way that it is forbidden to run external applications.
* [WARNING] This may interfere with some users' workflow or methods
* [1] https://bugzilla.mozilla.org/1281959 ***/
// user_pref("browser.download.forbid_open_with", true);
/** EXTENSIONS ***/
/* 2660: lock down allowed extension directories
* [SETUP-CHROME] This will break extensions, language packs, themes and any other
* XPI files which are installed outside of profile and application directories
* [1] https://mike.kaply.com/2012/02/21/understanding-add-on-scopes/
* [1] archived: https://archive.is/DYjAM ***/
user_pref("extensions.enabledScopes", 5); // [HIDDEN PREF]
user_pref("extensions.autoDisableScopes", 15); // [DEFAULT: 15]
/* 2662: disable webextension restrictions on certain mozilla domains (you also need 4503) [FF60+]
* [1] https://bugzilla.mozilla.org/buglist.cgi?bug_id=1384330,1406795,1415644,1453988 ***/
// user_pref("extensions.webextensions.restrictedDomains", "");
/** SECURITY ***/
/* 2680: enforce CSP (Content Security Policy)
* [WARNING] CSP is a very important and widespread security feature. Don't disable it!
* [1] https://developer.mozilla.org/docs/Web/HTTP/CSP ***/
user_pref("security.csp.enable", true); // [DEFAULT: true]
/* 2684: enforce a security delay on some confirmation dialogs such as install, open/save
* [1] https://www.squarefree.com/2004/07/01/race-conditions-in-security-dialogs/ ***/
user_pref("security.dialog_enable_delay", 700);
/*** [SECTION 2700]: PERSISTENT STORAGE
Data SET by websites including
cookies : profile\cookies.sqlite
localStorage : profile\webappsstore.sqlite
indexedDB : profile\storage\default
appCache : profile\OfflineCache
serviceWorkers :
[NOTE] indexedDB and serviceWorkers are not available in Private Browsing Mode
[NOTE] Blocking cookies also blocks websites access to: localStorage (incl. sessionStorage),
indexedDB, sharedWorker, and serviceWorker (and therefore service worker cache and notifications)
If you set a site exception for cookies (either "Allow" or "Allow for Session") then they become
accessible to websites except shared/service workers where the cookie setting *must* be "Allow"
***/
user_pref("_user.js.parrot", "2700 syntax error: the parrot's joined the bleedin' choir invisible!");
/* 2701: disable 3rd-party cookies and site-data [SETUP-WEB]
* 0=Accept cookies and site data, 1=(Block) All third-party cookies, 2=(Block) All cookies,
* 3=(Block) Cookies from unvisited websites, 4=(Block) Cross-site and social media trackers (default)
* [NOTE] You can set exceptions under site permissions or use an extension
* [NOTE] Enforcing category to custom ensures ETP related prefs are always honored
* [SETTING] Privacy & Security>Enhanced Tracking Protection>Custom>Cookies ***/
user_pref("network.cookie.cookieBehavior", 1);
user_pref("browser.contentblocking.category", "custom");
/* 2702: set third-party cookies (if enabled, see 2701) to session-only
[NOTE] .sessionOnly overrides .nonsecureSessionOnly except when .sessionOnly=false and
.nonsecureSessionOnly=true. This allows you to keep HTTPS cookies, but session-only HTTP ones
* [1] https://feeding.cloud.geek.nz/posts/tweaking-cookies-for-privacy-in-firefox/ ***/
user_pref("network.cookie.thirdparty.sessionOnly", true);
user_pref("network.cookie.thirdparty.nonsecureSessionOnly", true); // [FF58+]
/* 2703: delete cookies and site data on close
* 0=keep until they expire (default), 2=keep until you close Firefox
* [NOTE] The setting below is disabled (but not changed) if you block all cookies (2701 = 2)
* [SETTING] Privacy & Security>Cookies and Site Data>Delete cookies and site data when Firefox is closed ***/
// user_pref("network.cookie.lifetimePolicy", 2);
/* 2710: disable DOM (Document Object Model) Storage
* [WARNING] This will break a LOT of sites' functionality AND extensions!
* You are better off using an extension for more granular control ***/
// user_pref("dom.storage.enabled", false);
/* 2730: enforce no offline cache storage (appCache)
* The API is easily fingerprinted, use the "storage" pref instead ***/
// user_pref("browser.cache.offline.enable", false);
user_pref("browser.cache.offline.storage.enable", false); // [FF71+] [DEFAULT: false FF84+]
/* 2740: disable service worker cache and cache storage
* [NOTE] We clear service worker cache on exiting Firefox (see 2803)
* [1] https://w3c.github.io/ServiceWorker/#privacy ***/
// user_pref("dom.caches.enabled", false);
/* 2750: disable Storage API [FF51+]
* The API gives sites the ability to find out how much space they can use, how much
* they are already using, and even control whether or not they need to be alerted
* before the user agent disposes of site data in order to make room for other things.
* [1] https://developer.mozilla.org/docs/Web/API/StorageManager
* [2] https://developer.mozilla.org/docs/Web/API/Storage_API
* [3] https://blog.mozilla.org/l10n/2017/03/07/firefox-l10n-report-aurora-54/ ***/
// user_pref("dom.storageManager.enabled", false);
/* 2755: disable Storage Access API [FF65+]
* [1] https://developer.mozilla.org/en-US/docs/Web/API/Storage_Access_API ***/
// user_pref("dom.storage_access.enabled", false);
/* 2760: enable Local Storage Next Generation (LSNG) [FF65+] ***/
user_pref("dom.storage.next_gen", true);
/*** [SECTION 2800]: SHUTDOWN
You should set the values to what suits you best.
- "Offline Website Data" includes appCache (2730), localStorage (2710),
service worker cache (2740), and QuotaManager (IndexedDB (2720), asm-cache)
- In both 2803 + 2804, the 'download' and 'history' prefs are combined in the
Firefox interface as "Browsing & Download History" and their values will be synced
***/
user_pref("_user.js.parrot", "2800 syntax error: the parrot's bleedin' demised!");
/* 2802: enable Firefox to clear items on shutdown (see 2803)
* [SETTING] Privacy & Security>History>Custom Settings>Clear history when Firefox closes ***/
user_pref("privacy.sanitize.sanitizeOnShutdown", true);
/* 2803: set what items to clear on shutdown (if 2802 is true) [SETUP-CHROME]
* [NOTE] If 'history' is true, downloads will also be cleared regardless of the value
* but if 'history' is false, downloads can still be cleared independently
* However, this may not always be the case. The interface combines and syncs these
* prefs when set from there, and the sanitize code may change at any time
* [SETTING] Privacy & Security>History>Custom Settings>Clear history when Firefox closes>Settings ***/
user_pref("privacy.clearOnShutdown.cache", true);
user_pref("privacy.clearOnShutdown.cookies", true);
user_pref("privacy.clearOnShutdown.downloads", true); // see note above
user_pref("privacy.clearOnShutdown.formdata", true); // Form & Search History
user_pref("privacy.clearOnShutdown.history", true); // Browsing & Download History
user_pref("privacy.clearOnShutdown.offlineApps", true); // Offline Website Data
user_pref("privacy.clearOnShutdown.sessions", true); // Active Logins
user_pref("privacy.clearOnShutdown.siteSettings", false); // Site Preferences
/* 2804: reset default items to clear with Ctrl-Shift-Del (to match 2803) [SETUP-CHROME]
* This dialog can also be accessed from the menu History>Clear Recent History
* Firefox remembers your last choices. This will reset them when you start Firefox.
* [NOTE] Regardless of what you set privacy.cpd.downloads to, as soon as the dialog
* for "Clear Recent History" is opened, it is synced to the same as 'history' ***/
user_pref("privacy.cpd.cache", true);
user_pref("privacy.cpd.cookies", true);
// user_pref("privacy.cpd.downloads", true); // not used, see note above
user_pref("privacy.cpd.formdata", true); // Form & Search History
user_pref("privacy.cpd.history", true); // Browsing & Download History
user_pref("privacy.cpd.offlineApps", true); // Offline Website Data
user_pref("privacy.cpd.passwords", false); // this is not listed
user_pref("privacy.cpd.sessions", true); // Active Logins
user_pref("privacy.cpd.siteSettings", false); // Site Preferences
/* 2805: clear Session Restore data when sanitizing on shutdown or manually [FF34+]
* [NOTE] Not needed if Session Restore is not used (see 0102) or is already cleared with history (see 2803)
* [NOTE] privacy.clearOnShutdown.openWindows prevents resuming from crashes (see 1022)
* [NOTE] privacy.cpd.openWindows has a bug that causes an additional window to open ***/
// user_pref("privacy.clearOnShutdown.openWindows", true);
// user_pref("privacy.cpd.openWindows", true);
/* 2806: reset default 'Time range to clear' for 'Clear Recent History' (see 2804)
* Firefox remembers your last choice. This will reset the value when you start Firefox.
* 0=everything, 1=last hour, 2=last two hours, 3=last four hours,
* 4=today, 5=last five minutes, 6=last twenty-four hours
* [NOTE] The values 5 + 6 are not listed in the dropdown, which will display a
* blank value if they are used, but they do work as advertised ***/
user_pref("privacy.sanitize.timeSpan", 0);
/*** [SECTION 4000]: FPI (FIRST PARTY ISOLATION)
1278037 - indexedDB (FF51+)
1277803 - favicons (FF52+)
1264562 - OCSP cache (FF52+)
1268726 - Shared Workers (FF52+)
1316283 - SSL session cache (FF52+)
1317927 - media cache (FF53+)
1323644 - HSTS and HPKP (FF54+)
1334690 - HTTP Alternative Services (FF54+)
1334693 - SPDY/HTTP2 (FF55+)
1337893 - DNS cache (FF55+)
1344170 - blob: URI (FF55+)
1300671 - data:, about: URLs (FF55+)
1473247 - IP addresses (FF63+)
1492607 - postMessage with targetOrigin "*" (requires 4002) (FF65+)
1542309 - top-level domain URLs when host is in the public suffix list (FF68+)
1506693 - pdfjs range-based requests (FF68+)
1330467 - site permissions (FF69+)
1534339 - IPv6 (FF73+)
***/
user_pref("_user.js.parrot", "4000 syntax error: the parrot's pegged out");
/* 4001: enable First Party Isolation [FF51+]
* [SETUP-WEB] May break cross-domain logins and site functionality until perfected
* [1] https://bugzilla.mozilla.org/buglist.cgi?bug_id=1260931,1299996 ***/
user_pref("privacy.firstparty.isolate", true);
/* 4002: enforce FPI restriction for window.opener [FF54+]
* [NOTE] Setting this to false may reduce the breakage in 4001
* FF65+ blocks postMessage with targetOrigin "*" if originAttributes don't match. But
* to reduce breakage it ignores the 1st-party domain (FPD) originAttribute [2][3]
* The 2nd pref removes that limitation and will only allow communication if FPDs also match.
* [1] https://bugzilla.mozilla.org/1319773#c22
* [2] https://bugzilla.mozilla.org/1492607
* [3] https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage ***/
// user_pref("privacy.firstparty.isolate.restrict_opener_access", true); // [DEFAULT: true]
// user_pref("privacy.firstparty.isolate.block_post_message", true);
/* 4003: enable scheme with FPI [FF78+]
* [NOTE] Experimental: existing data and site permissions are incompatible
* and some site exceptions may not work e.g. HTTPS-only mode (see 1244) ***/
// user_pref("privacy.firstparty.isolate.use_site", true);
/*** [SECTION 4500]: RFP (RESIST FINGERPRINTING)
RFP covers a wide range of ongoing fingerprinting solutions.
It is an all-or-nothing buy in: you cannot pick and choose what parts you want
[WARNING] Do NOT use extensions to alter RFP protected metrics
[WARNING] Do NOT use prefs in section 4600 with RFP as they can interfere
FF41+
418986 - limit window.screen & CSS media queries leaking identifiable info
[TEST] https://arkenfox.github.io/TZP/tzp.html#screen
FF50+
1281949 - spoof screen orientation
1281963 - hide the contents of navigator.plugins and navigator.mimeTypes (FF50+)
FF55+
1330890 - spoof timezone as UTC 0
1360039 - spoof navigator.hardwareConcurrency as 2 (see 4601)
1217238 - reduce precision of time exposed by javascript
FF56+
1369303 - spoof/disable performance API (see 4602, 4603)
1333651 - spoof User Agent & Navigator API (see section 4700)
JS: FF78+ the version is spoofed as 78, and the OS as Windows 10, OS 10.15, Android 9, or Linux
HTTP Headers: spoofed as Windows or Android
1369319 - disable device sensor API (see 4604)
1369357 - disable site specific zoom (see 4605)
1337161 - hide gamepads from content (see 4606)
1372072 - spoof network information API as "unknown" when dom.netinfo.enabled = true (see 4607)
1333641 - reduce fingerprinting in WebSpeech API (see 4608)
FF57+
1369309 - spoof media statistics (see 4610)
1382499 - reduce screen co-ordinate fingerprinting in Touch API (see 4611)
1217290 & 1409677 - enable fingerprinting resistance for WebGL (see 2010-12)
1382545 - reduce fingerprinting in Animation API
1354633 - limit MediaError.message to a whitelist
1382533 - enable fingerprinting resistance for Presentation API
This blocks exposure of local IP Addresses via mDNS (Multicast DNS)
FF58+
967895 - spoof canvas and enable site permission prompt before allowing canvas data extraction
FF59+
1372073 - spoof/block fingerprinting in MediaDevices API
Spoof: enumerate devices reports one "Internal Camera" and one "Internal Microphone" if
media.navigator.enabled is true (see 2505 which we chose to keep disabled)
Block: suppresses the ondevicechange event (see 4612)
1039069 - warn when language prefs are set to non en-US (see 0210, 0211)
1222285 & 1433592 - spoof keyboard events and suppress keyboard modifier events
Spoofing mimics the content language of the document. Currently it only supports en-US.
Modifier events suppressed are SHIFT and both ALT keys. Chrome is not affected.
FF60-67
1337157 - disable WebGL debug renderer info (see 4613) (FF60+)
1459089 - disable OS locale in HTTP Accept-Language headers (ANDROID) (FF62+)
1479239 - return "no-preference" with prefers-reduced-motion (see 4614) (FF63+)
1363508 - spoof/suppress Pointer Events (see 4615) (FF64+)
FF65: pointerEvent.pointerid (1492766)
1485266 - disable exposure of system colors to CSS or canvas (see 4616) (FF67+)
1407366 - enable inner window letterboxing (see 4504) (FF67+)
1494034 - return "light" with prefers-color-scheme (see 4617) (FF67+)
FF68-77
1564422 - spoof audioContext outputLatency (FF70+)
1595823 - spoof audioContext sampleRate (FF72+)
1607316 - spoof pointer as coarse and hover as none (ANDROID) (FF74+)
FF78+
1621433 - randomize canvas (previously FF58+ returned an all-white canvas) (FF78+)
1653987 - limit font visibility to bundled and "Base Fonts" (see 4618) (non-ANDROID) (FF80+)
1461454 - spoof smooth=true and powerEfficient=false for supported media in MediaCapabilities (FF82+)
***/
user_pref("_user.js.parrot", "4500 syntax error: the parrot's popped 'is clogs");
/* 4501: enable privacy.resistFingerprinting [FF41+]
* This pref is the master switch for all other privacy.resist* prefs unless stated
* [SETUP-WEB] RFP can cause the odd website to break in strange ways, and has a few side affects,
* but is largely robust nowadays. Give it a try. Your choice. Also see 4504 (letterboxing).
* [1] https://bugzilla.mozilla.org/418986 ***/
user_pref("privacy.resistFingerprinting", true);
/* 4502: set new window sizes to round to hundreds [FF55+] [SETUP-CHROME]
* Width will round down to multiples of 200s and height to 100s, to fit your screen.
* The override values are a starting point to round from if you want some control
* [1] https://bugzilla.mozilla.org/1330882 ***/
// user_pref("privacy.window.maxInnerWidth", 1000);
// user_pref("privacy.window.maxInnerHeight", 1000);
/* 4503: disable mozAddonManager Web API [FF57+]
* [NOTE] To allow extensions to work on AMO, you also need 2662
* [1] https://bugzilla.mozilla.org/buglist.cgi?bug_id=1384330,1406795,1415644,1453988 ***/
user_pref("privacy.resistFingerprinting.block_mozAddonManager", true); // [HIDDEN PREF]
/* 4504: enable RFP letterboxing [FF67+]
* Dynamically resizes the inner window by applying margins in stepped ranges [2]
* If you use the dimension pref, then it will only apply those resolutions. The format is
* "width1xheight1, width2xheight2, ..." (e.g. "800x600, 1000x1000, 1600x900")
* [SETUP-WEB] This does NOT require RFP (see 4501) **for now**, so if you're not using 4501, or you are but
* dislike margins being applied, then flip this pref, keeping in mind that it is effectively fingerprintable
* [WARNING] The dimension pref is only meant for testing, and we recommend you DO NOT USE it
* [1] https://bugzilla.mozilla.org/1407366
* [2] https://hg.mozilla.org/mozilla-central/rev/6d2d7856e468#l2.32 ***/
user_pref("privacy.resistFingerprinting.letterboxing", true); // [HIDDEN PREF]
// user_pref("privacy.resistFingerprinting.letterboxing.dimensions", ""); // [HIDDEN PREF]
/* 4510: disable showing about:blank as soon as possible during startup [FF60+]
* When default true this no longer masks the RFP chrome resizing activity
* [1] https://bugzilla.mozilla.org/1448423 ***/
user_pref("browser.startup.blankWindow", false);
/* 4520: disable chrome animations [FF77+] [RESTART]
* [NOTE] pref added in FF63, but applied to chrome in FF77. RFP spoofs this for web content ***/
user_pref("ui.prefersReducedMotion", 1); // [HIDDEN PREF]
/*** [SECTION 4600]: RFP ALTERNATIVES
[WARNING] Do NOT use prefs in this section with RFP as they can interfere
***/
user_pref("_user.js.parrot", "4600 syntax error: the parrot's crossed the Jordan");
/* [SETUP-non-RFP] Non-RFP users replace the * with a slash on this line to enable these
// FF55+
// 4601: [2514] spoof (or limit?) number of CPU cores [FF48+]
// [NOTE] *may* affect core chrome/Firefox performance, will affect content.
// [1] https://bugzilla.mozilla.org/1008453
// [2] https://gitlab.torproject.org/tpo/applications/tor-browser/-/issues/21675
// [3] https://gitlab.torproject.org/tpo/applications/tor-browser/-/issues/22127
// [4] https://html.spec.whatwg.org/multipage/workers.html#navigator.hardwareconcurrency
// user_pref("dom.maxHardwareConcurrency", 2);
// * * * /
// FF56+
// 4602: [2411] disable resource/navigation timing
user_pref("dom.enable_resource_timing", false);
// 4603: [2412] disable timing attacks
// [1] https://wiki.mozilla.org/Security/Reviews/Firefox/NavigationTimingAPI
user_pref("dom.enable_performance", false);
// 4604: [2512] disable device sensor API
// Optional protection depending on your device
// [1] https://gitlab.torproject.org/tpo/applications/tor-browser/-/issues/15758
// [2] https://blog.lukaszolejnik.com/stealing-sensitive-browser-data-with-the-w3c-ambient-light-sensor-api/
// [3] https://bugzilla.mozilla.org/buglist.cgi?bug_id=1357733,1292751
// user_pref("device.sensors.enabled", false);
// 4605: [2515] disable site specific zoom
// Zoom levels affect screen res and are highly fingerprintable. This does not stop you using
// zoom, it will just not use/remember any site specific settings. Zoom levels on new tabs
// and new windows are reset to default and only the current tab retains the current zoom
user_pref("browser.zoom.siteSpecific", false);
// 4606: [2501] disable gamepad API - USB device ID enumeration
// Optional protection depending on your connected devices
// [1] https://gitlab.torproject.org/tpo/applications/tor-browser/-/issues/13023
// user_pref("dom.gamepad.enabled", false);
// 4607: [2503] disable giving away network info [FF31+]
// e.g. bluetooth, cellular, ethernet, wifi, wimax, other, mixed, unknown, none
// [1] https://developer.mozilla.org/docs/Web/API/Network_Information_API
// [2] https://wicg.github.io/netinfo/
// [3] https://bugzilla.mozilla.org/960426
user_pref("dom.netinfo.enabled", false); // [DEFAULT: true on Android]
// 4608: [2021] disable the SpeechSynthesis (Text-to-Speech) part of the Web Speech API
// [1] https://developer.mozilla.org/docs/Web/API/Web_Speech_API
// [2] https://developer.mozilla.org/docs/Web/API/SpeechSynthesis
// [3] https://wiki.mozilla.org/HTML5_Speech_API
user_pref("media.webspeech.synth.enabled", false);
// * * * /
// FF57+
// 4610: [2506] disable video statistics - JS performance fingerprinting [FF25+]
// [1] https://gitlab.torproject.org/tpo/applications/tor-browser/-/issues/15757
// [2] https://bugzilla.mozilla.org/654550
user_pref("media.video_stats.enabled", false);
// 4611: [2509] disable touch events
// fingerprinting attack vector - leaks screen res & actual screen coordinates
// 0=disabled, 1=enabled, 2=autodetect
// Optional protection depending on your device
// [1] https://developer.mozilla.org/docs/Web/API/Touch_events
// [2] https://gitlab.torproject.org/tpo/applications/tor-browser/-/issues/10286
// user_pref("dom.w3c_touch_events.enabled", 0);
// * * * /
// FF59+
// 4612: [2511] disable MediaDevices change detection [FF51+]
// [1] https://developer.mozilla.org/docs/Web/Events/devicechange
// [2] https://developer.mozilla.org/docs/Web/API/MediaDevices/ondevicechange
user_pref("media.ondevicechange.enabled", false);
// * * * /
// FF60+
// 4613: [2011] disable WebGL debug info being available to websites
// [1] https://bugzilla.mozilla.org/1171228
// [2] https://developer.mozilla.org/docs/Web/API/WEBGL_debug_renderer_info
user_pref("webgl.enable-debug-renderer-info", false);
// * * * /
// FF63+
// 4614: enforce prefers-reduced-motion as no-preference [FF63+] [RESTART]
// 0=no-preference, 1=reduce
user_pref("ui.prefersReducedMotion", 0); // [HIDDEN PREF]
// FF64+
// 4615: [2516] disable PointerEvents [FF86 or lower]
// [1] https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent
// [-] https://bugzilla.mozilla.org/1688105
user_pref("dom.w3c_pointer_events.enabled", false);
// * * * /
// FF67+
// 4616: [2618] disable exposure of system colors to CSS or canvas [FF44+]
// [NOTE] See second listed bug: may cause black on black for elements with undefined colors
// [SETUP-CHROME] Might affect CSS in themes and extensions
// [1] https://bugzilla.mozilla.org/buglist.cgi?bug_id=232227,1330876
user_pref("ui.use_standins_for_native_colors", true);
// 4617: enforce prefers-color-scheme as light [FF67+]
// 0=light, 1=dark : This overrides your OS value
user_pref("ui.systemUsesDarkTheme", 0); // [HIDDEN PREF]
// FF80+
// 4618: limit font visibility (non-ANDROID) [FF79+]
// Uses hardcoded lists with two parts: kBaseFonts + kLangPackFonts [1]
// 1=only base system fonts, 2=also fonts from optional language packs, 3=also user-installed fonts
// [NOTE] Bundled fonts are auto-allowed
// [1] https://searchfox.org/mozilla-central/search?path=StandardFonts*.inc
user_pref("layout.css.font-visibility.level", 1);
// * * * /
// ***/
/*** [SECTION 4700]: RFP ALTERNATIVES (USER AGENT SPOOFING)
These prefs are insufficient and leak. Use RFP and **nothing else**
- Many of the user agent components can be derived by other means. When those
values differ, you provide more bits and raise entropy. Examples include
workers, iframes, headers, tcp/ip attributes, feature detection, and many more
- Web extensions also lack APIs to fully protect spoofing
***/
user_pref("_user.js.parrot", "4700 syntax error: the parrot's taken 'is last bow");
/* 4701: navigator DOM object overrides
* [WARNING] DO NOT USE ***/
// user_pref("general.appname.override", ""); // [HIDDEN PREF]
// user_pref("general.appversion.override", ""); // [HIDDEN PREF]
// user_pref("general.buildID.override", ""); // [HIDDEN PREF]
// user_pref("general.oscpu.override", ""); // [HIDDEN PREF]
// user_pref("general.platform.override", ""); // [HIDDEN PREF]
// user_pref("general.useragent.override", ""); // [HIDDEN PREF]
/*** [SECTION 5000]: PERSONAL
Non-project related but useful. If any of these interest you, add them to your overrides ***/
user_pref("_user.js.parrot", "5000 syntax error: this is an ex-parrot!");
/* WELCOME & WHAT's NEW NOTICES ***/
// user_pref("browser.startup.homepage_override.mstone", "ignore"); // master switch
// user_pref("startup.homepage_welcome_url", "");
// user_pref("startup.homepage_welcome_url.additional", "");
// user_pref("startup.homepage_override_url", ""); // What's New page after updates
/* WARNINGS ***/
// user_pref("browser.tabs.warnOnClose", false);
// user_pref("browser.tabs.warnOnCloseOtherTabs", false);
// user_pref("browser.tabs.warnOnOpen", false);
// user_pref("full-screen-api.warning.delay", 0);
// user_pref("full-screen-api.warning.timeout", 0);
/* APPEARANCE ***/
// user_pref("browser.download.autohideButton", false); // [FF57+]
// user_pref("toolkit.legacyUserProfileCustomizations.stylesheets", true); // [FF68+] allow userChrome/userContent
/* CONTENT BEHAVIOR ***/
// user_pref("accessibility.typeaheadfind", true); // enable "Find As You Type"
// user_pref("clipboard.autocopy", false); // disable autocopy default [LINUX]
// user_pref("layout.spellcheckDefault", 2); // 0=none, 1-multi-line, 2=multi-line & single-line
/* UX BEHAVIOR ***/
// user_pref("browser.backspace_action", 2); // 0=previous page, 1=scroll up, 2=do nothing
// user_pref("browser.quitShortcut.disabled", true); // disable Ctrl-Q quit shortcut [LINUX] [MAC] [FF87+]
// user_pref("browser.tabs.closeWindowWithLastTab", false);
// user_pref("browser.tabs.loadBookmarksInTabs", true); // open bookmarks in a new tab [FF57+]
// user_pref("browser.urlbar.decodeURLsOnCopy", true); // see bugzilla 1320061 [FF53+]
// user_pref("general.autoScroll", false); // middle-click enabling auto-scrolling [DEFAULT: false on Linux]
// user_pref("ui.key.menuAccessKey", 0); // disable alt key toggling the menu bar [RESTART]
// user_pref("view_source.tab", false); // view "page/selection source" in a new window [FF68+, FF59 and under]
/* UX FEATURES: disable and hide the icons and menus ***/
// user_pref("browser.messaging-system.whatsNewPanel.enabled", false); // What's New [FF69+]
// user_pref("extensions.pocket.enabled", false); // Pocket Account [FF46+]
// user_pref("identity.fxaccounts.enabled", false); // Firefox Accounts & Sync [FF60+] [RESTART]
// user_pref("reader.parse-on-load.enabled", false); // Reader View
/* OTHER ***/
// user_pref("browser.bookmarks.max_backups", 2);
// user_pref("browser.newtabpage.activity-stream.asrouter.userprefs.cfr.addons", false); // disable CFR [FF67+]
// [SETTING] General>Browsing>Recommend extensions as you browse
// user_pref("browser.newtabpage.activity-stream.asrouter.userprefs.cfr.features", false); // disable CFR [FF67+]
// [SETTING] General>Browsing>Recommend features as you browse
// user_pref("network.manage-offline-status", false); // see bugzilla 620472
// user_pref("xpinstall.signatures.required", false); // enforced extension signing (Nightly/ESR)
/*** [SECTION 9999]: DEPRECATED / REMOVED / LEGACY / RENAMED
Documentation denoted as [-]. Items deprecated in FF78 or earlier have been archived at [1],
which also provides a link-clickable, viewer-friendly version of the deprecated bugzilla tickets
[1] https://github.com/arkenfox/user.js/issues/123
***/
user_pref("_user.js.parrot", "9999 syntax error: the parrot's deprecated!");
/* ESR78.x still uses all the following prefs
// [NOTE] replace the * with a slash in the line above to re-enable them
// FF79
// 0212: enforce fallback text encoding to match en-US
// When the content or server doesn't declare a charset the browser will
// fallback to the "Current locale" based on your application language
// [TEST] https://hsivonen.com/test/moz/check-charset.htm
// [1] https://gitlab.torproject.org/tpo/applications/tor-browser/-/issues/20025
// [-] https://bugzilla.mozilla.org/1603712
user_pref("intl.charset.fallback.override", "windows-1252");
// FF82
// 0206: disable geographically specific results/search engines e.g. "browser.search.*.US"
// i.e. ignore all of Mozilla's various search engines in multiple locales
// [-] https://bugzilla.mozilla.org/1619926
user_pref("browser.search.geoSpecificDefaults", false);
user_pref("browser.search.geoSpecificDefaults.url", "");
// FF86
// 1205: disable SSL Error Reporting
// [1] https://firefox-source-docs.mozilla.org/browser/base/sslerrorreport/preferences.html
// [-] https://bugzilla.mozilla.org/1681839
user_pref("security.ssl.errorReporting.automatic", false);
user_pref("security.ssl.errorReporting.enabled", false);
user_pref("security.ssl.errorReporting.url", "");
// 2653: disable hiding mime types (Options>General>Applications) not associated with a plugin
// [-] https://bugzilla.mozilla.org/1581678
user_pref("browser.download.hide_plugins_without_extensions", false);
// FF87
// 0105d: disable Activity Stream recent Highlights in the Library [FF57+]
// [-] https://bugzilla.mozilla.org/1689405
// user_pref("browser.library.activity-stream.enabled", false);
// ***/
/* END: internal custom pref to test for syntax errors ***/
user_pref("_user.js.parrot", "SUCCESS: No no he's not dead, he's, he's restin'!");
| user.js | /******
* name: arkenfox user.js
* date: 02 March 2021
* version 87-alpha
* url: https://github.com/arkenfox/user.js
* license: MIT: https://github.com/arkenfox/user.js/blob/master/LICENSE.txt
* README:
1. Consider using Tor Browser if it meets your needs or fits your threat model better
* https://www.torproject.org/about/torusers.html.en
2. Required reading: Overview, Backing Up, Implementing, and Maintenance entries
* https://github.com/arkenfox/user.js/wiki
3. If you skipped step 2, return to step 2
4. Make changes
* There are often trade-offs and conflicts between security vs privacy vs anti-fingerprinting
and these need to be balanced against functionality & convenience & breakage
* Some site breakage and unintended consequences will happen. Everyone's experience will differ
e.g. some user data is erased on close (section 2800), change this to suit your needs
* While not 100% definitive, search for "[SETUP" tags
e.g. third party images/videos not loading on some sites? check 1603
* Take the wiki link in step 2 and read the Troubleshooting entry
5. Some tag info
[SETUP-SECURITY] it's one item, read it
[SETUP-WEB] can cause some websites to break
[SETUP-CHROME] changes how Firefox itself behaves (i.e. not directly website related)
[SETUP-PERF] may impact performance
[WARNING] used sparingly, heed them
6. Override Recipes: https://github.com/arkenfox/user.js/issues/1080
* RELEASES: https://github.com/arkenfox/user.js/releases
* It is best to use the arkenfox release that is optimized for and matches your Firefox version
* EVERYONE: each release
- run prefsCleaner or reset deprecated prefs (9999s) and prefs made redundant by RPF (4600s)
- re-enable section 4600 if you don't use RFP
ESR78
- If you are not using arkenfox v78... (not a definitive list)
- 1244: HTTPS-Only mode is enabled
- 1401: document fonts is inactive as it is now covered by RFP in FF80+
- 4600: some prefs may apply even if you use RFP
- 9999: switch the appropriate deprecated section(s) back on
* INDEX:
0100: STARTUP
0200: GEOLOCATION / LANGUAGE / LOCALE
0300: QUIET FOX
0400: BLOCKLISTS / SAFE BROWSING
0500: SYSTEM ADD-ONS / EXPERIMENTS
0600: BLOCK IMPLICIT OUTBOUND
0700: HTTP* / TCP/IP / DNS / PROXY / SOCKS etc
0800: LOCATION BAR / SEARCH BAR / SUGGESTIONS / HISTORY / FORMS
0900: PASSWORDS
1000: CACHE / SESSION (RE)STORE / FAVICONS
1200: HTTPS (SSL/TLS / OCSP / CERTS / HPKP / CIPHERS)
1400: FONTS
1600: HEADERS / REFERERS
1700: CONTAINERS
1800: PLUGINS
2000: MEDIA / CAMERA / MIC
2200: WINDOW MEDDLING & LEAKS / POPUPS
2300: WEB WORKERS
2400: DOM (DOCUMENT OBJECT MODEL) & JAVASCRIPT
2500: HARDWARE FINGERPRINTING
2600: MISCELLANEOUS
2700: PERSISTENT STORAGE
2800: SHUTDOWN
4000: FPI (FIRST PARTY ISOLATION)
4500: RFP (RESIST FINGERPRINTING)
4600: RFP ALTERNATIVES
4700: RFP ALTERNATIVES (USER AGENT SPOOFING)
5000: PERSONAL
9999: DEPRECATED / REMOVED / LEGACY / RENAMED
******/
/* START: internal custom pref to test for syntax errors
* [NOTE] In FF60+, not all syntax errors cause parsing to abort i.e. reaching the last debug
* pref no longer necessarily means that all prefs have been applied. Check the console right
* after startup for any warnings/error messages related to non-applied prefs
* [1] https://blog.mozilla.org/nnethercote/2018/03/09/a-new-preferences-parser-for-firefox/ ***/
user_pref("_user.js.parrot", "START: Oh yes, the Norwegian Blue... what's wrong with it?");
/* 0000: disable about:config warning
* FF73-86: chrome://global/content/config.xhtml ***/
user_pref("general.warnOnAboutConfig", false); // XHTML version
user_pref("browser.aboutConfig.showWarning", false); // HTML version [FF71+]
/*** [SECTION 0100]: STARTUP ***/
user_pref("_user.js.parrot", "0100 syntax error: the parrot's dead!");
/* 0101: disable default browser check
* [SETTING] General>Startup>Always check if Firefox is your default browser ***/
user_pref("browser.shell.checkDefaultBrowser", false);
/* 0102: set START page (0=blank, 1=home, 2=last visited page, 3=resume previous session)
* [NOTE] Session Restore is not used in PB mode (0110) and is cleared with history (2803, 2804)
* [SETTING] General>Startup>Restore previous session ***/
user_pref("browser.startup.page", 0);
/* 0103: set HOME+NEWWINDOW page
* about:home=Activity Stream (default, see 0105), custom URL, about:blank
* [SETTING] Home>New Windows and Tabs>Homepage and new windows ***/
user_pref("browser.startup.homepage", "about:blank");
/* 0104: set NEWTAB page
* true=Activity Stream (default, see 0105), false=blank page
* [SETTING] Home>New Windows and Tabs>New tabs ***/
user_pref("browser.newtabpage.enabled", false);
user_pref("browser.newtab.preload", false);
/* 0105: disable Activity Stream stuff (AS)
* AS is the default homepage/newtab in FF57+, based on metadata and browsing behavior.
* **NOT LISTING ALL OF THESE: USE THE PREFERENCES UI**
* [SETTING] Home>Firefox Home Content>... to show/hide what you want ***/
/* 0105a: disable Activity Stream telemetry ***/
user_pref("browser.newtabpage.activity-stream.feeds.telemetry", false);
user_pref("browser.newtabpage.activity-stream.telemetry", false);
/* 0105b: disable Activity Stream Snippets
* Runs code received from a server (aka Remote Code Execution) and sends information back to a metrics server
* [1] https://abouthome-snippets-service.readthedocs.io/ ***/
user_pref("browser.newtabpage.activity-stream.feeds.snippets", false);
/* 0105c: disable Activity Stream Top Stories, Pocket-based and/or sponsored content ***/
user_pref("browser.newtabpage.activity-stream.feeds.section.topstories", false);
user_pref("browser.newtabpage.activity-stream.section.highlights.includePocket", false);
user_pref("browser.newtabpage.activity-stream.showSponsored", false);
user_pref("browser.newtabpage.activity-stream.feeds.discoverystreamfeed", false); // [FF66+]
/* 0105d: disable Activity Stream recent Highlights in the Library [FF57+] ***/
// user_pref("browser.library.activity-stream.enabled", false);
/* 0105e: clear default topsites
* [NOTE] This does not block you from adding your own ***/
user_pref("browser.newtabpage.activity-stream.default.sites", "");
/* 0110: start Firefox in PB (Private Browsing) mode
* [NOTE] In this mode *all* windows are "private windows" and the PB mode icon is not displayed
* [WARNING] The P in PB mode is misleading: it means no "persistent" disk storage such as history,
* caches, searches, cookies, localStorage, IndexedDB etc (which you can achieve in normal mode).
* In fact, PB mode limits or removes the ability to control some of these, and you need to quit
* Firefox to clear them. PB is best used as a one off window (File>New Private Window) to provide
* a temporary self-contained new session. Close all Private Windows to clear the PB mode session.
* [SETTING] Privacy & Security>History>Custom Settings>Always use private browsing mode
* [1] https://wiki.mozilla.org/Private_Browsing
* [2] https://spreadprivacy.com/is-private-browsing-really-private/ ***/
// user_pref("browser.privatebrowsing.autostart", true);
/*** [SECTION 0200]: GEOLOCATION / LANGUAGE / LOCALE ***/
user_pref("_user.js.parrot", "0200 syntax error: the parrot's definitely deceased!");
/** GEOLOCATION ***/
/* 0201: disable Location-Aware Browsing
* [NOTE] Best left at default "true", fingerprintable, already behind a prompt (see 0202)
* [1] https://www.mozilla.org/firefox/geolocation/ ***/
// user_pref("geo.enabled", false);
/* 0202: set a default permission for Location (see 0201) [FF58+]
* 0=always ask (default), 1=allow, 2=block
* [NOTE] Best left at default "always ask", fingerprintable via Permissions API
* [SETTING] to add site exceptions: Ctrl+I>Permissions>Access Your Location
* [SETTING] to manage site exceptions: Options>Privacy & Security>Permissions>Location>Settings ***/
// user_pref("permissions.default.geo", 2);
/* 0203: use Mozilla geolocation service instead of Google when geolocation is enabled [FF74+]
* Optionally enable logging to the console (defaults to false) ***/
user_pref("geo.provider.network.url", "https://location.services.mozilla.com/v1/geolocate?key=%MOZILLA_API_KEY%");
// user_pref("geo.provider.network.logging.enabled", true); // [HIDDEN PREF]
/* 0204: disable using the OS's geolocation service ***/
user_pref("geo.provider.ms-windows-location", false); // [WINDOWS]
user_pref("geo.provider.use_corelocation", false); // [MAC]
user_pref("geo.provider.use_gpsd", false); // [LINUX]
/* 0207: disable region updates
* [1] https://firefox-source-docs.mozilla.org/toolkit/modules/toolkit_modules/Region.html ***/
user_pref("browser.region.network.url", ""); // [FF78+]
user_pref("browser.region.update.enabled", false); // [[FF79+]
/* 0208: set search region
* [NOTE] May not be hidden if Firefox has changed your settings due to your region (see 0207) ***/
// user_pref("browser.search.region", "US"); // [HIDDEN PREF]
/** LANGUAGE / LOCALE ***/
/* 0210: set preferred language for displaying web pages
* [TEST] https://addons.mozilla.org/about ***/
user_pref("intl.accept_languages", "en-US, en");
/* 0211: enforce US English locale regardless of the system locale
* [SETUP-WEB] May break some input methods e.g xim/ibus for CJK languages [1]
* [1] https://bugzilla.mozilla.org/buglist.cgi?bug_id=867501,1629630 ***/
user_pref("javascript.use_us_english_locale", true); // [HIDDEN PREF]
/*** [SECTION 0300]: QUIET FOX
We only disable the auto-INSTALL of Firefox (app) updates. You still get prompts to update,
and it only takes one click. We highly discourage disabling auto-CHECKING for updates.
Legitimate reasons to disable auto-INSTALLS include hijacked/monetized extensions, time
constraints, legacy issues, dev/testing, and fear of breakage/bugs. It is still important
to do updates for security reasons, please do so manually if you make changes.
***/
user_pref("_user.js.parrot", "0300 syntax error: the parrot's not pinin' for the fjords!");
/* 0301b: disable auto-CHECKING for extension and theme updates ***/
// user_pref("extensions.update.enabled", false);
/* 0302a: disable auto-INSTALLING Firefox updates [NON-WINDOWS FF65+]
* [NOTE] In FF65+ on Windows this SETTING (below) is now stored in a file and the pref was removed
* [SETTING] General>Firefox Updates>Check for updates but let you choose to install them ***/
user_pref("app.update.auto", false);
/* 0302b: disable auto-INSTALLING extension and theme updates (after the check in 0301b)
* [SETTING] about:addons>Extensions>[cog-wheel-icon]>Update Add-ons Automatically (toggle) ***/
// user_pref("extensions.update.autoUpdateDefault", false);
/* 0306: disable extension metadata
* used when installing/updating an extension, and in daily background update checks:
* when false, extension detail tabs will have no description ***/
// user_pref("extensions.getAddons.cache.enabled", false);
/* 0308: disable search engine updates (e.g. OpenSearch)
* [NOTE] This does not affect Mozilla's built-in or Web Extension search engines ***/
user_pref("browser.search.update", false);
/* 0309: disable sending Flash crash reports ***/
user_pref("dom.ipc.plugins.flash.subprocess.crashreporter.enabled", false);
/* 0310: disable sending the URL of the website where a plugin crashed ***/
user_pref("dom.ipc.plugins.reportCrashURL", false);
/* 0320: disable about:addons' Recommendations pane (uses Google Analytics) ***/
user_pref("extensions.getAddons.showPane", false); // [HIDDEN PREF]
/* 0321: disable recommendations in about:addons' Extensions and Themes panes [FF68+] ***/
user_pref("extensions.htmlaboutaddons.recommendations.enabled", false);
/* 0330: disable telemetry
* the pref (.unified) affects the behaviour of the pref (.enabled)
* IF unified=false then .enabled controls the telemetry module
* IF unified=true then .enabled ONLY controls whether to record extended data
* so make sure to have both set as false
* [NOTE] FF58+ 'toolkit.telemetry.enabled' is now LOCKED to reflect prerelease
* or release builds (true and false respectively) [2]
* [1] https://firefox-source-docs.mozilla.org/toolkit/components/telemetry/telemetry/internals/preferences.html
* [2] https://medium.com/georg-fritzsche/data-preference-changes-in-firefox-58-2d5df9c428b5 ***/
user_pref("toolkit.telemetry.unified", false);
user_pref("toolkit.telemetry.enabled", false); // see [NOTE]
user_pref("toolkit.telemetry.server", "data:,");
user_pref("toolkit.telemetry.archive.enabled", false);
user_pref("toolkit.telemetry.newProfilePing.enabled", false); // [FF55+]
user_pref("toolkit.telemetry.shutdownPingSender.enabled", false); // [FF55+]
user_pref("toolkit.telemetry.updatePing.enabled", false); // [FF56+]
user_pref("toolkit.telemetry.bhrPing.enabled", false); // [FF57+] Background Hang Reporter
user_pref("toolkit.telemetry.firstShutdownPing.enabled", false); // [FF57+]
/* 0331: disable Telemetry Coverage
* [1] https://blog.mozilla.org/data/2018/08/20/effectively-measuring-search-in-firefox/ ***/
user_pref("toolkit.telemetry.coverage.opt-out", true); // [HIDDEN PREF]
user_pref("toolkit.coverage.opt-out", true); // [FF64+] [HIDDEN PREF]
user_pref("toolkit.coverage.endpoint.base", "");
/* 0340: disable Health Reports
* [SETTING] Privacy & Security>Firefox Data Collection & Use>Allow Firefox to send technical... data ***/
user_pref("datareporting.healthreport.uploadEnabled", false);
/* 0341: disable new data submission, master kill switch [FF41+]
* If disabled, no policy is shown or upload takes place, ever
* [1] https://bugzilla.mozilla.org/1195552 ***/
user_pref("datareporting.policy.dataSubmissionEnabled", false);
/* 0342: disable Studies (see 0503)
* [SETTING] Privacy & Security>Firefox Data Collection & Use>Allow Firefox to install and run studies ***/
user_pref("app.shield.optoutstudies.enabled", false);
/* 0343: disable personalized Extension Recommendations in about:addons and AMO [FF65+]
* [NOTE] This pref has no effect when Health Reports (0340) are disabled
* [SETTING] Privacy & Security>Firefox Data Collection & Use>Allow Firefox to make personalized extension recommendations
* [1] https://support.mozilla.org/kb/personalized-extension-recommendations ***/
user_pref("browser.discovery.enabled", false);
/* 0350: disable Crash Reports ***/
user_pref("breakpad.reportURL", "");
user_pref("browser.tabs.crashReporting.sendReport", false); // [FF44+]
// user_pref("browser.crashReports.unsubmittedCheck.enabled", false); // [FF51+] [DEFAULT: false]
/* 0351: enforce no submission of backlogged Crash Reports [FF58+]
* [SETTING] Privacy & Security>Firefox Data Collection & Use>Allow Firefox to send backlogged crash reports ***/
user_pref("browser.crashReports.unsubmittedCheck.autoSubmit2", false); // [DEFAULT: false]
/* 0390: disable Captive Portal detection
* [1] https://www.eff.org/deeplinks/2017/08/how-captive-portals-interfere-wireless-security-and-privacy
* [2] https://wiki.mozilla.org/Necko/CaptivePortal ***/
user_pref("captivedetect.canonicalURL", "");
user_pref("network.captive-portal-service.enabled", false); // [FF52+]
/* 0391: disable Network Connectivity checks [FF65+]
* [1] https://bugzilla.mozilla.org/1460537 ***/
user_pref("network.connectivity-service.enabled", false);
/*** [SECTION 0400]: BLOCKLISTS / SAFE BROWSING (SB) ***/
user_pref("_user.js.parrot", "0400 syntax error: the parrot's passed on!");
/** BLOCKLISTS ***/
/* 0401: enforce Firefox blocklist
* [NOTE] It includes updates for "revoked certificates"
* [1] https://blog.mozilla.org/security/2015/03/03/revoking-intermediate-certificates-introducing-onecrl/ ***/
user_pref("extensions.blocklist.enabled", true); // [DEFAULT: true]
/** SAFE BROWSING (SB)
Safe Browsing has taken many steps to preserve privacy. *IF* required, a full url is never
sent to Google, only a PART-hash of the prefix, and this is hidden with noise of other real
PART-hashes. Google also swear it is anonymized and only used to flag malicious sites.
Firefox also takes measures such as striping out identifying parameters and since SBv4 (FF57+)
doesn't even use cookies. (#Turn on browser.safebrowsing.debug to monitor this activity)
#Required reading [#] https://feeding.cloud.geek.nz/posts/how-safe-browsing-works-in-firefox/
[1] https://wiki.mozilla.org/Security/Safe_Browsing
[2] https://support.mozilla.org/en-US/kb/how-does-phishing-and-malware-protection-work
***/
/* 0410: disable SB (Safe Browsing)
* [WARNING] Do this at your own risk! These are the master switches.
* [SETTING] Privacy & Security>Security>... "Block dangerous and deceptive content" ***/
// user_pref("browser.safebrowsing.malware.enabled", false);
// user_pref("browser.safebrowsing.phishing.enabled", false);
/* 0411: disable SB checks for downloads (both local lookups + remote)
* This is the master switch for the safebrowsing.downloads* prefs (0412, 0413)
* [SETTING] Privacy & Security>Security>... "Block dangerous downloads" ***/
// user_pref("browser.safebrowsing.downloads.enabled", false);
/* 0412: disable SB checks for downloads (remote)
* To verify the safety of certain executable files, Firefox may submit some information about the
* file, including the name, origin, size and a cryptographic hash of the contents, to the Google
* Safe Browsing service which helps Firefox determine whether or not the file should be blocked
* [SETUP-SECURITY] If you do not understand this, or you want this protection, then override it ***/
user_pref("browser.safebrowsing.downloads.remote.enabled", false);
user_pref("browser.safebrowsing.downloads.remote.url", "");
/* 0413: disable SB checks for unwanted software
* [SETTING] Privacy & Security>Security>... "Warn you about unwanted and uncommon software" ***/
// user_pref("browser.safebrowsing.downloads.remote.block_potentially_unwanted", false);
// user_pref("browser.safebrowsing.downloads.remote.block_uncommon", false);
/* 0419: disable 'ignore this warning' on SB warnings [FF45+]
* If clicked, it bypasses the block for that session. This is a means for admins to enforce SB
* [TEST] see github wiki APPENDIX A: Test Sites: Section 5
* [1] https://bugzilla.mozilla.org/1226490 ***/
// user_pref("browser.safebrowsing.allowOverride", false);
/*** [SECTION 0500]: SYSTEM ADD-ONS / EXPERIMENTS
System Add-ons are a method for shipping extensions, considered to be
built-in features to Firefox, that are hidden from the about:addons UI.
To view your System Add-ons go to about:support, they are listed under "Firefox Features"
Some System Add-ons have no on-off prefs. Instead you can manually remove them. Note that app
updates will restore them. They may also be updated and possibly restored automatically (see 0505)
* Portable: "...\App\Firefox64\browser\features\" (or "App\Firefox\etc" for 32bit)
* Windows: "...\Program Files\Mozilla\browser\features" (or "Program Files (X86)\etc" for 32bit)
* Mac: "...\Applications\Firefox\Contents\Resources\browser\features\"
[NOTE] On Mac you can right-click on the application and select "Show Package Contents"
* Linux: "/usr/lib/firefox/browser/features" (or similar)
[1] https://firefox-source-docs.mozilla.org/toolkit/mozapps/extensions/addon-manager/SystemAddons.html
[2] https://dxr.mozilla.org/mozilla-central/source/browser/extensions
***/
user_pref("_user.js.parrot", "0500 syntax error: the parrot's cashed in 'is chips!");
/* 0503: disable Normandy/Shield [FF60+]
* Shield is an telemetry system (including Heartbeat) that can also push and test "recipes"
* [1] https://wiki.mozilla.org/Firefox/Shield
* [2] https://github.com/mozilla/normandy ***/
user_pref("app.normandy.enabled", false);
user_pref("app.normandy.api_url", "");
/* 0505: disable System Add-on updates ***/
user_pref("extensions.systemAddon.update.enabled", false); // [FF62+]
user_pref("extensions.systemAddon.update.url", ""); // [FF44+]
/* 0506: disable PingCentre telemetry (used in several System Add-ons) [FF57+]
* Currently blocked by 'datareporting.healthreport.uploadEnabled' (see 0340) ***/
user_pref("browser.ping-centre.telemetry", false);
/* 0515: disable Screenshots ***/
// user_pref("extensions.screenshots.disabled", true); // [FF55+]
/* 0517: disable Form Autofill
* [NOTE] Stored data is NOT secure (uses a JSON file)
* [NOTE] Heuristics controls Form Autofill on forms without @autocomplete attributes
* [SETTING] Privacy & Security>Forms and Autofill>Autofill addresses
* [1] https://wiki.mozilla.org/Firefox/Features/Form_Autofill ***/
user_pref("extensions.formautofill.addresses.enabled", false); // [FF55+]
user_pref("extensions.formautofill.available", "off"); // [FF56+]
user_pref("extensions.formautofill.creditCards.available", false); // [FF57+]
user_pref("extensions.formautofill.creditCards.enabled", false); // [FF56+]
user_pref("extensions.formautofill.heuristics.enabled", false); // [FF55+]
/* 0518: enforce disabling of Web Compatibility Reporter [FF56+]
* Web Compatibility Reporter adds a "Report Site Issue" button to send data to Mozilla ***/
user_pref("extensions.webcompat-reporter.enabled", false); // [DEFAULT: false]
/*** [SECTION 0600]: BLOCK IMPLICIT OUTBOUND [not explicitly asked for - e.g. clicked on] ***/
user_pref("_user.js.parrot", "0600 syntax error: the parrot's no more!");
/* 0601: disable link prefetching
* [1] https://developer.mozilla.org/docs/Web/HTTP/Link_prefetching_FAQ ***/
user_pref("network.prefetch-next", false);
/* 0602: disable DNS prefetching
* [1] https://developer.mozilla.org/docs/Web/HTTP/Headers/X-DNS-Prefetch-Control ***/
user_pref("network.dns.disablePrefetch", true);
user_pref("network.dns.disablePrefetchFromHTTPS", true); // [DEFAULT: true]
/* 0603: disable predictor / prefetching ***/
user_pref("network.predictor.enabled", false);
user_pref("network.predictor.enable-prefetch", false); // [FF48+] [DEFAULT: false]
/* 0605: disable link-mouseover opening connection to linked server
* [1] https://news.slashdot.org/story/15/08/14/2321202/how-to-quash-firefoxs-silent-requests ***/
user_pref("network.http.speculative-parallel-limit", 0);
/* 0606: enforce no "Hyperlink Auditing" (click tracking)
* [1] https://www.bleepingcomputer.com/news/software/major-browsers-to-prevent-disabling-of-click-tracking-privacy-risk/ ***/
user_pref("browser.send_pings", false); // [DEFAULT: false]
user_pref("browser.send_pings.require_same_host", true); // defense-in-depth
/*** [SECTION 0700]: HTTP* / TCP/IP / DNS / PROXY / SOCKS etc ***/
user_pref("_user.js.parrot", "0700 syntax error: the parrot's given up the ghost!");
/* 0701: disable IPv6
* IPv6 can be abused, especially with MAC addresses, and can leak with VPNs. That's even
* assuming your ISP and/or router and/or website can handle it. Sites will fall back to IPv4
* [STATS] Firefox telemetry (Dec 2020) shows ~8% of all connections are IPv6
* [NOTE] This is just an application level fallback. Disabling IPv6 is best done at an
* OS/network level, and/or configured properly in VPN setups. If you are not masking your IP,
* then this won't make much difference. If you are masking your IP, then it can only help.
* [NOTE] PHP defaults to IPv6 with "localhost". Use "php -S 127.0.0.1:PORT"
* [TEST] https://ipleak.org/
* [1] https://www.internetsociety.org/tag/ipv6-security/ (see Myths 2,4,5,6) ***/
user_pref("network.dns.disableIPv6", true);
/* 0702: disable HTTP2
* HTTP2 raises concerns with "multiplexing" and "server push", does nothing to
* enhance privacy, and opens up a number of server-side fingerprinting opportunities.
* [WARNING] Disabling this made sense in the past, and doesn't break anything, but HTTP2 is
* at 40% (December 2019) and growing [5]. Don't be that one person using HTTP1.1 on HTTP2 sites
* [1] https://http2.github.io/faq/
* [2] https://blog.scottlogic.com/2014/11/07/http-2-a-quick-look.html
* [3] https://http2.github.io/http2-spec/#rfc.section.10.8
* [4] https://queue.acm.org/detail.cfm?id=2716278
* [5] https://w3techs.com/technologies/details/ce-http2/all/all ***/
// user_pref("network.http.spdy.enabled", false);
// user_pref("network.http.spdy.enabled.deps", false);
// user_pref("network.http.spdy.enabled.http2", false);
// user_pref("network.http.spdy.websockets", false); // [FF65+]
/* 0703: disable HTTP Alternative Services [FF37+]
* [SETUP-PERF] Relax this if you have FPI enabled (see 4000) *AND* you understand the
* consequences. FPI isolates these, but it was designed with the Tor protocol in mind,
* and the Tor Browser has extra protection, including enhanced sanitizing per Identity.
* [1] https://tools.ietf.org/html/rfc7838#section-9
* [2] https://www.mnot.net/blog/2016/03/09/alt-svc ***/
user_pref("network.http.altsvc.enabled", false);
user_pref("network.http.altsvc.oe", false);
/* 0704: enforce the proxy server to do any DNS lookups when using SOCKS
* e.g. in Tor, this stops your local DNS server from knowing your Tor destination
* as a remote Tor node will handle the DNS request
* [1] https://trac.torproject.org/projects/tor/wiki/doc/TorifyHOWTO/WebBrowsers ***/
user_pref("network.proxy.socks_remote_dns", true);
/* 0708: disable FTP [FF60+] ***/
// user_pref("network.ftp.enabled", false); // [DEFAULT: false FF88+]
/* 0709: disable using UNC (Uniform Naming Convention) paths [FF61+]
* [SETUP-CHROME] Can break extensions for profiles on network shares
* [1] https://gitlab.torproject.org/tpo/applications/tor-browser/-/issues/26424 ***/
user_pref("network.file.disable_unc_paths", true); // [HIDDEN PREF]
/* 0710: disable GIO as a potential proxy bypass vector
* Gvfs/GIO has a set of supported protocols like obex, network, archive, computer, dav, cdda,
* gphoto2, trash, etc. By default only smb and sftp protocols are accepted so far (as of FF64)
* [1] https://bugzilla.mozilla.org/1433507
* [2] https://gitlab.torproject.org/tpo/applications/tor-browser/-/issues/23044
* [3] https://en.wikipedia.org/wiki/GVfs
* [4] https://en.wikipedia.org/wiki/GIO_(software) ***/
user_pref("network.gio.supported-protocols", ""); // [HIDDEN PREF]
/*** [SECTION 0800]: LOCATION BAR / SEARCH BAR / SUGGESTIONS / HISTORY / FORMS
Change items 0850 and above to suit for privacy vs convenience and functionality. Consider
your environment (no unwanted eyeballs), your device (restricted access), your device's
unattended state (locked, encrypted, forensic hardened). Likewise, you may want to check
the items cleared on shutdown in section 2800.
[NOTE] The urlbar is also commonly referred to as the location bar and address bar
#Required reading [#] https://xkcd.com/538/
***/
user_pref("_user.js.parrot", "0800 syntax error: the parrot's ceased to be!");
/* 0801: disable location bar using search
* Don't leak URL typos to a search engine, give an error message instead.
* Examples: "secretplace,com", "secretplace/com", "secretplace com", "secret place.com"
* [NOTE] This does **not** affect explicit user action such as using search buttons in the
* dropdown, or using keyword search shortcuts you configure in options (e.g. 'd' for DuckDuckGo)
* [SETUP-CHROME] If you don't, or rarely, type URLs, or you use a default search
* engine that respects privacy, then you probably don't need this ***/
user_pref("keyword.enabled", false);
/* 0802: disable location bar domain guessing
* domain guessing intercepts DNS "hostname not found errors" and resends a
* request (e.g. by adding www or .com). This is inconsistent use (e.g. FQDNs), does not work
* via Proxy Servers (different error), is a flawed use of DNS (TLDs: why treat .com
* as the 411 for DNS errors?), privacy issues (why connect to sites you didn't
* intend to), can leak sensitive data (e.g. query strings: e.g. Princeton attack),
* and is a security risk (e.g. common typos & malicious sites set up to exploit this) ***/
user_pref("browser.fixup.alternate.enabled", false);
/* 0803: display all parts of the url in the location bar ***/
user_pref("browser.urlbar.trimURLs", false);
/* 0805: disable coloring of visited links - CSS history leak
* [SETUP-HARDEN] Bulk rapid history sniffing was mitigated in 2010 [1][2]. Slower and more expensive
* redraw timing attacks were largely mitigated in FF77+ [3]. Using RFP (4501) further hampers timing
* attacks. Don't forget clearing history on close (2803). However, social engineering [2#limits][4][5]
* and advanced targeted timing attacks could still produce usable results
* [1] https://developer.mozilla.org/docs/Web/CSS/Privacy_and_the_:visited_selector
* [2] https://dbaron.org/mozilla/visited-privacy
* [3] https://bugzilla.mozilla.org/1632765
* [4] https://earthlng.github.io/testpages/visited_links.html (see github wiki APPENDIX A on how to use)
* [5] https://lcamtuf.blogspot.com/2016/08/css-mix-blend-mode-is-bad-for-keeping.html ***/
// user_pref("layout.css.visited_links_enabled", false);
/* 0807: disable live search suggestions
/* [NOTE] Both must be true for the location bar to work
* [SETUP-CHROME] Change these if you trust and use a privacy respecting search engine
* [SETTING] Search>Provide search suggestions | Show search suggestions in address bar results ***/
user_pref("browser.search.suggest.enabled", false);
user_pref("browser.urlbar.suggest.searches", false);
/* 0810: disable location bar making speculative connections [FF56+]
* [1] https://bugzilla.mozilla.org/1348275 ***/
user_pref("browser.urlbar.speculativeConnect.enabled", false);
/* 0811: disable location bar leaking single words to a DNS provider **after searching** [FF78+]
* 0=never resolve single words, 1=heuristic (default), 2=always resolve
* [NOTE] For FF78 value 1 and 2 are the same and always resolve but that will change in future versions
* [1] https://bugzilla.mozilla.org/1642623 ***/
user_pref("browser.urlbar.dnsResolveSingleWordsAfterSearch", 0);
/* 0850a: disable location bar suggestion types
* [SETTING] Privacy & Security>Address Bar>When using the address bar, suggest ***/
// user_pref("browser.urlbar.suggest.history", false);
// user_pref("browser.urlbar.suggest.bookmark", false);
// user_pref("browser.urlbar.suggest.openpage", false);
// user_pref("browser.urlbar.suggest.topsites", false); // [FF78+]
/* 0850b: disable tab-to-search [FF85+]
* Alternatively, you can exclude on a per-engine basis by unchecking them in Options>Search
* [SETTING] Privacy & Security>Address Bar>When using the address bar, suggest>Search engines ***/
// user_pref("browser.urlbar.suggest.engines", false);
/* 0850c: disable location bar dropdown
* This value controls the total number of entries to appear in the location bar dropdown ***/
// user_pref("browser.urlbar.maxRichResults", 0);
/* 0850d: disable location bar autofill
* [1] https://support.mozilla.org/en-US/kb/address-bar-autocomplete-firefox#w_url-autocomplete ***/
// user_pref("browser.urlbar.autoFill", false);
/* 0860: disable search and form history
* [SETUP-WEB] Be aware that autocomplete form data can be read by third parties [1][2]
* [NOTE] We also clear formdata on exit (see 2803)
* [SETTING] Privacy & Security>History>Custom Settings>Remember search and form history
* [1] https://blog.mindedsecurity.com/2011/10/autocompleteagain.html
* [2] https://bugzilla.mozilla.org/381681 ***/
user_pref("browser.formfill.enable", false);
/* 0862: disable browsing and download history
* [NOTE] We also clear history and downloads on exiting Firefox (see 2803)
* [SETTING] Privacy & Security>History>Custom Settings>Remember browsing and download history ***/
// user_pref("places.history.enabled", false);
/* 0870: disable Windows jumplist [WINDOWS] ***/
user_pref("browser.taskbar.lists.enabled", false);
user_pref("browser.taskbar.lists.frequent.enabled", false);
user_pref("browser.taskbar.lists.recent.enabled", false);
user_pref("browser.taskbar.lists.tasks.enabled", false);
/* 0871: disable Windows taskbar preview [WINDOWS] ***/
// user_pref("browser.taskbar.previews.enable", false); // [DEFAULT: false]
/*** [SECTION 0900]: PASSWORDS ***/
user_pref("_user.js.parrot", "0900 syntax error: the parrot's expired!");
/* 0901: disable saving passwords
* [NOTE] This does not clear any passwords already saved
* [SETTING] Privacy & Security>Logins and Passwords>Ask to save logins and passwords for websites ***/
// user_pref("signon.rememberSignons", false);
/* 0902: use a primary password
* There are no preferences for this. It is all handled internally.
* [SETTING] Privacy & Security>Logins and Passwords>Use a Primary Password
* [1] https://support.mozilla.org/kb/use-primary-password-protect-stored-logins-and-pas ***/
/* 0903: set how often Firefox should ask for the primary password
* 0=the first time (default), 1=every time it's needed, 2=every n minutes (see 0904) ***/
user_pref("security.ask_for_password", 2);
/* 0904: set how often in minutes Firefox should ask for the primary password (see 0903)
* in minutes, default is 30 ***/
user_pref("security.password_lifetime", 5);
/* 0905: disable auto-filling username & password form fields
* can leak in cross-site forms *and* be spoofed
* [NOTE] Username & password is still available when you enter the field
* [SETTING] Privacy & Security>Logins and Passwords>Autofill logins and passwords
* [1] https://freedom-to-tinker.com/2017/12/27/no-boundaries-for-user-identities-web-trackers-exploit-browser-login-managers/ ***/
user_pref("signon.autofillForms", false);
/* 0909: disable formless login capture for Password Manager [FF51+] ***/
user_pref("signon.formlessCapture.enabled", false);
/* 0912: limit (or disable) HTTP authentication credentials dialogs triggered by sub-resources [FF41+]
* hardens against potential credentials phishing
* 0=don't allow sub-resources to open HTTP authentication credentials dialogs
* 1=don't allow cross-origin sub-resources to open HTTP authentication credentials dialogs
* 2=allow sub-resources to open HTTP authentication credentials dialogs (default) ***/
user_pref("network.auth.subresource-http-auth-allow", 1);
/*** [SECTION 1000]: CACHE / SESSION (RE)STORE / FAVICONS
Cache tracking/fingerprinting techniques [1][2][3] require a cache. Disabling disk (1001)
*and* memory (1003) caches is one solution; but that's extreme and fingerprintable. A hardened
Temporary Containers configuration can effectively do the same thing, by isolating every tab [4].
We consider avoiding disk cache (1001) so cache is session/memory only (like Private Browsing
mode), and isolating cache to first party (4001) is sufficient and a good balance between
risk and performance. ETAGs can also be neutralized by modifying response headers [5], and
you can clear the cache manually or on a regular basis with an extension.
[1] https://en.wikipedia.org/wiki/HTTP_ETag#Tracking_using_ETags
[2] https://robertheaton.com/2014/01/20/cookieless-user-tracking-for-douchebags/
[3] https://www.grepular.com/Preventing_Web_Tracking_via_the_Browser_Cache
[4] https://medium.com/@stoically/enhance-your-privacy-in-firefox-with-temporary-containers-33925cd6cd21
[5] https://github.com/arkenfox/user.js/wiki/4.2.4-Header-Editor
***/
user_pref("_user.js.parrot", "1000 syntax error: the parrot's gone to meet 'is maker!");
/** CACHE ***/
/* 1001: disable disk cache
* [SETUP-PERF] If you think disk cache may help (heavy tab user, high-res video),
* or you use a hardened Temporary Containers, then feel free to override this
* [NOTE] We also clear cache on exiting Firefox (see 2803) ***/
user_pref("browser.cache.disk.enable", false);
/* 1003: disable memory cache
* capacity: -1=determine dynamically (default), 0=none, n=memory capacity in kibibytes ***/
// user_pref("browser.cache.memory.enable", false);
// user_pref("browser.cache.memory.capacity", 0);
/* 1006: disable permissions manager from writing to disk [RESTART]
* [NOTE] This means any permission changes are session only
* [1] https://bugzilla.mozilla.org/967812 ***/
// user_pref("permissions.memory_only", true); // [HIDDEN PREF]
/* 1007: disable media cache from writing to disk in Private Browsing
* [NOTE] MSE (Media Source Extensions) are already stored in-memory in PB
* [SETUP-WEB] ESR78: playback might break on subsequent loading (1650281) ***/
user_pref("browser.privatebrowsing.forceMediaMemoryCache", true); // [FF75+]
user_pref("media.memory_cache_max_size", 65536);
/** SESSIONS & SESSION RESTORE ***/
/* 1020: exclude "Undo Closed Tabs" in Session Restore ***/
// user_pref("browser.sessionstore.max_tabs_undo", 0);
/* 1021: disable storing extra session data [SETUP-CHROME]
* extra session data contains contents of forms, scrollbar positions, cookies and POST data
* define on which sites to save extra session data:
* 0=everywhere, 1=unencrypted sites, 2=nowhere ***/
user_pref("browser.sessionstore.privacy_level", 2);
/* 1022: disable resuming session from crash ***/
// user_pref("browser.sessionstore.resume_from_crash", false);
/* 1023: set the minimum interval between session save operations
* Increasing this can help on older machines and some websites, as well as reducing writes [1]
* Default is 15000 (15 secs). Try 30000 (30 secs), 60000 (1 min) etc
* [SETUP-CHROME] This can also affect entries in the "Recently Closed Tabs" feature:
* i.e. the longer the interval the more chance a quick tab open/close won't be captured.
* This longer interval *may* affect history but we cannot replicate any history not recorded
* [1] https://bugzilla.mozilla.org/1304389 ***/
user_pref("browser.sessionstore.interval", 30000);
/* 1024: disable automatic Firefox start and session restore after reboot [FF62+] [WINDOWS]
* [1] https://bugzilla.mozilla.org/603903 ***/
user_pref("toolkit.winRegisterApplicationRestart", false);
/** FAVICONS ***/
/* 1030: disable favicons in shortcuts
* URL shortcuts use a cached randomly named .ico file which is stored in your
* profile/shortcutCache directory. The .ico remains after the shortcut is deleted.
* If set to false then the shortcuts use a generic Firefox icon ***/
user_pref("browser.shell.shortcutFavicons", false);
/* 1031: disable favicons in history and bookmarks
* Stored as data blobs in favicons.sqlite, these don't reveal anything that your
* actual history (and bookmarks) already do. Your history is more detailed, so
* control that instead; e.g. disable history, clear history on close, use PB mode
* [NOTE] favicons.sqlite is sanitized on Firefox close, not in-session ***/
// user_pref("browser.chrome.site_icons", false);
/* 1032: disable favicons in web notifications ***/
// user_pref("alerts.showFavicons", false); // [DEFAULT: false]
/*** [SECTION 1200]: HTTPS (SSL/TLS / OCSP / CERTS / HPKP / CIPHERS)
Your cipher and other settings can be used in server side fingerprinting
[TEST] https://www.ssllabs.com/ssltest/viewMyClient.html
[TEST] https://browserleaks.com/ssl
[TEST] https://ja3er.com/
[1] https://www.securityartwork.es/2017/02/02/tls-client-fingerprinting-with-bro/
***/
user_pref("_user.js.parrot", "1200 syntax error: the parrot's a stiff!");
/** SSL (Secure Sockets Layer) / TLS (Transport Layer Security) ***/
/* 1201: require safe negotiation
* Blocks connections (SSL_ERROR_UNSAFE_NEGOTIATION) to servers that don't support RFC 5746 [2]
* as they're potentially vulnerable to a MiTM attack [3]. A server without RFC 5746 can be
* safe from the attack if it disables renegotiations but the problem is that the browser can't
* know that. Setting this pref to true is the only way for the browser to ensure there will be
* no unsafe renegotiations on the channel between the browser and the server.
* [STATS] SSL Labs (Dec 2020) reports 99.0% of sites have secure renegotiation [4]
* [1] https://wiki.mozilla.org/Security:Renegotiation
* [2] https://tools.ietf.org/html/rfc5746
* [3] https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2009-3555
* [4] https://www.ssllabs.com/ssl-pulse/ ***/
user_pref("security.ssl.require_safe_negotiation", true);
/* 1202: control TLS versions with min and max
* 1=TLS 1.0, 2=TLS 1.1, 3=TLS 1.2, 4=TLS 1.3
* [WARNING] Leave these at default, otherwise you alter your TLS fingerprint.
* [1] https://www.ssllabs.com/ssl-pulse/ ***/
// user_pref("security.tls.version.min", 3); // [DEFAULT: 3]
// user_pref("security.tls.version.max", 4);
/* 1203: enforce TLS 1.0 and 1.1 downgrades as session only ***/
user_pref("security.tls.version.enable-deprecated", false);
/* 1204: disable SSL session tracking [FF36+]
* SSL Session IDs are unique and last up to 24hrs in Firefox (or longer with prolongation attacks)
* [NOTE] These are not used in PB mode. In normal windows they are isolated when using FPI (4001)
* and/or containers. In FF85+ they are isolated by default (privacy.partition.network_state)
* [WARNING] There are perf and passive fingerprinting costs, for little to no gain. Preventing
* tracking via this method does not address IPs, nor handle any sanitizing of current identifiers
* [1] https://tools.ietf.org/html/rfc5077
* [2] https://bugzilla.mozilla.org/967977
* [3] https://arxiv.org/abs/1810.07304 ***/
// user_pref("security.ssl.disable_session_identifiers", true); // [HIDDEN PREF]
/* 1206: disable TLS1.3 0-RTT (round-trip time) [FF51+]
* [1] https://github.com/tlswg/tls13-spec/issues/1001
* [2] https://blog.cloudflare.com/tls-1-3-overview-and-q-and-a/ ***/
user_pref("security.tls.enable_0rtt_data", false);
/** OCSP (Online Certificate Status Protocol)
#Required reading [#] https://scotthelme.co.uk/revocation-is-broken/ ***/
/* 1210: enable OCSP Stapling
* [1] https://blog.mozilla.org/security/2013/07/29/ocsp-stapling-in-firefox/ ***/
user_pref("security.ssl.enable_ocsp_stapling", true);
/* 1211: control when to use OCSP fetching (to confirm current validity of certificates)
* 0=disabled, 1=enabled (default), 2=enabled for EV certificates only
* OCSP (non-stapled) leaks information about the sites you visit to the CA (cert authority)
* It's a trade-off between security (checking) and privacy (leaking info to the CA)
* [NOTE] This pref only controls OCSP fetching and does not affect OCSP stapling
* [1] https://en.wikipedia.org/wiki/Ocsp ***/
user_pref("security.OCSP.enabled", 1);
/* 1212: set OCSP fetch failures (non-stapled, see 1211) to hard-fail [SETUP-WEB]
* When a CA cannot be reached to validate a cert, Firefox just continues the connection (=soft-fail)
* Setting this pref to true tells Firefox to instead terminate the connection (=hard-fail)
* It is pointless to soft-fail when an OCSP fetch fails: you cannot confirm a cert is still valid (it
* could have been revoked) and/or you could be under attack (e.g. malicious blocking of OCSP servers)
* [1] https://blog.mozilla.org/security/2013/07/29/ocsp-stapling-in-firefox/
* [2] https://www.imperialviolet.org/2014/04/19/revchecking.html ***/
user_pref("security.OCSP.require", true);
/** CERTS / HPKP (HTTP Public Key Pinning) ***/
/* 1220: disable or limit SHA-1 certificates
* 0=all SHA1 certs are allowed
* 1=all SHA1 certs are blocked
* 2=deprecated option that now maps to 1
* 3=only allowed for locally-added roots (e.g. anti-virus)
* 4=only allowed for locally-added roots or for certs in 2015 and earlier
* [SETUP-CHROME] When disabled, some man-in-the-middle devices (e.g. security scanners and
* antivirus products, may fail to connect to HTTPS sites. SHA-1 is *almost* obsolete.
* [1] https://blog.mozilla.org/security/2016/10/18/phasing-out-sha-1-on-the-public-web/ ***/
user_pref("security.pki.sha1_enforcement_level", 1);
/* 1221: disable Windows 8.1's Microsoft Family Safety cert [FF50+] [WINDOWS]
* 0=disable detecting Family Safety mode and importing the root
* 1=only attempt to detect Family Safety mode (don't import the root)
* 2=detect Family Safety mode and import the root
* [1] https://gitlab.torproject.org/tpo/applications/tor-browser/-/issues/21686 ***/
user_pref("security.family_safety.mode", 0);
/* 1222: disable intermediate certificate caching (fingerprinting attack vector) [FF41+] [RESTART]
* [NOTE] This affects login/cert/key dbs. The effect is all credentials are session-only.
* Saved logins and passwords are not available. Reset the pref and restart to return them.
* [1] https://shiftordie.de/blog/2017/02/21/fingerprinting-firefox-users-with-cached-intermediate-ca-certificates-fiprinca/ ***/
// user_pref("security.nocertdb", true); // [HIDDEN PREF]
/* 1223: enforce strict pinning
* PKP (Public Key Pinning) 0=disabled 1=allow user MiTM (such as your antivirus), 2=strict
* [SETUP-WEB] If you rely on an AV (antivirus) to protect your web browsing
* by inspecting ALL your web traffic, then leave at current default=1
* [1] https://gitlab.torproject.org/tpo/applications/tor-browser/-/issues/16206 ***/
user_pref("security.cert_pinning.enforcement_level", 2);
/* 1224: enforce CRLite [FF73+]
* In FF84+ it covers valid certs and in mode 2 doesn't fall back to OCSP
* [1] https://bugzilla.mozilla.org/buglist.cgi?bug_id=1429800,1670985
* [2] https://blog.mozilla.org/security/tag/crlite/ ***/
user_pref("security.remote_settings.crlite_filters.enabled", true);
user_pref("security.pki.crlite_mode", 2);
/** MIXED CONTENT ***/
/* 1240: enforce no insecure active content on https pages
* [1] https://gitlab.torproject.org/tpo/applications/tor-browser/-/issues/21323 ***/
user_pref("security.mixed_content.block_active_content", true); // [DEFAULT: true]
/* 1241: disable insecure passive content (such as images) on https pages [SETUP-WEB] ***/
user_pref("security.mixed_content.block_display_content", true);
/* 1243: block unencrypted requests from Flash on encrypted pages to mitigate MitM attacks [FF59+]
* [1] https://bugzilla.mozilla.org/1190623 ***/
user_pref("security.mixed_content.block_object_subrequest", true);
/* 1244: enable HTTPS-Only mode [FF76+]
* When "https_only_mode" (all windows) is true, "https_only_mode_pbm" (private windows only) is ignored
* [SETTING] to add site exceptions: Padlock>HTTPS-Only mode>On/Off/Off temporarily
* [SETTING] Privacy & Security>HTTPS-Only Mode
* [TEST] http://example.com [upgrade]
* [TEST] http://neverssl.org/ [no upgrade]
* [1] https://bugzilla.mozilla.org/1613063 [META] ***/
user_pref("dom.security.https_only_mode", true); // [FF76+]
// user_pref("dom.security.https_only_mode_pbm", true); // [FF80+]
/* 1245: enable HTTPS-Only mode for local resources [FF77+] ***/
// user_pref("dom.security.https_only_mode.upgrade_local", true);
/* 1246: disable HTTP background requests [FF82+]
* When attempting to upgrade, if the server doesn't respond within 3 seconds, firefox
* sends HTTP requests in order to check if the server supports HTTPS or not.
* This is done to avoid waiting for a timeout which takes 90 seconds
* [1] https://bugzilla.mozilla.org/buglist.cgi?bug_id=1642387,1660945 ***/
user_pref("dom.security.https_only_mode_send_http_background_request", false);
/** CIPHERS [WARNING: do not meddle with your cipher suite: see the section 1200 intro]
* These are all the ciphers still using SHA-1 and CBC which are weaker than the available alternatives. (see "Cipher Suites" in [1])
* Additionally some have other weaknesses like key sizes of 128 (or lower) [2] and/or no Perfect Forward Secrecy [3].
* [1] https://browserleaks.com/ssl
* [2] https://en.wikipedia.org/wiki/Key_size
* [3] https://en.wikipedia.org/wiki/Forward_secrecy
***/
/* 1261: disable 3DES (effective key size < 128 and no PFS)
* [1] https://en.wikipedia.org/wiki/3des#Security
* [2] https://en.wikipedia.org/wiki/Meet-in-the-middle_attack
* [3] https://www-archive.mozilla.org/projects/security/pki/nss/ssl/fips-ssl-ciphersuites.html ***/
// user_pref("security.ssl3.rsa_des_ede3_sha", false);
/* 1264: disable the remaining non-modern cipher suites as of FF78 (in order of preferred by FF) ***/
// user_pref("security.ssl3.ecdhe_ecdsa_aes_256_sha", false);
// user_pref("security.ssl3.ecdhe_ecdsa_aes_128_sha", false);
// user_pref("security.ssl3.ecdhe_rsa_aes_128_sha", false);
// user_pref("security.ssl3.ecdhe_rsa_aes_256_sha", false);
// user_pref("security.ssl3.rsa_aes_128_sha", false); // no PFS
// user_pref("security.ssl3.rsa_aes_256_sha", false); // no PFS
/** UI (User Interface) ***/
/* 1270: display warning on the padlock for "broken security" (if 1201 is false)
* Bug: warning padlock not indicated for subresources on a secure page! [2]
* [1] https://wiki.mozilla.org/Security:Renegotiation
* [2] https://bugzilla.mozilla.org/1353705 ***/
user_pref("security.ssl.treat_unsafe_negotiation_as_broken", true);
/* 1271: control "Add Security Exception" dialog on SSL warnings
* 0=do neither 1=pre-populate url 2=pre-populate url + pre-fetch cert (default)
* [1] https://github.com/pyllyukko/user.js/issues/210 ***/
user_pref("browser.ssl_override_behavior", 1);
/* 1272: display advanced information on Insecure Connection warning pages
* only works when it's possible to add an exception
* i.e. it doesn't work for HSTS discrepancies (https://subdomain.preloaded-hsts.badssl.com/)
* [TEST] https://expired.badssl.com/ ***/
user_pref("browser.xul.error_pages.expert_bad_cert", true);
/* 1273: display "insecure" icon and "Not Secure" text on HTTP sites ***/
// user_pref("security.insecure_connection_icon.enabled", true); // [FF59+] [DEFAULT: true]
user_pref("security.insecure_connection_text.enabled", true); // [FF60+]
/*** [SECTION 1400]: FONTS ***/
user_pref("_user.js.parrot", "1400 syntax error: the parrot's bereft of life!");
/* 1401: disable websites choosing fonts (0=block, 1=allow)
* This can limit most (but not all) JS font enumeration which is a high entropy fingerprinting vector
* [WARNING] **DO NOT USE**: in FF80+ RFP covers this, and non-RFP users should use font vis (4618)
* [SETTING] General>Language and Appearance>Fonts & Colors>Advanced>Allow pages to choose... ***/
// user_pref("browser.display.use_document_fonts", 0);
/* 1403: disable icon fonts (glyphs) and local fallback rendering
* [1] https://bugzilla.mozilla.org/789788
* [2] https://gitlab.torproject.org/legacy/trac/-/issues/8455 ***/
// user_pref("gfx.downloadable_fonts.enabled", false); // [FF41+]
// user_pref("gfx.downloadable_fonts.fallback_delay", -1);
/* 1404: disable rendering of SVG OpenType fonts
* [1] https://wiki.mozilla.org/SVGOpenTypeFonts - iSECPartnersReport recommends to disable this ***/
user_pref("gfx.font_rendering.opentype_svg.enabled", false);
/* 1408: disable graphite
* Graphite has had many critical security issues in the past [1]
* [1] https://www.mozilla.org/security/advisories/mfsa2017-15/#CVE-2017-7778
* [2] https://en.wikipedia.org/wiki/Graphite_(SIL) ***/
user_pref("gfx.font_rendering.graphite.enabled", false);
/* 1409: limit system font exposure to a whitelist [FF52+] [RESTART]
* If the whitelist is empty, then whitelisting is considered disabled and all fonts are allowed
* [NOTE] In FF81+ the whitelist **overrides** RFP's font visibility (see 4618)
* [WARNING] **DO NOT USE**: in FF80+ RFP covers this, and non-RFP users should use font vis (4618)
* [1] https://bugzilla.mozilla.org/1121643 ***/
// user_pref("font.system.whitelist", ""); // [HIDDEN PREF]
/*** [SECTION 1600]: HEADERS / REFERERS
Only *cross domain* referers need controlling: leave 1601, 1602, 1605 and 1606 alone
---
Expect some breakage: Use an extension if you need precise control
---
full URI: https://example.com:8888/foo/bar.html?id=1234
scheme+host+port+path: https://example.com:8888/foo/bar.html
scheme+host+port: https://example.com:8888
---
#Required reading [#] https://feeding.cloud.geek.nz/posts/tweaking-referrer-for-privacy-in-firefox/
***/
user_pref("_user.js.parrot", "1600 syntax error: the parrot rests in peace!");
/* 1601: ALL: control when images/links send a referer
* 0=never, 1=send only when links are clicked, 2=for links and images (default) ***/
// user_pref("network.http.sendRefererHeader", 2);
/* 1602: ALL: control the amount of information to send
* 0=send full URI (default), 1=scheme+host+port+path, 2=scheme+host+port ***/
// user_pref("network.http.referer.trimmingPolicy", 0);
/* 1603: CROSS ORIGIN: control when to send a referer
* 0=always (default), 1=only if base domains match, 2=only if hosts match
* [SETUP-WEB] Known to cause issues with older modems/routers and some sites e.g vimeo, icloud ***/
user_pref("network.http.referer.XOriginPolicy", 2);
/* 1604: CROSS ORIGIN: control the amount of information to send [FF52+]
* 0=send full URI (default), 1=scheme+host+port+path, 2=scheme+host+port ***/
user_pref("network.http.referer.XOriginTrimmingPolicy", 2);
/* 1605: ALL: disable spoofing a referer
* [WARNING] Do not set this to true, as spoofing effectively disables the anti-CSRF
* (Cross-Site Request Forgery) protections that some sites may rely on ***/
// user_pref("network.http.referer.spoofSource", false); // [DEFAULT: false]
/* 1606: ALL: set the default Referrer Policy [FF59+]
* 0=no-referer, 1=same-origin, 2=strict-origin-when-cross-origin, 3=no-referrer-when-downgrade
* [NOTE] This is only a default, it can be overridden by a site-controlled Referrer Policy
* [1] https://www.w3.org/TR/referrer-policy/
* [2] https://developer.mozilla.org/docs/Web/HTTP/Headers/Referrer-Policy
* [3] https://blog.mozilla.org/security/2018/01/31/preventing-data-leaks-by-stripping-path-information-in-http-referrers/
* [4] https://blog.mozilla.org/security/2021/03/22/firefox-87-trims-http-referrers-by-default-to-protect-user-privacy/ ***/
// user_pref("network.http.referer.defaultPolicy", 2); // [DEFAULT: 2 FF87+]
// user_pref("network.http.referer.defaultPolicy.pbmode", 2); // [DEFAULT: 2]
/* 1607: TOR: hide (not spoof) referrer when leaving a .onion domain [FF54+]
* [NOTE] Firefox cannot access .onion sites by default. We recommend you use
* the Tor Browser which is specifically designed for hidden services
* [1] https://bugzilla.mozilla.org/1305144 ***/
user_pref("network.http.referer.hideOnionSource", true);
/* 1610: ALL: enable the DNT (Do Not Track) HTTP header
* [NOTE] DNT is enforced with Enhanced Tracking Protection regardless of this pref
* [SETTING] Privacy & Security>Enhanced Tracking Protection>Send websites a "Do Not Track" signal... ***/
user_pref("privacy.donottrackheader.enabled", true);
/*** [SECTION 1700]: CONTAINERS
If you want to *really* leverage containers, we highly recommend Temporary Containers [2].
Read the article by the extension author [3], and check out the github wiki/repo [4].
[1] https://wiki.mozilla.org/Security/Contextual_Identity_Project/Containers
[2] https://addons.mozilla.org/firefox/addon/temporary-containers/
[3] https://medium.com/@stoically/enhance-your-privacy-in-firefox-with-temporary-containers-33925cd6cd21
[4] https://github.com/stoically/temporary-containers/wiki
***/
user_pref("_user.js.parrot", "1700 syntax error: the parrot's bit the dust!");
/* 1701: enable Container Tabs setting in preferences (see 1702) [FF50+]
* [1] https://bugzilla.mozilla.org/1279029 ***/
user_pref("privacy.userContext.ui.enabled", true);
/* 1702: enable Container Tabs [FF50+]
* [SETTING] General>Tabs>Enable Container Tabs ***/
user_pref("privacy.userContext.enabled", true);
/* 1703: set behaviour on "+ Tab" button to display container menu on left click [FF74+]
* [NOTE] The menu is always shown on long press and right click
* [SETTING] General>Tabs>Enable Container Tabs>Settings>Select a container for each new tab ***/
// user_pref("privacy.userContext.newTabContainerOnLeftClick.enabled", true);
/*** [SECTION 1800]: PLUGINS ***/
user_pref("_user.js.parrot", "1800 syntax error: the parrot's pushing up daisies!");
/* 1803: disable Flash plugin
* 0=deactivated, 1=ask, 2=enabled
* ESR52.x is the last branch to *fully* support NPAPI, FF52+ stable only supports Flash
* [NOTE] You can still override individual sites via site permissions ***/
user_pref("plugin.state.flash", 0);
/* 1820: disable GMP (Gecko Media Plugins)
* [1] https://wiki.mozilla.org/GeckoMediaPlugins ***/
// user_pref("media.gmp-provider.enabled", false);
/* 1825: disable widevine CDM (Content Decryption Module)
* [NOTE] This is covered by the EME master switch (1830) ***/
// user_pref("media.gmp-widevinecdm.enabled", false);
/* 1830: disable all DRM content (EME: Encryption Media Extension)
* [SETUP-WEB] e.g. Netflix, Amazon Prime, Hulu, HBO, Disney+, Showtime, Starz, DirectTV
* [SETTING] General>DRM Content>Play DRM-controlled content
* [1] https://www.eff.org/deeplinks/2017/10/drms-dead-canary-how-we-just-lost-web-what-we-learned-it-and-what-we-need-do-next ***/
user_pref("media.eme.enabled", false);
/*** [SECTION 2000]: MEDIA / CAMERA / MIC ***/
user_pref("_user.js.parrot", "2000 syntax error: the parrot's snuffed it!");
/* 2001: disable WebRTC (Web Real-Time Communication)
* [SETUP-WEB] WebRTC can leak your IP address from behind your VPN, but if this is not
* in your threat model, and you want Real-Time Communication, this is the pref for you
* [1] https://www.privacytools.io/#webrtc ***/
user_pref("media.peerconnection.enabled", false);
/* 2002: limit WebRTC IP leaks if using WebRTC
* In FF70+ these settings match Mode 4 (Mode 3 in older versions) [3]
* [TEST] https://browserleaks.com/webrtc
* [1] https://bugzilla.mozilla.org/buglist.cgi?bug_id=1189041,1297416,1452713
* [2] https://wiki.mozilla.org/Media/WebRTC/Privacy
* [3] https://tools.ietf.org/html/draft-ietf-rtcweb-ip-handling-12#section-5.2 ***/
user_pref("media.peerconnection.ice.default_address_only", true);
user_pref("media.peerconnection.ice.no_host", true); // [FF51+]
user_pref("media.peerconnection.ice.proxy_only_if_behind_proxy", true); // [FF70+]
/* 2010: disable WebGL (Web Graphics Library)
* [SETUP-WEB] When disabled, may break some websites. When enabled, provides high entropy,
* especially with readPixels(). Some of the other entropy is lessened with RFP (see 4501)
* [1] https://www.contextis.com/resources/blog/webgl-new-dimension-browser-exploitation/
* [2] https://security.stackexchange.com/questions/13799/is-webgl-a-security-concern ***/
user_pref("webgl.disabled", true);
user_pref("webgl.enable-webgl2", false);
/* 2012: limit WebGL ***/
// user_pref("webgl.min_capability_mode", true);
user_pref("webgl.disable-fail-if-major-performance-caveat", true); // [DEFAULT: true FF86+]
/* 2022: disable screensharing ***/
user_pref("media.getusermedia.screensharing.enabled", false);
user_pref("media.getusermedia.browser.enabled", false);
user_pref("media.getusermedia.audiocapture.enabled", false);
/* 2024: set a default permission for Camera/Microphone [FF58+]
* 0=always ask (default), 1=allow, 2=block
* [SETTING] to add site exceptions: Ctrl+I>Permissions>Use the Camera/Microphone
* [SETTING] to manage site exceptions: Options>Privacy & Security>Permissions>Camera/Microphone>Settings ***/
// user_pref("permissions.default.camera", 2);
// user_pref("permissions.default.microphone", 2);
/* 2030: disable autoplay of HTML5 media [FF63+]
* 0=Allow all, 1=Block non-muted media (default in FF67+), 2=Prompt (removed in FF66), 5=Block all (FF69+)
* [NOTE] You can set exceptions under site permissions
* [SETTING] Privacy & Security>Permissions>Autoplay>Settings>Default for all websites ***/
// user_pref("media.autoplay.default", 5);
/* 2031: disable autoplay of HTML5 media if you interacted with the site [FF78+]
* 0=sticky (default), 1=transient, 2=user
* Firefox's Autoplay Policy Documentation [PDF] is linked below via SUMO
* [NOTE] If you have trouble with some video sites, then add an exception (see 2030)
* [1] https://support.mozilla.org/questions/1293231 ***/
user_pref("media.autoplay.blocking_policy", 2);
/*** [SECTION 2200]: WINDOW MEDDLING & LEAKS / POPUPS ***/
user_pref("_user.js.parrot", "2200 syntax error: the parrot's 'istory!");
/* 2202: prevent scripts from moving and resizing open windows ***/
user_pref("dom.disable_window_move_resize", true);
/* 2203: open links targeting new windows in a new tab instead
* This stops malicious window sizes and some screen resolution leaks.
* You can still right-click a link and open in a new window.
* [TEST] https://arkenfox.github.io/TZP/tzp.html#screen
* [1] https://gitlab.torproject.org/tpo/applications/tor-browser/-/issues/9881 ***/
user_pref("browser.link.open_newwindow", 3); // 1=most recent window or tab 2=new window, 3=new tab
user_pref("browser.link.open_newwindow.restriction", 0);
/* 2204: disable Fullscreen API (requires user interaction) to prevent screen-resolution leaks
* [NOTE] You can still manually toggle the browser's fullscreen state (F11),
* but this pref will disable embedded video/game fullscreen controls, e.g. youtube
* [TEST] https://arkenfox.github.io/TZP/tzp.html#screen ***/
// user_pref("full-screen-api.enabled", false);
/* 2210: block popup windows
* [SETTING] Privacy & Security>Permissions>Block pop-up windows ***/
user_pref("dom.disable_open_during_load", true);
/* 2212: limit events that can cause a popup [SETUP-WEB]
* default FF86+: "change click dblclick auxclick mousedown mouseup pointerdown pointerup notificationclick reset submit touchend contextmenu ***/
user_pref("dom.popup_allowed_events", "click dblclick mousedown pointerdown");
/*** [SECTION 2300]: WEB WORKERS
A worker is a JS "background task" running in a global context, i.e. it is different from
the current window. Workers can spawn new workers (must be the same origin & scheme),
including service and shared workers. Shared workers can be utilized by multiple scripts and
communicate between browsing contexts (windows/tabs/iframes) and can even control your cache.
[1] Web Workers: https://developer.mozilla.org/docs/Web/API/Web_Workers_API
[2] Worker: https://developer.mozilla.org/docs/Web/API/Worker
[3] Service Worker: https://developer.mozilla.org/docs/Web/API/Service_Worker_API
[4] SharedWorker: https://developer.mozilla.org/docs/Web/API/SharedWorker
[5] ChromeWorker: https://developer.mozilla.org/docs/Web/API/ChromeWorker
[6] Notifications: https://support.mozilla.org/questions/1165867#answer-981820
***/
user_pref("_user.js.parrot", "2300 syntax error: the parrot's off the twig!");
/* 2302: disable service workers [FF32, FF44-compat]
* Service workers essentially act as proxy servers that sit between web apps, and the
* browser and network, are event driven, and can control the web page/site it is associated
* with, intercepting and modifying navigation and resource requests, and caching resources.
* [NOTE] Service worker APIs are hidden (in Firefox) and cannot be used when in PB mode.
* [NOTE] Service workers only run over HTTPS. Service workers have no DOM access.
* [SETUP-WEB] Disabling service workers will break some sites. This pref is required true for
* service worker notifications (2304), push notifications (disabled, 2305) and service worker
* cache (2740). If you enable this pref, then check those settings as well ***/
user_pref("dom.serviceWorkers.enabled", false);
/* 2304: disable Web Notifications
* [NOTE] Web Notifications can also use service workers (2302) and are behind a prompt (2306)
* [1] https://developer.mozilla.org/docs/Web/API/Notifications_API ***/
// user_pref("dom.webnotifications.enabled", false); // [FF22+]
// user_pref("dom.webnotifications.serviceworker.enabled", false); // [FF44+]
/* 2305: disable Push Notifications [FF44+]
* Push is an API that allows websites to send you (subscribed) messages even when the site
* isn't loaded, by pushing messages to your userAgentID through Mozilla's Push Server.
* [NOTE] Push requires service workers (2302) to subscribe to and display, and is behind
* a prompt (2306). Disabling service workers alone doesn't stop Firefox polling the
* Mozilla Push Server. To remove all subscriptions, reset your userAgentID (in about:config
* or on start), and you will get a new one within a few seconds.
* [1] https://support.mozilla.org/en-US/kb/push-notifications-firefox
* [2] https://developer.mozilla.org/en-US/docs/Web/API/Push_API ***/
user_pref("dom.push.enabled", false);
// user_pref("dom.push.userAgentID", "");
/* 2306: set a default permission for Notifications (both 2304 and 2305) [FF58+]
* 0=always ask (default), 1=allow, 2=block
* [NOTE] Best left at default "always ask", fingerprintable via Permissions API
* [SETTING] to add site exceptions: Ctrl+I>Permissions>Receive Notifications
* [SETTING] to manage site exceptions: Options>Privacy & Security>Permissions>Notifications>Settings ***/
// user_pref("permissions.default.desktop-notification", 2);
/*** [SECTION 2400]: DOM (DOCUMENT OBJECT MODEL) & JAVASCRIPT ***/
user_pref("_user.js.parrot", "2400 syntax error: the parrot's kicked the bucket!");
/* 2401: disable website control over browser right-click context menu
* [NOTE] Shift-Right-Click will always bring up the browser right-click context menu ***/
// user_pref("dom.event.contextmenu.enabled", false);
/* 2402: disable website access to clipboard events/content [SETUP-HARDEN]
* [NOTE] This will break some sites' functionality e.g. Outlook, Twitter, Facebook, Wordpress
* This applies to onCut/onCopy/onPaste events - i.e. it requires interaction with the website
* [WARNING] If both 'middlemouse.paste' and 'general.autoScroll' are true (at least one
* is default false) then enabling this pref can leak clipboard content [1]
* [1] https://bugzilla.mozilla.org/1528289 ***/
// user_pref("dom.event.clipboardevents.enabled", false);
/* 2404: disable clipboard commands (cut/copy) from "non-privileged" content [FF41+]
* this disables document.execCommand("cut"/"copy") to protect your clipboard
* [1] https://bugzilla.mozilla.org/1170911 ***/
user_pref("dom.allow_cut_copy", false);
/* 2405: disable "Confirm you want to leave" dialog on page close
* Does not prevent JS leaks of the page close event.
* [1] https://developer.mozilla.org/docs/Web/Events/beforeunload
* [2] https://support.mozilla.org/questions/1043508 ***/
user_pref("dom.disable_beforeunload", true);
/* 2414: disable shaking the screen ***/
user_pref("dom.vibrator.enabled", false);
/* 2420: disable asm.js [FF22+] [SETUP-PERF]
* [1] http://asmjs.org/
* [2] https://www.mozilla.org/security/advisories/mfsa2015-29/
* [3] https://www.mozilla.org/security/advisories/mfsa2015-50/
* [4] https://www.mozilla.org/security/advisories/mfsa2017-01/#CVE-2017-5375
* [5] https://www.mozilla.org/security/advisories/mfsa2017-05/#CVE-2017-5400
* [6] https://rh0dev.github.io/blog/2017/the-return-of-the-jit/ ***/
user_pref("javascript.options.asmjs", false);
/* 2421: disable Ion and baseline JIT to harden against JS exploits [SETUP-HARDEN]
* [NOTE] In FF75+, when **both** Ion and JIT are disabled, **and** the new
* hidden pref is enabled, then Ion can still be used by extensions (1599226)
* [WARNING] Disabling Ion/JIT can cause some site issues and performance loss
* [1] https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2015-0817 ***/
// user_pref("javascript.options.ion", false);
// user_pref("javascript.options.baselinejit", false);
// user_pref("javascript.options.jit_trustedprincipals", true); // [FF75+] [HIDDEN PREF]
/* 2422: disable WebAssembly [FF52+]
* Vulnerabilities have increasingly been found, including those known and fixed
* in native programs years ago [2]. WASM has powerful low-level access, making
* certain attacks (brute-force) and vulnerabilities more possible
* [STATS] ~0.2% of websites, about half of which are for crytopmining / malvertising [2][3]
* [1] https://developer.mozilla.org/docs/WebAssembly
* [2] https://spectrum.ieee.org/tech-talk/telecom/security/more-worries-over-the-security-of-web-assembly
* [3] https://www.zdnet.com/article/half-of-the-websites-using-webassembly-use-it-for-malicious-purposes ***/
user_pref("javascript.options.wasm", false);
/* 2429: enable (limited but sufficient) window.opener protection [FF65+]
* Makes rel=noopener implicit for target=_blank in anchor and area elements when no rel attribute is set ***/
user_pref("dom.targetBlankNoOpener.enabled", true); // [DEFAULT: true FF79+]
/*** [SECTION 2500]: HARDWARE FINGERPRINTING ***/
user_pref("_user.js.parrot", "2500 syntax error: the parrot's shuffled off 'is mortal coil!");
/* 2502: disable Battery Status API
* Initially a Linux issue (high precision readout) that was fixed.
* However, it is still another metric for fingerprinting, used to raise entropy.
* e.g. do you have a battery or not, current charging status, charge level, times remaining etc
* [NOTE] From FF52+ Battery Status API is only available in chrome/privileged code [1]
* [1] https://bugzilla.mozilla.org/1313580 ***/
// user_pref("dom.battery.enabled", false);
/* 2505: disable media device enumeration [FF29+]
* [NOTE] media.peerconnection.enabled should also be set to false (see 2001)
* [1] https://wiki.mozilla.org/Media/getUserMedia
* [2] https://developer.mozilla.org/docs/Web/API/MediaDevices/enumerateDevices ***/
user_pref("media.navigator.enabled", false);
/* 2508: disable hardware acceleration to reduce graphics fingerprinting [SETUP-HARDEN]
* [WARNING] Affects text rendering (fonts will look different), impacts video performance,
* and parts of Quantum that utilize the GPU will also be affected as they are rolled out
* [SETTING] General>Performance>Custom>Use hardware acceleration when available
* [1] https://wiki.mozilla.org/Platform/GFX/HardwareAcceleration ***/
// user_pref("gfx.direct2d.disabled", true); // [WINDOWS]
// user_pref("layers.acceleration.disabled", true);
/* 2510: disable Web Audio API [FF51+]
* [1] https://bugzilla.mozilla.org/1288359 ***/
user_pref("dom.webaudio.enabled", false);
/* 2517: disable Media Capabilities API [FF63+]
* [WARNING] This *may* affect media performance if disabled, no one is sure
* [1] https://github.com/WICG/media-capabilities
* [2] https://wicg.github.io/media-capabilities/#security-privacy-considerations ***/
// user_pref("media.media-capabilities.enabled", false);
/* 2520: disable virtual reality devices
* Optional protection depending on your connected devices
* [1] https://developer.mozilla.org/docs/Web/API/WebVR_API ***/
// user_pref("dom.vr.enabled", false);
/* 2521: set a default permission for Virtual Reality (see 2520) [FF73+]
* 0=always ask (default), 1=allow, 2=block
* [SETTING] to add site exceptions: Ctrl+I>Permissions>Access Virtual Reality Devices
* [SETTING] to manage site exceptions: Options>Privacy & Security>Permissions>Virtual Reality>Settings ***/
// user_pref("permissions.default.xr", 2);
/*** [SECTION 2600]: MISCELLANEOUS ***/
user_pref("_user.js.parrot", "2600 syntax error: the parrot's run down the curtain!");
/* 2601: prevent accessibility services from accessing your browser [RESTART]
* [SETTING] Privacy & Security>Permissions>Prevent accessibility services from accessing your browser (FF80 or lower)
* [1] https://support.mozilla.org/kb/accessibility-services ***/
user_pref("accessibility.force_disabled", 1);
/* 2602: disable sending additional analytics to web servers
* [1] https://developer.mozilla.org/docs/Web/API/Navigator/sendBeacon ***/
user_pref("beacon.enabled", false);
/* 2603: remove temp files opened with an external application
* [1] https://bugzilla.mozilla.org/302433 ***/
user_pref("browser.helperApps.deleteTempFileOnExit", true);
/* 2604: disable page thumbnail collection ***/
user_pref("browser.pagethumbnails.capturing_disabled", true); // [HIDDEN PREF]
/* 2606: disable UITour backend so there is no chance that a remote page can use it ***/
user_pref("browser.uitour.enabled", false);
user_pref("browser.uitour.url", "");
/* 2607: disable various developer tools in browser context
* [SETTING] Devtools>Advanced Settings>Enable browser chrome and add-on debugging toolboxes
* [1] https://github.com/pyllyukko/user.js/issues/179#issuecomment-246468676 ***/
user_pref("devtools.chrome.enabled", false);
/* 2608: reset remote debugging to disabled
* [1] https://gitlab.torproject.org/tpo/applications/tor-browser/-/issues/16222 ***/
user_pref("devtools.debugger.remote-enabled", false); // [DEFAULT: false]
/* 2609: disable MathML (Mathematical Markup Language) [FF51+] [SETUP-HARDEN]
* [TEST] https://arkenfox.github.io/TZP/tzp.html#misc
* [1] https://bugzilla.mozilla.org/1173199 ***/
// user_pref("mathml.disabled", true);
/* 2610: disable in-content SVG (Scalable Vector Graphics) [FF53+]
* [WARNING] Expect breakage incl. youtube player controls. Best left for a "hardened" profile.
* [1] https://bugzilla.mozilla.org/1216893 ***/
// user_pref("svg.disabled", true);
/* 2611: disable middle mouse click opening links from clipboard
* [1] https://gitlab.torproject.org/tpo/applications/tor-browser/-/issues/10089 ***/
user_pref("middlemouse.contentLoadURL", false);
/* 2615: disable websites overriding Firefox's keyboard shortcuts [FF58+]
* 0 (default) or 1=allow, 2=block
* [SETTING] to add site exceptions: Ctrl+I>Permissions>Override Keyboard Shortcuts ***/
// user_pref("permissions.default.shortcuts", 2);
/* 2616: remove special permissions for certain mozilla domains [FF35+]
* [1] resource://app/defaults/permissions ***/
user_pref("permissions.manager.defaultsUrl", "");
/* 2617: remove webchannel whitelist ***/
user_pref("webchannel.allowObject.urlWhitelist", "");
/* 2619: enforce Punycode for Internationalized Domain Names to eliminate possible spoofing
* Firefox has *some* protections, but it is better to be safe than sorry
* [SETUP-WEB] Might be undesirable for non-latin alphabet users since legitimate IDN's are also punycoded
* [TEST] https://www.xn--80ak6aa92e.com/ (www.apple.com)
* [1] https://wiki.mozilla.org/IDN_Display_Algorithm
* [2] https://en.wikipedia.org/wiki/IDN_homograph_attack
* [3] CVE-2017-5383: https://www.mozilla.org/security/advisories/mfsa2017-02/
* [4] https://www.xudongz.com/blog/2017/idn-phishing/ ***/
user_pref("network.IDN_show_punycode", true);
/* 2620: enforce Firefox's built-in PDF reader [SETUP-CHROME]
* This setting controls if the option "Display in Firefox" is available in the setting below
* and by effect controls whether PDFs are handled in-browser or externally ("Ask" or "Open With")
* PROS: pdfjs is lightweight, open source, and as secure/vetted as any pdf reader out there (more than most)
* Exploits are rare (1 serious case in 4 yrs), treated seriously and patched quickly.
* It doesn't break "state separation" of browser content (by not sharing with OS, independent apps).
* It maintains disk avoidance and application data isolation. It's convenient. You can still save to disk.
* CONS: You may prefer a different pdf reader for security reasons
* CAVEAT: JS can still force a pdf to open in-browser by bundling its own code (rare)
* [SETTING] General>Applications>Portable Document Format (PDF) ***/
user_pref("pdfjs.disabled", false); // [DEFAULT: false]
/* 2621: disable links launching Windows Store on Windows 8/8.1/10 [WINDOWS] ***/
user_pref("network.protocol-handler.external.ms-windows-store", false);
/* 2622: enforce no system colors; they can be fingerprinted
* [SETTING] General>Language and Appearance>Fonts and Colors>Colors>Use system colors ***/
user_pref("browser.display.use_system_colors", false); // [DEFAULT: false]
/* 2623: disable permissions delegation [FF73+]
* Currently applies to cross-origin geolocation, camera, mic and screen-sharing
* permissions, and fullscreen requests. Disabling delegation means any prompts
* for these will show/use their correct 3rd party origin
* [1] https://groups.google.com/forum/#!topic/mozilla.dev.platform/BdFOMAuCGW8/discussion ***/
user_pref("permissions.delegation.enabled", false);
/* 2624: enable "window.name" protection [FF82+]
* If a new page from another domain is loaded into a tab, then window.name is set to an empty string. The original
* string is restored if the tab reverts back to the original page. This change prevents some cross-site attacks
* [TEST] https://arkenfox.github.io/TZP/tests/windownamea.html ***/
user_pref("privacy.window.name.update.enabled", true); // [DEFAULT: true FF86+]
/* 2625: disable bypassing 3rd party extension install prompts [FF82+]
* [1] https://bugzilla.mozilla.org/buglist.cgi?bug_id=1659530,1681331 ***/
user_pref("extensions.postDownloadThirdPartyPrompt", false);
/** DOWNLOADS ***/
/* 2650: discourage downloading to desktop
* 0=desktop, 1=downloads (default), 2=last used
* [SETTING] To set your default "downloads": General>Downloads>Save files to ***/
// user_pref("browser.download.folderList", 2);
/* 2651: enforce user interaction for security by always asking where to download
* [SETUP-CHROME] On Android this blocks longtapping and saving images
* [SETTING] General>Downloads>Always ask you where to save files ***/
user_pref("browser.download.useDownloadDir", false);
/* 2652: disable adding downloads to the system's "recent documents" list ***/
user_pref("browser.download.manager.addToRecentDocs", false);
/* 2654: disable "open with" in download dialog [FF50+] [SETUP-HARDEN]
* This is very useful to enable when the browser is sandboxed (e.g. via AppArmor)
* in such a way that it is forbidden to run external applications.
* [WARNING] This may interfere with some users' workflow or methods
* [1] https://bugzilla.mozilla.org/1281959 ***/
// user_pref("browser.download.forbid_open_with", true);
/** EXTENSIONS ***/
/* 2660: lock down allowed extension directories
* [SETUP-CHROME] This will break extensions, language packs, themes and any other
* XPI files which are installed outside of profile and application directories
* [1] https://mike.kaply.com/2012/02/21/understanding-add-on-scopes/
* [1] archived: https://archive.is/DYjAM ***/
user_pref("extensions.enabledScopes", 5); // [HIDDEN PREF]
user_pref("extensions.autoDisableScopes", 15); // [DEFAULT: 15]
/* 2662: disable webextension restrictions on certain mozilla domains (you also need 4503) [FF60+]
* [1] https://bugzilla.mozilla.org/buglist.cgi?bug_id=1384330,1406795,1415644,1453988 ***/
// user_pref("extensions.webextensions.restrictedDomains", "");
/** SECURITY ***/
/* 2680: enforce CSP (Content Security Policy)
* [WARNING] CSP is a very important and widespread security feature. Don't disable it!
* [1] https://developer.mozilla.org/docs/Web/HTTP/CSP ***/
user_pref("security.csp.enable", true); // [DEFAULT: true]
/* 2684: enforce a security delay on some confirmation dialogs such as install, open/save
* [1] https://www.squarefree.com/2004/07/01/race-conditions-in-security-dialogs/ ***/
user_pref("security.dialog_enable_delay", 700);
/*** [SECTION 2700]: PERSISTENT STORAGE
Data SET by websites including
cookies : profile\cookies.sqlite
localStorage : profile\webappsstore.sqlite
indexedDB : profile\storage\default
appCache : profile\OfflineCache
serviceWorkers :
[NOTE] indexedDB and serviceWorkers are not available in Private Browsing Mode
[NOTE] Blocking cookies also blocks websites access to: localStorage (incl. sessionStorage),
indexedDB, sharedWorker, and serviceWorker (and therefore service worker cache and notifications)
If you set a site exception for cookies (either "Allow" or "Allow for Session") then they become
accessible to websites except shared/service workers where the cookie setting *must* be "Allow"
***/
user_pref("_user.js.parrot", "2700 syntax error: the parrot's joined the bleedin' choir invisible!");
/* 2701: disable 3rd-party cookies and site-data [SETUP-WEB]
* 0=Accept cookies and site data, 1=(Block) All third-party cookies, 2=(Block) All cookies,
* 3=(Block) Cookies from unvisited websites, 4=(Block) Cross-site and social media trackers (default)
* [NOTE] You can set exceptions under site permissions or use an extension
* [NOTE] Enforcing category to custom ensures ETP related prefs are always honored
* [SETTING] Privacy & Security>Enhanced Tracking Protection>Custom>Cookies ***/
user_pref("network.cookie.cookieBehavior", 1);
user_pref("browser.contentblocking.category", "custom");
/* 2702: set third-party cookies (if enabled, see 2701) to session-only
[NOTE] .sessionOnly overrides .nonsecureSessionOnly except when .sessionOnly=false and
.nonsecureSessionOnly=true. This allows you to keep HTTPS cookies, but session-only HTTP ones
* [1] https://feeding.cloud.geek.nz/posts/tweaking-cookies-for-privacy-in-firefox/ ***/
user_pref("network.cookie.thirdparty.sessionOnly", true);
user_pref("network.cookie.thirdparty.nonsecureSessionOnly", true); // [FF58+]
/* 2703: delete cookies and site data on close
* 0=keep until they expire (default), 2=keep until you close Firefox
* [NOTE] The setting below is disabled (but not changed) if you block all cookies (2701 = 2)
* [SETTING] Privacy & Security>Cookies and Site Data>Delete cookies and site data when Firefox is closed ***/
// user_pref("network.cookie.lifetimePolicy", 2);
/* 2710: disable DOM (Document Object Model) Storage
* [WARNING] This will break a LOT of sites' functionality AND extensions!
* You are better off using an extension for more granular control ***/
// user_pref("dom.storage.enabled", false);
/* 2730: enforce no offline cache storage (appCache)
* The API is easily fingerprinted, use the "storage" pref instead ***/
// user_pref("browser.cache.offline.enable", false);
user_pref("browser.cache.offline.storage.enable", false); // [FF71+] [DEFAULT: false FF84+]
/* 2740: disable service worker cache and cache storage
* [NOTE] We clear service worker cache on exiting Firefox (see 2803)
* [1] https://w3c.github.io/ServiceWorker/#privacy ***/
// user_pref("dom.caches.enabled", false);
/* 2750: disable Storage API [FF51+]
* The API gives sites the ability to find out how much space they can use, how much
* they are already using, and even control whether or not they need to be alerted
* before the user agent disposes of site data in order to make room for other things.
* [1] https://developer.mozilla.org/docs/Web/API/StorageManager
* [2] https://developer.mozilla.org/docs/Web/API/Storage_API
* [3] https://blog.mozilla.org/l10n/2017/03/07/firefox-l10n-report-aurora-54/ ***/
// user_pref("dom.storageManager.enabled", false);
/* 2755: disable Storage Access API [FF65+]
* [1] https://developer.mozilla.org/en-US/docs/Web/API/Storage_Access_API ***/
// user_pref("dom.storage_access.enabled", false);
/* 2760: enable Local Storage Next Generation (LSNG) [FF65+] ***/
user_pref("dom.storage.next_gen", true);
/*** [SECTION 2800]: SHUTDOWN
You should set the values to what suits you best.
- "Offline Website Data" includes appCache (2730), localStorage (2710),
service worker cache (2740), and QuotaManager (IndexedDB (2720), asm-cache)
- In both 2803 + 2804, the 'download' and 'history' prefs are combined in the
Firefox interface as "Browsing & Download History" and their values will be synced
***/
user_pref("_user.js.parrot", "2800 syntax error: the parrot's bleedin' demised!");
/* 2802: enable Firefox to clear items on shutdown (see 2803)
* [SETTING] Privacy & Security>History>Custom Settings>Clear history when Firefox closes ***/
user_pref("privacy.sanitize.sanitizeOnShutdown", true);
/* 2803: set what items to clear on shutdown (if 2802 is true) [SETUP-CHROME]
* [NOTE] If 'history' is true, downloads will also be cleared regardless of the value
* but if 'history' is false, downloads can still be cleared independently
* However, this may not always be the case. The interface combines and syncs these
* prefs when set from there, and the sanitize code may change at any time
* [SETTING] Privacy & Security>History>Custom Settings>Clear history when Firefox closes>Settings ***/
user_pref("privacy.clearOnShutdown.cache", true);
user_pref("privacy.clearOnShutdown.cookies", true);
user_pref("privacy.clearOnShutdown.downloads", true); // see note above
user_pref("privacy.clearOnShutdown.formdata", true); // Form & Search History
user_pref("privacy.clearOnShutdown.history", true); // Browsing & Download History
user_pref("privacy.clearOnShutdown.offlineApps", true); // Offline Website Data
user_pref("privacy.clearOnShutdown.sessions", true); // Active Logins
user_pref("privacy.clearOnShutdown.siteSettings", false); // Site Preferences
/* 2804: reset default items to clear with Ctrl-Shift-Del (to match 2803) [SETUP-CHROME]
* This dialog can also be accessed from the menu History>Clear Recent History
* Firefox remembers your last choices. This will reset them when you start Firefox.
* [NOTE] Regardless of what you set privacy.cpd.downloads to, as soon as the dialog
* for "Clear Recent History" is opened, it is synced to the same as 'history' ***/
user_pref("privacy.cpd.cache", true);
user_pref("privacy.cpd.cookies", true);
// user_pref("privacy.cpd.downloads", true); // not used, see note above
user_pref("privacy.cpd.formdata", true); // Form & Search History
user_pref("privacy.cpd.history", true); // Browsing & Download History
user_pref("privacy.cpd.offlineApps", true); // Offline Website Data
user_pref("privacy.cpd.passwords", false); // this is not listed
user_pref("privacy.cpd.sessions", true); // Active Logins
user_pref("privacy.cpd.siteSettings", false); // Site Preferences
/* 2805: clear Session Restore data when sanitizing on shutdown or manually [FF34+]
* [NOTE] Not needed if Session Restore is not used (see 0102) or is already cleared with history (see 2803)
* [NOTE] privacy.clearOnShutdown.openWindows prevents resuming from crashes (see 1022)
* [NOTE] privacy.cpd.openWindows has a bug that causes an additional window to open ***/
// user_pref("privacy.clearOnShutdown.openWindows", true);
// user_pref("privacy.cpd.openWindows", true);
/* 2806: reset default 'Time range to clear' for 'Clear Recent History' (see 2804)
* Firefox remembers your last choice. This will reset the value when you start Firefox.
* 0=everything, 1=last hour, 2=last two hours, 3=last four hours,
* 4=today, 5=last five minutes, 6=last twenty-four hours
* [NOTE] The values 5 + 6 are not listed in the dropdown, which will display a
* blank value if they are used, but they do work as advertised ***/
user_pref("privacy.sanitize.timeSpan", 0);
/*** [SECTION 4000]: FPI (FIRST PARTY ISOLATION)
1278037 - indexedDB (FF51+)
1277803 - favicons (FF52+)
1264562 - OCSP cache (FF52+)
1268726 - Shared Workers (FF52+)
1316283 - SSL session cache (FF52+)
1317927 - media cache (FF53+)
1323644 - HSTS and HPKP (FF54+)
1334690 - HTTP Alternative Services (FF54+)
1334693 - SPDY/HTTP2 (FF55+)
1337893 - DNS cache (FF55+)
1344170 - blob: URI (FF55+)
1300671 - data:, about: URLs (FF55+)
1473247 - IP addresses (FF63+)
1492607 - postMessage with targetOrigin "*" (requires 4002) (FF65+)
1542309 - top-level domain URLs when host is in the public suffix list (FF68+)
1506693 - pdfjs range-based requests (FF68+)
1330467 - site permissions (FF69+)
1534339 - IPv6 (FF73+)
***/
user_pref("_user.js.parrot", "4000 syntax error: the parrot's pegged out");
/* 4001: enable First Party Isolation [FF51+]
* [SETUP-WEB] May break cross-domain logins and site functionality until perfected
* [1] https://bugzilla.mozilla.org/buglist.cgi?bug_id=1260931,1299996 ***/
user_pref("privacy.firstparty.isolate", true);
/* 4002: enforce FPI restriction for window.opener [FF54+]
* [NOTE] Setting this to false may reduce the breakage in 4001
* FF65+ blocks postMessage with targetOrigin "*" if originAttributes don't match. But
* to reduce breakage it ignores the 1st-party domain (FPD) originAttribute [2][3]
* The 2nd pref removes that limitation and will only allow communication if FPDs also match.
* [1] https://bugzilla.mozilla.org/1319773#c22
* [2] https://bugzilla.mozilla.org/1492607
* [3] https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage ***/
// user_pref("privacy.firstparty.isolate.restrict_opener_access", true); // [DEFAULT: true]
// user_pref("privacy.firstparty.isolate.block_post_message", true);
/* 4003: enable scheme with FPI [FF78+]
* [NOTE] Experimental: existing data and site permissions are incompatible
* and some site exceptions may not work e.g. HTTPS-only mode (see 1244) ***/
// user_pref("privacy.firstparty.isolate.use_site", true);
/*** [SECTION 4500]: RFP (RESIST FINGERPRINTING)
RFP covers a wide range of ongoing fingerprinting solutions.
It is an all-or-nothing buy in: you cannot pick and choose what parts you want
[WARNING] Do NOT use extensions to alter RFP protected metrics
[WARNING] Do NOT use prefs in section 4600 with RFP as they can interfere
FF41+
418986 - limit window.screen & CSS media queries leaking identifiable info
[TEST] https://arkenfox.github.io/TZP/tzp.html#screen
FF50+
1281949 - spoof screen orientation
1281963 - hide the contents of navigator.plugins and navigator.mimeTypes (FF50+)
FF55+
1330890 - spoof timezone as UTC 0
1360039 - spoof navigator.hardwareConcurrency as 2 (see 4601)
1217238 - reduce precision of time exposed by javascript
FF56+
1369303 - spoof/disable performance API (see 4602, 4603)
1333651 - spoof User Agent & Navigator API (see section 4700)
JS: FF78+ the version is spoofed as 78, and the OS as Windows 10, OS 10.15, Android 9, or Linux
HTTP Headers: spoofed as Windows or Android
1369319 - disable device sensor API (see 4604)
1369357 - disable site specific zoom (see 4605)
1337161 - hide gamepads from content (see 4606)
1372072 - spoof network information API as "unknown" when dom.netinfo.enabled = true (see 4607)
1333641 - reduce fingerprinting in WebSpeech API (see 4608)
FF57+
1369309 - spoof media statistics (see 4610)
1382499 - reduce screen co-ordinate fingerprinting in Touch API (see 4611)
1217290 & 1409677 - enable fingerprinting resistance for WebGL (see 2010-12)
1382545 - reduce fingerprinting in Animation API
1354633 - limit MediaError.message to a whitelist
1382533 - enable fingerprinting resistance for Presentation API
This blocks exposure of local IP Addresses via mDNS (Multicast DNS)
FF58+
967895 - spoof canvas and enable site permission prompt before allowing canvas data extraction
FF59+
1372073 - spoof/block fingerprinting in MediaDevices API
Spoof: enumerate devices reports one "Internal Camera" and one "Internal Microphone" if
media.navigator.enabled is true (see 2505 which we chose to keep disabled)
Block: suppresses the ondevicechange event (see 4612)
1039069 - warn when language prefs are set to non en-US (see 0210, 0211)
1222285 & 1433592 - spoof keyboard events and suppress keyboard modifier events
Spoofing mimics the content language of the document. Currently it only supports en-US.
Modifier events suppressed are SHIFT and both ALT keys. Chrome is not affected.
FF60-67
1337157 - disable WebGL debug renderer info (see 4613) (FF60+)
1459089 - disable OS locale in HTTP Accept-Language headers (ANDROID) (FF62+)
1479239 - return "no-preference" with prefers-reduced-motion (see 4614) (FF63+)
1363508 - spoof/suppress Pointer Events (see 4615) (FF64+)
FF65: pointerEvent.pointerid (1492766)
1485266 - disable exposure of system colors to CSS or canvas (see 4616) (FF67+)
1407366 - enable inner window letterboxing (see 4504) (FF67+)
1494034 - return "light" with prefers-color-scheme (see 4617) (FF67+)
FF68-77
1564422 - spoof audioContext outputLatency (FF70+)
1595823 - spoof audioContext sampleRate (FF72+)
1607316 - spoof pointer as coarse and hover as none (ANDROID) (FF74+)
FF78+
1621433 - randomize canvas (previously FF58+ returned an all-white canvas) (FF78+)
1653987 - limit font visibility to bundled and "Base Fonts" (see 4618) (non-ANDROID) (FF80+)
1461454 - spoof smooth=true and powerEfficient=false for supported media in MediaCapabilities (FF82+)
***/
user_pref("_user.js.parrot", "4500 syntax error: the parrot's popped 'is clogs");
/* 4501: enable privacy.resistFingerprinting [FF41+]
* This pref is the master switch for all other privacy.resist* prefs unless stated
* [SETUP-WEB] RFP can cause the odd website to break in strange ways, and has a few side affects,
* but is largely robust nowadays. Give it a try. Your choice. Also see 4504 (letterboxing).
* [1] https://bugzilla.mozilla.org/418986 ***/
user_pref("privacy.resistFingerprinting", true);
/* 4502: set new window sizes to round to hundreds [FF55+] [SETUP-CHROME]
* Width will round down to multiples of 200s and height to 100s, to fit your screen.
* The override values are a starting point to round from if you want some control
* [1] https://bugzilla.mozilla.org/1330882 ***/
// user_pref("privacy.window.maxInnerWidth", 1000);
// user_pref("privacy.window.maxInnerHeight", 1000);
/* 4503: disable mozAddonManager Web API [FF57+]
* [NOTE] To allow extensions to work on AMO, you also need 2662
* [1] https://bugzilla.mozilla.org/buglist.cgi?bug_id=1384330,1406795,1415644,1453988 ***/
user_pref("privacy.resistFingerprinting.block_mozAddonManager", true); // [HIDDEN PREF]
/* 4504: enable RFP letterboxing [FF67+]
* Dynamically resizes the inner window by applying margins in stepped ranges [2]
* If you use the dimension pref, then it will only apply those resolutions. The format is
* "width1xheight1, width2xheight2, ..." (e.g. "800x600, 1000x1000, 1600x900")
* [SETUP-WEB] This does NOT require RFP (see 4501) **for now**, so if you're not using 4501, or you are but
* dislike margins being applied, then flip this pref, keeping in mind that it is effectively fingerprintable
* [WARNING] The dimension pref is only meant for testing, and we recommend you DO NOT USE it
* [1] https://bugzilla.mozilla.org/1407366
* [2] https://hg.mozilla.org/mozilla-central/rev/6d2d7856e468#l2.32 ***/
user_pref("privacy.resistFingerprinting.letterboxing", true); // [HIDDEN PREF]
// user_pref("privacy.resistFingerprinting.letterboxing.dimensions", ""); // [HIDDEN PREF]
/* 4510: disable showing about:blank as soon as possible during startup [FF60+]
* When default true this no longer masks the RFP chrome resizing activity
* [1] https://bugzilla.mozilla.org/1448423 ***/
user_pref("browser.startup.blankWindow", false);
/* 4520: disable chrome animations [FF77+] [RESTART]
* [NOTE] pref added in FF63, but applied to chrome in FF77. RFP spoofs this for web content ***/
user_pref("ui.prefersReducedMotion", 1); // [HIDDEN PREF]
/*** [SECTION 4600]: RFP ALTERNATIVES
[WARNING] Do NOT use prefs in this section with RFP as they can interfere
***/
user_pref("_user.js.parrot", "4600 syntax error: the parrot's crossed the Jordan");
/* [SETUP-non-RFP] Non-RFP users replace the * with a slash on this line to enable these
// FF55+
// 4601: [2514] spoof (or limit?) number of CPU cores [FF48+]
// [NOTE] *may* affect core chrome/Firefox performance, will affect content.
// [1] https://bugzilla.mozilla.org/1008453
// [2] https://gitlab.torproject.org/tpo/applications/tor-browser/-/issues/21675
// [3] https://gitlab.torproject.org/tpo/applications/tor-browser/-/issues/22127
// [4] https://html.spec.whatwg.org/multipage/workers.html#navigator.hardwareconcurrency
// user_pref("dom.maxHardwareConcurrency", 2);
// * * * /
// FF56+
// 4602: [2411] disable resource/navigation timing
user_pref("dom.enable_resource_timing", false);
// 4603: [2412] disable timing attacks
// [1] https://wiki.mozilla.org/Security/Reviews/Firefox/NavigationTimingAPI
user_pref("dom.enable_performance", false);
// 4604: [2512] disable device sensor API
// Optional protection depending on your device
// [1] https://gitlab.torproject.org/tpo/applications/tor-browser/-/issues/15758
// [2] https://blog.lukaszolejnik.com/stealing-sensitive-browser-data-with-the-w3c-ambient-light-sensor-api/
// [3] https://bugzilla.mozilla.org/buglist.cgi?bug_id=1357733,1292751
// user_pref("device.sensors.enabled", false);
// 4605: [2515] disable site specific zoom
// Zoom levels affect screen res and are highly fingerprintable. This does not stop you using
// zoom, it will just not use/remember any site specific settings. Zoom levels on new tabs
// and new windows are reset to default and only the current tab retains the current zoom
user_pref("browser.zoom.siteSpecific", false);
// 4606: [2501] disable gamepad API - USB device ID enumeration
// Optional protection depending on your connected devices
// [1] https://gitlab.torproject.org/tpo/applications/tor-browser/-/issues/13023
// user_pref("dom.gamepad.enabled", false);
// 4607: [2503] disable giving away network info [FF31+]
// e.g. bluetooth, cellular, ethernet, wifi, wimax, other, mixed, unknown, none
// [1] https://developer.mozilla.org/docs/Web/API/Network_Information_API
// [2] https://wicg.github.io/netinfo/
// [3] https://bugzilla.mozilla.org/960426
user_pref("dom.netinfo.enabled", false); // [DEFAULT: true on Android]
// 4608: [2021] disable the SpeechSynthesis (Text-to-Speech) part of the Web Speech API
// [1] https://developer.mozilla.org/docs/Web/API/Web_Speech_API
// [2] https://developer.mozilla.org/docs/Web/API/SpeechSynthesis
// [3] https://wiki.mozilla.org/HTML5_Speech_API
user_pref("media.webspeech.synth.enabled", false);
// * * * /
// FF57+
// 4610: [2506] disable video statistics - JS performance fingerprinting [FF25+]
// [1] https://gitlab.torproject.org/tpo/applications/tor-browser/-/issues/15757
// [2] https://bugzilla.mozilla.org/654550
user_pref("media.video_stats.enabled", false);
// 4611: [2509] disable touch events
// fingerprinting attack vector - leaks screen res & actual screen coordinates
// 0=disabled, 1=enabled, 2=autodetect
// Optional protection depending on your device
// [1] https://developer.mozilla.org/docs/Web/API/Touch_events
// [2] https://gitlab.torproject.org/tpo/applications/tor-browser/-/issues/10286
// user_pref("dom.w3c_touch_events.enabled", 0);
// * * * /
// FF59+
// 4612: [2511] disable MediaDevices change detection [FF51+]
// [1] https://developer.mozilla.org/docs/Web/Events/devicechange
// [2] https://developer.mozilla.org/docs/Web/API/MediaDevices/ondevicechange
user_pref("media.ondevicechange.enabled", false);
// * * * /
// FF60+
// 4613: [2011] disable WebGL debug info being available to websites
// [1] https://bugzilla.mozilla.org/1171228
// [2] https://developer.mozilla.org/docs/Web/API/WEBGL_debug_renderer_info
user_pref("webgl.enable-debug-renderer-info", false);
// * * * /
// FF63+
// 4614: enforce prefers-reduced-motion as no-preference [FF63+] [RESTART]
// 0=no-preference, 1=reduce
user_pref("ui.prefersReducedMotion", 0); // [HIDDEN PREF]
// FF64+
// 4615: [2516] disable PointerEvents
// [1] https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent
user_pref("dom.w3c_pointer_events.enabled", false);
// * * * /
// FF67+
// 4616: [2618] disable exposure of system colors to CSS or canvas [FF44+]
// [NOTE] See second listed bug: may cause black on black for elements with undefined colors
// [SETUP-CHROME] Might affect CSS in themes and extensions
// [1] https://bugzilla.mozilla.org/buglist.cgi?bug_id=232227,1330876
user_pref("ui.use_standins_for_native_colors", true);
// 4617: enforce prefers-color-scheme as light [FF67+]
// 0=light, 1=dark : This overrides your OS value
user_pref("ui.systemUsesDarkTheme", 0); // [HIDDEN PREF]
// FF80+
// 4618: limit font visibility (non-ANDROID) [FF79+]
// Uses hardcoded lists with two parts: kBaseFonts + kLangPackFonts [1]
// 1=only base system fonts, 2=also fonts from optional language packs, 3=also user-installed fonts
// [NOTE] Bundled fonts are auto-allowed
// [1] https://searchfox.org/mozilla-central/search?path=StandardFonts*.inc
user_pref("layout.css.font-visibility.level", 1);
// * * * /
// ***/
/*** [SECTION 4700]: RFP ALTERNATIVES (USER AGENT SPOOFING)
These prefs are insufficient and leak. Use RFP and **nothing else**
- Many of the user agent components can be derived by other means. When those
values differ, you provide more bits and raise entropy. Examples include
workers, iframes, headers, tcp/ip attributes, feature detection, and many more
- Web extensions also lack APIs to fully protect spoofing
***/
user_pref("_user.js.parrot", "4700 syntax error: the parrot's taken 'is last bow");
/* 4701: navigator DOM object overrides
* [WARNING] DO NOT USE ***/
// user_pref("general.appname.override", ""); // [HIDDEN PREF]
// user_pref("general.appversion.override", ""); // [HIDDEN PREF]
// user_pref("general.buildID.override", ""); // [HIDDEN PREF]
// user_pref("general.oscpu.override", ""); // [HIDDEN PREF]
// user_pref("general.platform.override", ""); // [HIDDEN PREF]
// user_pref("general.useragent.override", ""); // [HIDDEN PREF]
/*** [SECTION 5000]: PERSONAL
Non-project related but useful. If any of these interest you, add them to your overrides ***/
user_pref("_user.js.parrot", "5000 syntax error: this is an ex-parrot!");
/* WELCOME & WHAT's NEW NOTICES ***/
// user_pref("browser.startup.homepage_override.mstone", "ignore"); // master switch
// user_pref("startup.homepage_welcome_url", "");
// user_pref("startup.homepage_welcome_url.additional", "");
// user_pref("startup.homepage_override_url", ""); // What's New page after updates
/* WARNINGS ***/
// user_pref("browser.tabs.warnOnClose", false);
// user_pref("browser.tabs.warnOnCloseOtherTabs", false);
// user_pref("browser.tabs.warnOnOpen", false);
// user_pref("full-screen-api.warning.delay", 0);
// user_pref("full-screen-api.warning.timeout", 0);
/* APPEARANCE ***/
// user_pref("browser.download.autohideButton", false); // [FF57+]
// user_pref("toolkit.legacyUserProfileCustomizations.stylesheets", true); // [FF68+] allow userChrome/userContent
/* CONTENT BEHAVIOR ***/
// user_pref("accessibility.typeaheadfind", true); // enable "Find As You Type"
// user_pref("clipboard.autocopy", false); // disable autocopy default [LINUX]
// user_pref("layout.spellcheckDefault", 2); // 0=none, 1-multi-line, 2=multi-line & single-line
/* UX BEHAVIOR ***/
// user_pref("browser.backspace_action", 2); // 0=previous page, 1=scroll up, 2=do nothing
// user_pref("browser.quitShortcut.disabled", true); // disable Ctrl-Q quit shortcut [LINUX] [MAC] [FF87+]
// user_pref("browser.tabs.closeWindowWithLastTab", false);
// user_pref("browser.tabs.loadBookmarksInTabs", true); // open bookmarks in a new tab [FF57+]
// user_pref("browser.urlbar.decodeURLsOnCopy", true); // see bugzilla 1320061 [FF53+]
// user_pref("general.autoScroll", false); // middle-click enabling auto-scrolling [DEFAULT: false on Linux]
// user_pref("ui.key.menuAccessKey", 0); // disable alt key toggling the menu bar [RESTART]
// user_pref("view_source.tab", false); // view "page/selection source" in a new window [FF68+, FF59 and under]
/* UX FEATURES: disable and hide the icons and menus ***/
// user_pref("browser.messaging-system.whatsNewPanel.enabled", false); // What's New [FF69+]
// user_pref("extensions.pocket.enabled", false); // Pocket Account [FF46+]
// user_pref("identity.fxaccounts.enabled", false); // Firefox Accounts & Sync [FF60+] [RESTART]
// user_pref("reader.parse-on-load.enabled", false); // Reader View
/* OTHER ***/
// user_pref("browser.bookmarks.max_backups", 2);
// user_pref("browser.newtabpage.activity-stream.asrouter.userprefs.cfr.addons", false); // disable CFR [FF67+]
// [SETTING] General>Browsing>Recommend extensions as you browse
// user_pref("browser.newtabpage.activity-stream.asrouter.userprefs.cfr.features", false); // disable CFR [FF67+]
// [SETTING] General>Browsing>Recommend features as you browse
// user_pref("network.manage-offline-status", false); // see bugzilla 620472
// user_pref("xpinstall.signatures.required", false); // enforced extension signing (Nightly/ESR)
/*** [SECTION 9999]: DEPRECATED / REMOVED / LEGACY / RENAMED
Documentation denoted as [-]. Items deprecated in FF78 or earlier have been archived at [1],
which also provides a link-clickable, viewer-friendly version of the deprecated bugzilla tickets
[1] https://github.com/arkenfox/user.js/issues/123
***/
user_pref("_user.js.parrot", "9999 syntax error: the parrot's deprecated!");
/* ESR78.x still uses all the following prefs
// [NOTE] replace the * with a slash in the line above to re-enable them
// FF79
// 0212: enforce fallback text encoding to match en-US
// When the content or server doesn't declare a charset the browser will
// fallback to the "Current locale" based on your application language
// [TEST] https://hsivonen.com/test/moz/check-charset.htm
// [1] https://gitlab.torproject.org/tpo/applications/tor-browser/-/issues/20025
// [-] https://bugzilla.mozilla.org/1603712
user_pref("intl.charset.fallback.override", "windows-1252");
// FF82
// 0206: disable geographically specific results/search engines e.g. "browser.search.*.US"
// i.e. ignore all of Mozilla's various search engines in multiple locales
// [-] https://bugzilla.mozilla.org/1619926
user_pref("browser.search.geoSpecificDefaults", false);
user_pref("browser.search.geoSpecificDefaults.url", "");
// FF86
// 1205: disable SSL Error Reporting
// [1] https://firefox-source-docs.mozilla.org/browser/base/sslerrorreport/preferences.html
// [-] https://bugzilla.mozilla.org/1681839
user_pref("security.ssl.errorReporting.automatic", false);
user_pref("security.ssl.errorReporting.enabled", false);
user_pref("security.ssl.errorReporting.url", "");
// 2653: disable hiding mime types (Options>General>Applications) not associated with a plugin
// [-] https://bugzilla.mozilla.org/1581678
user_pref("browser.download.hide_plugins_without_extensions", false);
// ***/
/* END: internal custom pref to test for syntax errors ***/
user_pref("_user.js.parrot", "SUCCESS: No no he's not dead, he's, he's restin'!");
| 87 deprecated
It is simpler to leave the PointerEvent pref where it is, until ESR78 is EOL
- FF87+ users who use RFP Alts simply add a dead pref, no harm
- This way ESR78 users don't have to worry about extra char flipping: it's the same as before: 1 flip for ESR, 1 flip for RFP Alts | user.js | 87 deprecated | <ide><path>ser.js
<ide> user_pref("browser.newtabpage.activity-stream.section.highlights.includePocket", false);
<ide> user_pref("browser.newtabpage.activity-stream.showSponsored", false);
<ide> user_pref("browser.newtabpage.activity-stream.feeds.discoverystreamfeed", false); // [FF66+]
<del>/* 0105d: disable Activity Stream recent Highlights in the Library [FF57+] ***/
<del> // user_pref("browser.library.activity-stream.enabled", false);
<ide> /* 0105e: clear default topsites
<ide> * [NOTE] This does not block you from adding your own ***/
<ide> user_pref("browser.newtabpage.activity-stream.default.sites", "");
<ide> // 0=no-preference, 1=reduce
<ide> user_pref("ui.prefersReducedMotion", 0); // [HIDDEN PREF]
<ide> // FF64+
<del>// 4615: [2516] disable PointerEvents
<add>// 4615: [2516] disable PointerEvents [FF86 or lower]
<ide> // [1] https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent
<add> // [-] https://bugzilla.mozilla.org/1688105
<ide> user_pref("dom.w3c_pointer_events.enabled", false);
<ide> // * * * /
<ide> // FF67+
<ide> // 2653: disable hiding mime types (Options>General>Applications) not associated with a plugin
<ide> // [-] https://bugzilla.mozilla.org/1581678
<ide> user_pref("browser.download.hide_plugins_without_extensions", false);
<add>// FF87
<add>// 0105d: disable Activity Stream recent Highlights in the Library [FF57+]
<add> // [-] https://bugzilla.mozilla.org/1689405
<add> // user_pref("browser.library.activity-stream.enabled", false);
<ide> // ***/
<ide>
<ide> /* END: internal custom pref to test for syntax errors ***/ |
|
JavaScript | apache-2.0 | d7e53bb3e12adbb790ba227d4690c37a5b11508c | 0 | appium/appium,Sw0rdstream/appium,appium/appium,appium/appium,appium/appium,appium/appium,appium/appium | "use strict";
var errors = require('./errors')
, request = require('request')
, _ = require('underscore')
, logger = require('../logger').get('appium');
var UnknownError = errors.UnknownError
, ProtocolError = errors.ProtocolError;
exports.respond = function(response, cb) {
if (typeof response === 'undefined') {
cb(null, '');
} else {
if (typeof(response) !== "object") {
cb(new UnknownError(), response);
} else if (!('status' in response)) {
cb(new ProtocolError('Status missing in response from device'), response);
} else {
var status = parseInt(response.status, 10);
if (isNaN(status)) {
cb(new ProtocolError('Invalid status in response from device'), response);
} else {
response.status = status;
cb(null, response);
}
}
}
};
exports.proxy = function(command, cb) {
// was thinking we should use a queue for commands instead of writing to a file
logger.info('Pushing command to appium work queue: ' + JSON.stringify(command));
this.push([command, cb]);
if (typeof command === "object") {
command = JSON.stringify(command);
}
};
exports.waitForCondition = function(waitMs, condFn, cb, intervalMs) {
if (typeof intervalMs === "undefined") {
intervalMs = 500;
}
var begunAt = Date.now();
var endAt = begunAt + waitMs;
var me = this;
var spin = function() {
condFn(function(condMet) {
var args = Array.prototype.slice.call(arguments);
if (condMet) {
cb.apply(me, args.slice(1));
} else if (Date.now() < endAt) {
setTimeout(spin, intervalMs);
} else {
cb.apply(me, args.slice(1));
}
});
};
spin();
};
exports.request = function(url, method, body, contentType, cb) {
if (typeof cb === "undefined" && typeof contentType === "function") {
cb = contentType;
contentType = null;
}
if (typeof contentType === "undefined" || contentType === null) {
contentType = "application/json";
}
if (!(/^https?:\/\//.exec(url))) {
url = 'http://' + url;
}
var opts = {
url: url
, method: method
, headers: {'Content-Type': contentType}
};
if (_.contains(['put', 'post', 'patch'], method.toLowerCase())) {
if (typeof body !== "string") {
opts.json = body;
} else {
opts.body = body;
}
}
logger.info("Making http request with opts: " + JSON.stringify(opts));
request(opts, cb);
};
| app/device.js | "use strict";
var errors = require('./errors')
, request = require('request')
, _ = require('underscore')
, logger = require('../logger').get('appium');
var UnknownError = errors.UnknownError
, ProtocolError = errors.ProtocolError;
exports.respond = function(response, cb) {
if (typeof response === 'undefined') {
cb(null, '');
} else {
if (typeof(response) !== "object") {
cb(new UnknownError(), response);
} else if (!('status' in response)) {
cb(new ProtocolError('Status missing in response from device'), response);
} else {
var status = parseInt(response.status, 10);
if (isNaN(status)) {
cb(new ProtocolError('Invalid status in response from device'), response);
} else {
response.status = status;
cb(null, response);
}
}
}
};
exports.proxy = function(command, cb) {
// was thinking we should use a queue for commands instead of writing to a file
logger.info('Pushing command to appium work queue: ' + JSON.stringify(command));
this.push([command, cb]);
if (typeof command === "object") {
command = JSON.stringify(command);
}
};
exports.waitForCondition = function(waitMs, condFn, cb, intervalMs) {
if (typeof intervalMs === "undefined") {
intervalMs = 500;
}
var begunAt = Date.now();
var endAt = begunAt + waitMs;
var me = this;
var spin = function() {
condFn(function(condMet) {
var args = Array.prototype.slice.call(arguments);
if (condMet) {
cb.apply(me, args.slice(1));
} else if (Date.now() < endAt) {
setTimeout(spin, intervalMs);
} else {
cb.apply(me, args.slice(1));
}
});
};
spin();
};
exports.request = function(url, method, body, contentType, cb) {
if (typeof cb === "undefined" && typeof contentType === "function") {
cb = contentType;
contentType = null;
}
if (typeof contentType === "undefined" || contentType === null) {
contentType = "application/json";
}
if (!(/^https?:\/\//.exec(url))) {
url = 'http://' + url;
}
var opts = {
url: url
, method: method
, headers: {'Content-Type': contentType}
, timeout: 10000
};
if (_.contains(['put', 'post', 'patch'], method.toLowerCase())) {
if (typeof body !== "string") {
opts.json = body;
} else {
opts.body = body;
}
}
logger.info("Making http request with opts: " + JSON.stringify(opts));
request(opts, cb);
};
| remove short http timeout for selendroid (fix #540)
| app/device.js | remove short http timeout for selendroid (fix #540) | <ide><path>pp/device.js
<ide> url: url
<ide> , method: method
<ide> , headers: {'Content-Type': contentType}
<del> , timeout: 10000
<ide> };
<ide> if (_.contains(['put', 'post', 'patch'], method.toLowerCase())) {
<ide> if (typeof body !== "string") { |
|
Java | apache-2.0 | 36c686cab3e9fe62895fee8b4f71fdd780cafe84 | 0 | GELOG/sample-hbase-app | package org.gelog.sys870;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import org.apache.commons.io.IOUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HRegionInfo;
import org.apache.hadoop.hbase.HRegionLocation;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.Table;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Development process:
*
* 1. Compile on your workstation
* Using Maven :
*
* mvn package
*
* ls -lh target/*.jar
* -rw-r--r-- 1 david staff 8.4K Oct 4 23:29 target/hbase-app-0.0.1-SNAPSHOT.jar
* -rw-r--r-- 1 david staff 31M Oct 4 23:29 target/hbase-app-0.0.1-SNAPSHOT-fattyboy.jar
*
*
* Using graddle :
*
* (eclipse usage) gradle eclipse
* (idea usage) gradle idea
*
* gradle package
*
* ls -lh build/libs/*.jar
* -rw-r--r-- 1 michael michael 37426474 5 oct 23:56 hbase-app-0.0.1-SNAPSHOT-all.jar
*
* 2. Start a Docker container (using gradle, replace absolute path from target to build/libs)
* docker run --rm -ti \
* -v $HOME/workspace/ets/sys870/sample-hbase-app/target:/opt/target \
* hbase bash
*
* 3. Run you job as follows (builded using gradle ? adapt jar name):
* java -jar /opt/target/hbase-app-0.0.1-SNAPSHOT-fattyboy.jar
*
*
* IMPROVEMENTS:
* FIXME: Normally, we should be able to run the non-fat jar as follows:
*
* java -cp .:$(hbase classpath) -jar hbase-app-0.0.1-SNAPSHOT.jar
*
* but it complains about not being able to find the Hadoop Configuration class.
*
*
* TODO: The HBase ZooKeeper IP is hardcoded in src/main/resources.
* It would be great to find an elegant way to override this between
* local and dev HBase cluster.
*
* TODO: Find a way to connect to Docker container from IDE.
* Currently, if I need hardcode the "hbase-master" IP address in /etc/hosts.
* It allows connecting to ZooKeeper, but it fails when connecting to HBase
* RegionServer. This seems to be because the RegionServer port is always
* changing when starting the HBase master, so it is impossible to NAT this
* port from the container through the Docker-Machine / Boot2Docker or
* through a remote server.
*
* The port may be randomly assigned since HBase starts in non-distributed
* mode.
*
* @author david
* @see https://github.com/larsgeorge/hbase-book
* for more Java API code examples.
*/
public class HBaseApp
{
private static final Logger LOG = LoggerFactory.getLogger(HBaseConfiguration.class);
public static void main( String[] args ) throws IOException
{
new HBaseApp();
}
public HBaseApp() throws IOException
{
Configuration conf;
Connection conn;
String zkConnectionString;
// Scanner reader = new Scanner(System.in); // Reading from System.in
// System.out.println("Enter a number: ");
// int n = reader.nextInt();
System.out.println("Setting up HBase configuration ...");
conf = configureHBase();
System.out.println("\t" + getPropertyTraceability(conf, "hbase.zookeeper.quorum") );
System.out.println("\t" + getPropertyTraceability(conf, "hbase.zookeeper.property.clientPort") );
// Note: Verify that the client can connect to ZooKeeper (normally not required)
/*
System.out.println("Connecting manually to ZooKeeper (not required) ...");
zkConnectionString = conf.get( "hbase.zookeeper.quorum" );
testingZooKeeper( zkConnectionString );
*/
//System.exit(1);
System.out.println("Using HBase client to connect to the ZooKeeper Quorum ...");
conn = ConnectionFactory.createConnection( conf );
locateTable( conn, "hbase:meta" );
locateTable( conn, "table1" );
locateTable( conn, "default:table1" );
createTable( conn );
System.exit(1);
}
public Configuration configureHBase()
{
Configuration conf;
InputStream confStream;
conf = HBaseConfiguration.create();
confStream = conf.getConfResourceAsInputStream("hello.xml");
int available = 0;
try {
available = confStream.available();
} catch (Exception e) {
//for debug purpose
System.out.println("configuration files not found locally");
} finally {
IOUtils.closeQuietly( confStream );
}
if (available == 0 ) {
conf = new Configuration();
conf.addResource("core-site.xml");
conf.addResource("hbase-site.xml");
conf.addResource("hdfs-site.xml");
}
// Add any necessary configuration files (hbase-site.xml, core-site.xml)
//config.addResource(new Path(System.getenv("HBASE_CONF_DIR"), "hbase-site.xml"));
//config.addResource(new Path(System.getenv("HADOOP_CONF_DIR"), "core-site.xml"));
conf.set("zookeeper.session.timeout", "100");
return conf;
}
public String getPropertyTraceability( Configuration conf, String key )
{
String value;
String[] sources;
String source;
value = conf.get( key );
sources = conf.getPropertySources( key );
// Only keep the most recent source (last in the array)
source = (sources != null ? sources[sources.length-1] : "");
return key + " = " + value + " (" + source + ")";
}
public void testingZooKeeper( String zkConnectionString ) throws IOException
{
ZooKeeperWrapper zk;
int zkSessionTimeout;
zkSessionTimeout = 3000;
zk = new ZooKeeperWrapper( zkConnectionString, zkSessionTimeout );
System.out.println("Listing paths in ZooKeeper recursively ...");
zk.list( "/" );
zk.disconnect();
}
public void locateTable( Connection connection, String tableName ) throws IOException
{
TableName tableNameH; // TableName used by HBase (bytes ?)
byte[] startRow;
String host;
List<HRegionLocation> locations;
HRegionInfo regionInfo;
System.out.println("Locating the '" + tableName + "' table ...");
tableNameH = TableName.valueOf( tableName );
startRow = null;
locations = connection.getRegionLocator(tableNameH).getAllRegionLocations();
for (HRegionLocation location : locations) {
host = location.getHostnamePort();
regionInfo = location.getRegionInfo();
startRow = regionInfo.getStartKey();
System.out.printf("\tHost: %s has region #%d starting at row %s\n",
host,
regionInfo.getRegionId(),
startRow );
System.out.println( );
}
}
public void createTable( Connection conn ) throws IOException
{
Admin admin;
String tableName;
TableName tableNameH; // TableName used by HBase (bytes ?)
HTableDescriptor table;
String family;
admin = conn.getAdmin();
tableName = "demo-table";
tableNameH = TableName.valueOf( tableName );
if ( admin.tableExists(tableNameH) ) {
System.out.println("Table already exists. Deleting table " + tableName);
admin.disableTable( tableNameH );
admin.deleteTable( tableNameH );
}
System.out.println("Creating table " + tableName);
family = "cf";
table = new HTableDescriptor( tableNameH );
table.addFamily( new HColumnDescriptor( family ) );
admin.createTable( table );
}
}
| src/main/java/org/gelog/sys870/HBaseApp.java | package org.gelog.sys870;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import org.apache.commons.io.IOUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HRegionInfo;
import org.apache.hadoop.hbase.HRegionLocation;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.Table;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Development process:
*
* 1. Compile on your workstation
* Using Maven :
*
* mvn package
*
* ls -lh target/*.jar
* -rw-r--r-- 1 david staff 8.4K Oct 4 23:29 target/hbase-app-0.0.1-SNAPSHOT.jar
* -rw-r--r-- 1 david staff 31M Oct 4 23:29 target/hbase-app-0.0.1-SNAPSHOT-fattyboy.jar
*
*
* Using graddle :
*
* (eclipse usage) gradle eclipse
* (idea usage) gradle idea
*
* gradle package
*
* ls -lh build/libs/*.jar
* -rw-r--r-- 1 michael michael 37426474 5 oct 23:56 hbase-app-0.0.1-SNAPSHOT-all.jar
*
* 2. Start a Docker container (using gradle, replace absolute path from target to build/libs)
* docker run --rm -ti \
* -v $HOME/workspace/ets/sys870/sample-hbase-app/target:/opt/target \
* hbase bash
*
* 3. Run you job as follows:
* java -jar /opt/target/hbase-app-0.0.1-SNAPSHOT-fattyboy.jar
*
*
* IMPROVEMENTS:
* FIXME: Normally, we should be able to run the non-fat jar as follows:
*
* java -cp .:$(hbase classpath) -jar hbase-app-0.0.1-SNAPSHOT.jar
*
* but it complains about not being able to find the Hadoop Configuration class.
*
*
* TODO: The HBase ZooKeeper IP is hardcoded in src/main/resources.
* It would be great to find an elegant way to override this between
* local and dev HBase cluster.
*
* TODO: Find a way to connect to Docker container from IDE.
* Currently, if I need hardcode the "hbase-master" IP address in /etc/hosts.
* It allows connecting to ZooKeeper, but it fails when connecting to HBase
* RegionServer. This seems to be because the RegionServer port is always
* changing when starting the HBase master, so it is impossible to NAT this
* port from the container through the Docker-Machine / Boot2Docker or
* through a remote server.
*
* The port may be randomly assigned since HBase starts in non-distributed
* mode.
*
* @author david
* @see https://github.com/larsgeorge/hbase-book
* for more Java API code examples.
*/
public class HBaseApp
{
private static final Logger LOG = LoggerFactory.getLogger(HBaseConfiguration.class);
public static void main( String[] args ) throws IOException
{
new HBaseApp();
}
public HBaseApp() throws IOException
{
Configuration conf;
Connection conn;
String zkConnectionString;
// Scanner reader = new Scanner(System.in); // Reading from System.in
// System.out.println("Enter a number: ");
// int n = reader.nextInt();
System.out.println("Setting up HBase configuration ...");
conf = configureHBase();
System.out.println("\t" + getPropertyTraceability(conf, "hbase.zookeeper.quorum") );
System.out.println("\t" + getPropertyTraceability(conf, "hbase.zookeeper.property.clientPort") );
// Note: Verify that the client can connect to ZooKeeper (normally not required)
/*
System.out.println("Connecting manually to ZooKeeper (not required) ...");
zkConnectionString = conf.get( "hbase.zookeeper.quorum" );
testingZooKeeper( zkConnectionString );
*/
//System.exit(1);
System.out.println("Using HBase client to connect to the ZooKeeper Quorum ...");
conn = ConnectionFactory.createConnection( conf );
locateTable( conn, "hbase:meta" );
locateTable( conn, "table1" );
locateTable( conn, "default:table1" );
createTable( conn );
System.exit(1);
}
public Configuration configureHBase()
{
Configuration conf;
InputStream confStream;
conf = HBaseConfiguration.create();
confStream = conf.getConfResourceAsInputStream("hello.xml");
int available = 0;
try {
available = confStream.available();
} catch (Exception e) {
//for debug purpose
System.out.println("configuration files not found locally");
} finally {
IOUtils.closeQuietly( confStream );
}
if (available == 0 ) {
conf = new Configuration();
conf.addResource("core-site.xml");
conf.addResource("hbase-site.xml");
conf.addResource("hdfs-site.xml");
}
// Add any necessary configuration files (hbase-site.xml, core-site.xml)
//config.addResource(new Path(System.getenv("HBASE_CONF_DIR"), "hbase-site.xml"));
//config.addResource(new Path(System.getenv("HADOOP_CONF_DIR"), "core-site.xml"));
conf.set("zookeeper.session.timeout", "100");
return conf;
}
public String getPropertyTraceability( Configuration conf, String key )
{
String value;
String[] sources;
String source;
value = conf.get( key );
sources = conf.getPropertySources( key );
// Only keep the most recent source (last in the array)
source = (sources != null ? sources[sources.length-1] : "");
return key + " = " + value + " (" + source + ")";
}
public void testingZooKeeper( String zkConnectionString ) throws IOException
{
ZooKeeperWrapper zk;
int zkSessionTimeout;
zkSessionTimeout = 3000;
zk = new ZooKeeperWrapper( zkConnectionString, zkSessionTimeout );
System.out.println("Listing paths in ZooKeeper recursively ...");
zk.list( "/" );
zk.disconnect();
}
public void locateTable( Connection connection, String tableName ) throws IOException
{
TableName tableNameH; // TableName used by HBase (bytes ?)
byte[] startRow;
String host;
List<HRegionLocation> locations;
HRegionInfo regionInfo;
System.out.println("Locating the '" + tableName + "' table ...");
tableNameH = TableName.valueOf( tableName );
startRow = null;
locations = connection.getRegionLocator(tableNameH).getAllRegionLocations();
for (HRegionLocation location : locations) {
host = location.getHostnamePort();
regionInfo = location.getRegionInfo();
startRow = regionInfo.getStartKey();
System.out.printf("\tHost: %s has region #%d starting at row %s\n",
host,
regionInfo.getRegionId(),
startRow );
System.out.println( );
}
}
public void createTable( Connection conn ) throws IOException
{
Admin admin;
String tableName;
TableName tableNameH; // TableName used by HBase (bytes ?)
HTableDescriptor table;
String family;
admin = conn.getAdmin();
tableName = "demo-table";
tableNameH = TableName.valueOf( tableName );
if ( admin.tableExists(tableNameH) ) {
System.out.println("Table already exists. Deleting table " + tableName);
admin.disableTable( tableNameH );
admin.deleteTable( tableNameH );
}
System.out.println("Creating table " + tableName);
family = "cf";
table = new HTableDescriptor( tableNameH );
table.addFamily( new HColumnDescriptor( family ) );
admin.createTable( table );
}
}
| doc : small changes
| src/main/java/org/gelog/sys870/HBaseApp.java | doc : small changes | <ide><path>rc/main/java/org/gelog/sys870/HBaseApp.java
<ide> * -v $HOME/workspace/ets/sys870/sample-hbase-app/target:/opt/target \
<ide> * hbase bash
<ide> *
<del> * 3. Run you job as follows:
<add> * 3. Run you job as follows (builded using gradle ? adapt jar name):
<ide> * java -jar /opt/target/hbase-app-0.0.1-SNAPSHOT-fattyboy.jar
<ide> *
<ide> * |
|
Java | mit | fa05f221e570a7880a77f338da9e529a79fbc68e | 0 | PrinceOfAmber/Cyclic,PrinceOfAmber/CyclicMagic | package com.lothrazar.cyclicmagic.component.hydrator;
import com.lothrazar.cyclicmagic.block.base.BaseMachineTesr;
import com.lothrazar.cyclicmagic.block.base.TileEntityBaseMachineInvo;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
/**
* Thanks to this tutorial
* http://modwiki.temporal-reality.com/mw/index.php/Render_Block_TESR_/_OBJ-1.9
*
* @author Sam
*
*/
@SideOnly(Side.CLIENT)
public class HydratorTESR extends BaseMachineTesr<TileEntityHydrator> {
private static final float height = 0.5F;
public HydratorTESR(int slot, int ls) {
super(slot);
}
@Override
public void renderBasic(TileEntityBaseMachineInvo te) {
renderItem(te, te.getStackInSlot(0), 0, height, 1);
renderItem(te, te.getStackInSlot(1), 1, height, 1);
renderItem(te, te.getStackInSlot(2), 1, height, 0);
renderItem(te, te.getStackInSlot(3), 0, height, 0);
}
}
| src/main/java/com/lothrazar/cyclicmagic/component/hydrator/HydratorTESR.java | package com.lothrazar.cyclicmagic.component.hydrator;
import com.lothrazar.cyclicmagic.block.base.BaseMachineTesr;
import com.lothrazar.cyclicmagic.block.base.TileEntityBaseMachineInvo;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
/**
* Thanks to this tutorial
* http://modwiki.temporal-reality.com/mw/index.php/Render_Block_TESR_/_OBJ-1.9
*
* @author Sam
*
*/
@SideOnly(Side.CLIENT)
public class HydratorTESR extends BaseMachineTesr<TileEntityHydrator> {
private int lowerSlot;
public HydratorTESR(int slot, int ls) {
super(slot);
lowerSlot = ls;
}
@Override
public void renderBasic(TileEntityBaseMachineInvo te) {
renderItem(te, te.getStackInSlot(this.itemSlotAbove), 0, 0.5F, 1);
renderItem(te, te.getStackInSlot(this.lowerSlot), 1, 0.5F, 0);
}
}
| hydrator TESR animate 4 not 2
| src/main/java/com/lothrazar/cyclicmagic/component/hydrator/HydratorTESR.java | hydrator TESR animate 4 not 2 | <ide><path>rc/main/java/com/lothrazar/cyclicmagic/component/hydrator/HydratorTESR.java
<ide> */
<ide> @SideOnly(Side.CLIENT)
<ide> public class HydratorTESR extends BaseMachineTesr<TileEntityHydrator> {
<del> private int lowerSlot;
<add> private static final float height = 0.5F;
<ide> public HydratorTESR(int slot, int ls) {
<ide> super(slot);
<del> lowerSlot = ls;
<ide> }
<ide> @Override
<ide> public void renderBasic(TileEntityBaseMachineInvo te) {
<del> renderItem(te, te.getStackInSlot(this.itemSlotAbove), 0, 0.5F, 1);
<del> renderItem(te, te.getStackInSlot(this.lowerSlot), 1, 0.5F, 0);
<add> renderItem(te, te.getStackInSlot(0), 0, height, 1);
<add> renderItem(te, te.getStackInSlot(1), 1, height, 1);
<add> renderItem(te, te.getStackInSlot(2), 1, height, 0);
<add> renderItem(te, te.getStackInSlot(3), 0, height, 0);
<ide> }
<ide> } |
|
Java | apache-2.0 | d2d6ba0c17575067326cc33e1235556fba13b817 | 0 | strapdata/elassandra5-rc,strapdata/elassandra5-rc,strapdata/elassandra5-rc,strapdata/elassandra5-rc,strapdata/elassandra5-rc | /*
* Copyright (c) 2017 Strapdata (http://www.strapdata.com)
* Contains some code from Elasticsearch (http://www.elastic.co)
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.elasticsearch.cluster.service;
import ch.qos.logback.classic.jmx.JMXConfiguratorMBean;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.Appender;
import ch.qos.logback.core.joran.spi.JoranException;
import com.carrotsearch.hppc.cursors.ObjectCursor;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.net.InetAddresses;
import org.apache.cassandra.config.CFMetaData;
import org.apache.cassandra.config.ColumnDefinition;
import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.config.Schema;
import org.apache.cassandra.cql3.CQL3Type;
import org.apache.cassandra.cql3.ColumnIdentifier;
import org.apache.cassandra.cql3.ColumnSpecification;
import org.apache.cassandra.cql3.QueryOptions;
import org.apache.cassandra.cql3.QueryProcessor;
import org.apache.cassandra.cql3.UntypedResultSet;
import org.apache.cassandra.cql3.UntypedResultSet.Row;
import org.apache.cassandra.cql3.statements.IndexTarget;
import org.apache.cassandra.cql3.statements.ParsedStatement;
import org.apache.cassandra.cql3.statements.TableAttributes;
import org.apache.cassandra.db.CBuilder;
import org.apache.cassandra.db.ConsistencyLevel;
import org.apache.cassandra.db.Keyspace;
import org.apache.cassandra.db.KeyspaceNotDefinedException;
import org.apache.cassandra.db.SystemKeyspace;
import org.apache.cassandra.db.marshal.AbstractType;
import org.apache.cassandra.db.marshal.BytesType;
import org.apache.cassandra.db.marshal.CollectionType;
import org.apache.cassandra.db.marshal.ListType;
import org.apache.cassandra.db.marshal.MapType;
import org.apache.cassandra.db.marshal.SetType;
import org.apache.cassandra.db.marshal.TupleType;
import org.apache.cassandra.db.marshal.TypeParser;
import org.apache.cassandra.db.marshal.UTF8Type;
import org.apache.cassandra.db.marshal.UserType;
import org.apache.cassandra.dht.Token;
import org.apache.cassandra.exceptions.ConfigurationException;
import org.apache.cassandra.exceptions.InvalidRequestException;
import org.apache.cassandra.exceptions.RequestExecutionException;
import org.apache.cassandra.exceptions.RequestValidationException;
import org.apache.cassandra.exceptions.SyntaxException;
import org.apache.cassandra.exceptions.UnavailableException;
import org.apache.cassandra.exceptions.WriteTimeoutException;
import org.apache.cassandra.index.Index;
import org.apache.cassandra.locator.AbstractReplicationStrategy;
import org.apache.cassandra.locator.NetworkTopologyStrategy;
import org.apache.cassandra.schema.IndexMetadata;
import org.apache.cassandra.schema.KeyspaceMetadata;
import org.apache.cassandra.schema.ReplicationParams;
import org.apache.cassandra.schema.TableParams;
import org.apache.cassandra.serializers.CollectionSerializer;
import org.apache.cassandra.serializers.MapSerializer;
import org.apache.cassandra.serializers.MarshalException;
import org.apache.cassandra.service.ClientState;
import org.apache.cassandra.service.ElassandraDaemon;
import org.apache.cassandra.service.MigrationManager;
import org.apache.cassandra.service.QueryState;
import org.apache.cassandra.service.StorageService;
import org.apache.cassandra.transport.ProtocolVersion;
import org.apache.cassandra.transport.messages.ResultMessage;
import org.apache.cassandra.utils.ByteBufferUtil;
import org.apache.cassandra.utils.FBUtilities;
import org.apache.cassandra.utils.Pair;
import org.apache.cassandra.utils.UUIDGen;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.message.ParameterizedMessage;
import org.apache.logging.log4j.util.Supplier;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.elassandra.ConcurrentMetaDataUpdateException;
import org.elassandra.NoPersistedMetaDataException;
import org.elassandra.cluster.routing.AbstractSearchStrategy;
import org.elassandra.cluster.routing.PrimaryFirstSearchStrategy;
import org.elassandra.discovery.CassandraDiscovery;
import org.elassandra.index.ExtendedElasticSecondaryIndex;
import org.elassandra.index.mapper.internal.NodeFieldMapper;
import org.elassandra.index.mapper.internal.TokenFieldMapper;
import org.elassandra.index.search.TokenRangesService;
import org.elassandra.indices.CassandraSecondaryIndicesApplier;
import org.elassandra.shard.CassandraShardStartedBarrier;
import org.elasticsearch.ElasticsearchTimeoutException;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.ActionRequestValidationException;
import org.elasticsearch.action.DocWriteRequest;
import org.elasticsearch.action.admin.indices.mapping.put.PutMappingClusterStateUpdateRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.support.replication.ReplicationResponse.ShardInfo;
import org.elasticsearch.cluster.ClusterChangedEvent;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.ClusterStateApplier;
import org.elasticsearch.cluster.ClusterStateListener;
import org.elasticsearch.cluster.ClusterStateTaskConfig;
import org.elasticsearch.cluster.ClusterStateTaskListener;
import org.elasticsearch.cluster.ClusterStateUpdateTask;
import org.elasticsearch.cluster.ack.ClusterStateUpdateRequest;
import org.elasticsearch.cluster.ack.ClusterStateUpdateResponse;
import org.elasticsearch.cluster.action.index.MappingUpdatedAction;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.cluster.metadata.MappingMetaData;
import org.elasticsearch.cluster.metadata.MetaData;
import org.elasticsearch.cluster.metadata.MetaDataMappingService;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.node.DiscoveryNode.DiscoveryNodeStatus;
import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.cluster.routing.OperationRouting;
import org.elasticsearch.cluster.routing.RoutingTable;
import org.elasticsearch.cluster.routing.ShardRoutingState;
import org.elasticsearch.common.Priority;
import org.elasticsearch.common.SuppressForbidden;
import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.logging.Loggers;
import org.elasticsearch.common.settings.ClusterSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.discovery.Discovery;
import org.elasticsearch.gateway.MetaStateService;
import org.elasticsearch.index.IndexNotFoundException;
import org.elasticsearch.index.IndexService;
import org.elasticsearch.index.engine.Engine;
import org.elasticsearch.index.engine.VersionConflictEngineException;
import org.elasticsearch.index.get.GetField;
import org.elasticsearch.index.mapper.BaseGeoPointFieldMapper;
import org.elasticsearch.index.mapper.BaseGeoPointFieldMapper.LegacyGeoPointFieldType;
import org.elasticsearch.index.mapper.CompletionFieldMapper;
import org.elasticsearch.index.mapper.DateFieldMapper;
import org.elasticsearch.index.mapper.DocumentFieldMappers;
import org.elasticsearch.index.mapper.DocumentMapper;
import org.elasticsearch.index.mapper.FieldMapper;
import org.elasticsearch.index.mapper.GeoPointFieldMapper;
import org.elasticsearch.index.mapper.GeoShapeFieldMapper;
import org.elasticsearch.index.mapper.IdFieldMapper;
import org.elasticsearch.index.mapper.MappedFieldType;
import org.elasticsearch.index.mapper.Mapper;
import org.elasticsearch.index.mapper.Mapper.CqlCollection;
import org.elasticsearch.index.mapper.Mapper.CqlStruct;
import org.elasticsearch.index.mapper.MapperException;
import org.elasticsearch.index.mapper.MapperParsingException;
import org.elasticsearch.index.mapper.MapperService;
import org.elasticsearch.index.mapper.Mapping;
import org.elasticsearch.index.mapper.MetadataFieldMapper;
import org.elasticsearch.index.mapper.ObjectMapper;
import org.elasticsearch.index.mapper.ParentFieldMapper;
import org.elasticsearch.index.mapper.RoutingFieldMapper;
import org.elasticsearch.index.mapper.SourceFieldMapper;
import org.elasticsearch.index.mapper.SourceToParse;
import org.elasticsearch.index.mapper.TTLFieldMapper;
import org.elasticsearch.index.mapper.TimestampFieldMapper;
import org.elasticsearch.index.mapper.Uid;
import org.elasticsearch.index.shard.IndexShard;
import org.elasticsearch.indices.IndicesService;
import org.elasticsearch.threadpool.ThreadPool;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.nio.ByteBuffer;
import java.nio.charset.CharacterCodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.LongConsumer;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import javax.management.JMX;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import static org.apache.cassandra.cql3.QueryProcessor.executeInternal;
import static org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_NUMBER_OF_REPLICAS;
public class ClusterService extends org.elasticsearch.cluster.service.BaseClusterService {
public static final String ELASTIC_ID_COLUMN_NAME = "_id";
public static final String ELASTIC_ADMIN_KEYSPACE = "elastic_admin";
public static final String ELASTIC_ADMIN_METADATA_TABLE = "metadata";
public static final String SETTING_CLUSTER_DATACENTER_GROUP = "datacenter.group";
// settings levels : system, cluster, index, table(_meta)
public static final String SYSTEM_PREFIX = "es.";
public static final String CLUSTER_PREFIX = "cluster.";
public static final String INDEX_PREFIX = "index.";
public static final String TABLE_PREFIX = "";
private static final int CREATE_ELASTIC_ADMIN_RETRY_ATTEMPTS = Integer.getInteger(SYSTEM_PREFIX + "create_elastic_admin_retry_attempts", 5);
/**
* Dynamic mapping update timeout
*/
public static final String MAPPING_UPDATE_TIMEOUT = "mapping_update_timeout";
/**
* Secondary index class
*/
public static final String SECONDARY_INDEX_CLASS = "secondary_index_class";
/**
* Search strategy class
*/
public static final String SEARCH_STRATEGY_CLASS = "search_strategy_class";
/**
* When true, add the cassandra node id to documents (for use with the token aggregation feature)
*/
public static final String INCLUDE_NODE_ID = "include_node_id";
/**
* When true, re-indexes a row when compacting, usefull to delete expired documents or columns.
*/
public static final String INDEX_ON_COMPACTION = "index_on_compaction";
/**
* When true, refreshes ES index after each update (used for testing).
*/
public static final String SYNCHRONOUS_REFRESH = "synchronous_refresh";
/**
* When true, delete kespace/table when removing an index.
*/
public static final String DROP_ON_DELETE_INDEX = "drop_on_delete_index";
/**
* When true, snapshot lucene files with sstables.
*/
public static final String SNAPSHOT_WITH_SSTABLE = "snapshot_with_sstable";
/**
* When true, use the optimized version less Elasticsearch engine.
*/
public static final String VERSION_LESS_ENGINE = "version_less_engine";
/**
* Lucene numeric precision to store _token , see http://blog-archive.griddynamics.com/2014/10/numeric-range-queries-in-lucenesolr.html
*/
public static final String TOKEN_PRECISION_STEP = "token_precision_step";
/**
* Enable the token_ranges bitset cache (cache the token_ranges filter result at the lucene liveDocs level).
*/
public static final String TOKEN_RANGES_BITSET_CACHE = "token_ranges_bitset_cache";
/**
* Expiration time for unused cached token_ranges queries.
*/
public static final String TOKEN_RANGES_QUERY_EXPIRE = "token_ranges_query_expire";
/**
* Add static columns to indexed documents (default is false).
*/
public static final String INDEX_STATIC_COLUMNS = "index_static_columns";
/**
* Index only static columns (one document per partition row, ex: timeseries tags).
*/
public static final String INDEX_STATIC_ONLY = "index_static_only";
// system property settings
public static final String SETTING_SYSTEM_MAPPING_UPDATE_TIMEOUT = SYSTEM_PREFIX+MAPPING_UPDATE_TIMEOUT;
public static final String SETTING_SYSTEM_SECONDARY_INDEX_CLASS = SYSTEM_PREFIX+SECONDARY_INDEX_CLASS;
public static final String SETTING_SYSTEM_SEARCH_STRATEGY_CLASS = SYSTEM_PREFIX+SEARCH_STRATEGY_CLASS;
public static final String SETTING_SYSTEM_INCLUDE_NODE_ID = SYSTEM_PREFIX+INCLUDE_NODE_ID;
public static final String SETTING_SYSTEM_INDEX_ON_COMPACTION = SYSTEM_PREFIX+INDEX_ON_COMPACTION;
public static final String SETTING_SYSTEM_SYNCHRONOUS_REFRESH = SYSTEM_PREFIX+SYNCHRONOUS_REFRESH;
public static final String SETTING_SYSTEM_DROP_ON_DELETE_INDEX = SYSTEM_PREFIX+DROP_ON_DELETE_INDEX;
public static final String SETTING_SYSTEM_SNAPSHOT_WITH_SSTABLE = SYSTEM_PREFIX+SNAPSHOT_WITH_SSTABLE;
public static final String SETTING_SYSTEM_VERSION_LESS_ENGINE = SYSTEM_PREFIX+VERSION_LESS_ENGINE;
public static final String SETTING_SYSTEM_TOKEN_PRECISION_STEP = SYSTEM_PREFIX+TOKEN_PRECISION_STEP;
public static final String SETTING_SYSTEM_TOKEN_RANGES_BITSET_CACHE = SYSTEM_PREFIX+TOKEN_RANGES_BITSET_CACHE;
public static final String SETTING_SYSTEM_TOKEN_RANGES_QUERY_EXPIRE = SYSTEM_PREFIX+TOKEN_RANGES_QUERY_EXPIRE;
// elassandra cluster settings
public static final String SETTING_CLUSTER_MAPPING_UPDATE_TIMEOUT = CLUSTER_PREFIX+MAPPING_UPDATE_TIMEOUT;
public static final String SETTING_CLUSTER_SECONDARY_INDEX_CLASS = CLUSTER_PREFIX+SECONDARY_INDEX_CLASS;
public static final String SETTING_CLUSTER_SEARCH_STRATEGY_CLASS = CLUSTER_PREFIX+SEARCH_STRATEGY_CLASS;
public static final String SETTING_CLUSTER_INCLUDE_NODE_ID = CLUSTER_PREFIX+INCLUDE_NODE_ID;
public static final String SETTING_CLUSTER_INDEX_ON_COMPACTION = CLUSTER_PREFIX+INDEX_ON_COMPACTION;
public static final String SETTING_CLUSTER_SYNCHRONOUS_REFRESH = CLUSTER_PREFIX+SYNCHRONOUS_REFRESH;
public static final String SETTING_CLUSTER_DROP_ON_DELETE_INDEX = CLUSTER_PREFIX+DROP_ON_DELETE_INDEX;
public static final String SETTING_CLUSTER_SNAPSHOT_WITH_SSTABLE = CLUSTER_PREFIX+SNAPSHOT_WITH_SSTABLE;
public static final String SETTING_CLUSTER_VERSION_LESS_ENGINE = CLUSTER_PREFIX+VERSION_LESS_ENGINE;
public static final String SETTING_CLUSTER_TOKEN_PRECISION_STEP = CLUSTER_PREFIX+TOKEN_PRECISION_STEP;
public static final String SETTING_CLUSTER_TOKEN_RANGES_BITSET_CACHE = CLUSTER_PREFIX+TOKEN_RANGES_BITSET_CACHE;
public static int defaultPrecisionStep = Integer.getInteger(SETTING_SYSTEM_TOKEN_PRECISION_STEP, 6);
public static class DocPrimaryKey {
public String[] names;
public Object[] values;
public boolean isStaticDocument; // pk = partition key and pk has clustering key.
public DocPrimaryKey(String[] names, Object[] values, boolean isStaticDocument) {
this.names = names;
this.values = values;
this.isStaticDocument = isStaticDocument;
}
public DocPrimaryKey(String[] names, Object[] values) {
this.names = names;
this.values = values;
this.isStaticDocument = false;
}
public List<ByteBuffer> serialize(ParsedStatement.Prepared prepared) {
List<ByteBuffer> boundValues = new ArrayList<ByteBuffer>(values.length);
for (int i = 0; i < values.length; i++) {
Object v = values[i];
AbstractType type = prepared.boundNames.get(i).type;
boundValues.add(v instanceof ByteBuffer || v == null ? (ByteBuffer) v : type.decompose(v));
}
return boundValues;
}
}
public static Map<String, String> cqlMapping = new ImmutableMap.Builder<String,String>()
.put("text", "keyword")
.put("varchar", "keyword")
.put("timestamp", "date")
.put("date", "date")
.put("time", "long")
.put("int", "integer")
.put("double", "double")
.put("float", "float")
.put("bigint", "long")
.put("boolean", "boolean")
.put("blob", "binary")
.put("inet", "ip" )
.put("uuid", "keyword" )
.put("timeuuid", "keyword" )
.build();
private MetaStateService metaStateService;
private IndicesService indicesService;
private CassandraDiscovery discovery;
private final TokenRangesService tokenRangeService;
private final CassandraSecondaryIndicesApplier cassandraSecondaryIndicesApplier;
// manage asynchronous CQL schema update
protected final AtomicReference<MetadataSchemaUpdate> lastMetadataToSave = new AtomicReference<MetadataSchemaUpdate>(null);
protected final Semaphore metadataToSaveSemaphore = new Semaphore(0);
protected final MappingUpdatedAction mappingUpdatedAction;
public final static Class<? extends Index> defaultSecondaryIndexClass = ExtendedElasticSecondaryIndex.class;
protected final PrimaryFirstSearchStrategy primaryFirstSearchStrategy = new PrimaryFirstSearchStrategy();
protected final Map<String, AbstractSearchStrategy> strategies = new ConcurrentHashMap<String, AbstractSearchStrategy>();
protected final Map<String, AbstractSearchStrategy.Router> routers = new ConcurrentHashMap<String, AbstractSearchStrategy.Router>();
private final ConsistencyLevel metadataWriteCL = consistencyLevelFromString(System.getProperty("elassandra.metadata.write.cl","QUORUM"));
private final ConsistencyLevel metadataReadCL = consistencyLevelFromString(System.getProperty("elassandra.metadata.read.cl","QUORUM"));
private final ConsistencyLevel metadataSerialCL = consistencyLevelFromString(System.getProperty("elassandra.metadata.serial.cl","SERIAL"));
private final String elasticAdminKeyspaceName;
private final String selectMetadataQuery;
private final String selectVersionMetadataQuery;
private final String insertMetadataQuery;
private final String updateMetaDataQuery;
private volatile CassandraShardStartedBarrier shardStartedBarrier;
private final OperationRouting operationRouting;
@Inject
public ClusterService(Settings settings, ClusterSettings clusterSettings, ThreadPool threadPool, Supplier<DiscoveryNode> localNodeSupplier) {
super(settings, clusterSettings, threadPool, localNodeSupplier);
this.mappingUpdatedAction = null;
this.tokenRangeService = new TokenRangesService(settings);
this.cassandraSecondaryIndicesApplier = new CassandraSecondaryIndicesApplier(settings, this);
this.operationRouting = new OperationRouting(settings, clusterSettings, this);
String datacenterGroup = settings.get(SETTING_CLUSTER_DATACENTER_GROUP);
if (datacenterGroup != null && datacenterGroup.length() > 0) {
logger.info("Starting with datacenter.group=[{}]", datacenterGroup.trim().toLowerCase(Locale.ROOT));
elasticAdminKeyspaceName = String.format(Locale.ROOT, "%s_%s", ELASTIC_ADMIN_KEYSPACE,datacenterGroup.trim().toLowerCase(Locale.ROOT));
} else {
elasticAdminKeyspaceName = ELASTIC_ADMIN_KEYSPACE;
}
selectMetadataQuery = String.format(Locale.ROOT, "SELECT metadata,version,owner FROM \"%s\".\"%s\" WHERE cluster_name = ?", elasticAdminKeyspaceName, ELASTIC_ADMIN_METADATA_TABLE);
selectVersionMetadataQuery = String.format(Locale.ROOT, "SELECT version FROM \"%s\".\"%s\" WHERE cluster_name = ?", elasticAdminKeyspaceName, ELASTIC_ADMIN_METADATA_TABLE);
insertMetadataQuery = String.format(Locale.ROOT, "INSERT INTO \"%s\".\"%s\" (cluster_name,owner,version,metadata) VALUES (?,?,?,?) IF NOT EXISTS", elasticAdminKeyspaceName, ELASTIC_ADMIN_METADATA_TABLE);
updateMetaDataQuery = String.format(Locale.ROOT, "UPDATE \"%s\".\"%s\" SET owner = ?, version = ?, metadata = ? WHERE cluster_name = ? IF version < ?", elasticAdminKeyspaceName, ELASTIC_ADMIN_METADATA_TABLE);
}
public OperationRouting operationRouting() {
return operationRouting;
}
public void setMetaStateService(MetaStateService metaStateService) {
this.metaStateService = metaStateService;
}
public void setIndicesService(IndicesService indicesService) {
this.indicesService = indicesService;
}
public IndicesService getIndicesService() {
return this.indicesService;
}
public void setDiscovery(Discovery discovery) {
this.discovery = (CassandraDiscovery)discovery;
}
public TokenRangesService tokenRangesService() {
return this.tokenRangeService;
}
public void addShardStartedBarrier() {
this.shardStartedBarrier = new CassandraShardStartedBarrier(settings, this);
}
public void removeShardStartedBarrier() {
this.shardStartedBarrier = null;
}
public void blockUntilShardsStarted() {
if (shardStartedBarrier != null) {
shardStartedBarrier.blockUntilShardsStarted();
}
}
public String getElasticAdminKeyspaceName() {
return this.elasticAdminKeyspaceName;
}
public boolean isNativeCql3Type(String cqlType) {
return cqlMapping.keySet().contains(cqlType) && !cqlType.startsWith("geo_");
}
public Class<? extends AbstractSearchStrategy> searchStrategyClass(IndexMetaData indexMetaData, ClusterState state) {
try {
return AbstractSearchStrategy.getSearchStrategyClass(
indexMetaData.getSettings().get(IndexMetaData.SETTING_SEARCH_STRATEGY_CLASS,
state.metaData().settings().get(ClusterService.SETTING_CLUSTER_SEARCH_STRATEGY_CLASS,PrimaryFirstSearchStrategy.class.getName()))
);
} catch(ConfigurationException e) {
logger.error((Supplier<?>) () -> new ParameterizedMessage("Bad search strategy class, fallback to [{}]", PrimaryFirstSearchStrategy.class.getName()), e);
return PrimaryFirstSearchStrategy.class;
}
}
private AbstractSearchStrategy searchStrategyInstance(Class<? extends AbstractSearchStrategy> clazz) {
AbstractSearchStrategy searchStrategy = strategies.get(clazz.getName());
if (searchStrategy == null) {
try {
searchStrategy = clazz.newInstance();
} catch (Exception e) {
logger.error((Supplier<?>) () -> new ParameterizedMessage("Cannot instanciate search strategy [{}]", clazz.getName()), e);
searchStrategy = new PrimaryFirstSearchStrategy();
}
strategies.putIfAbsent(clazz.getName(), searchStrategy);
}
return searchStrategy;
}
public PrimaryFirstSearchStrategy.PrimaryFirstRouter updateRouter(IndexMetaData indexMetaData, ClusterState state) {
// update and returns a PrimaryFirstRouter for the build table.
PrimaryFirstSearchStrategy.PrimaryFirstRouter router = (PrimaryFirstSearchStrategy.PrimaryFirstRouter)this.primaryFirstSearchStrategy.newRouter(indexMetaData.getIndex(), indexMetaData.keyspace(), this::getShardRoutingStates, state);
// update the router cache with the effective router
AbstractSearchStrategy effectiveSearchStrategy = searchStrategyInstance(searchStrategyClass(indexMetaData, state));
if (! effectiveSearchStrategy.equals(PrimaryFirstSearchStrategy.class) ) {
AbstractSearchStrategy.Router router2 = effectiveSearchStrategy.newRouter(indexMetaData.getIndex(), indexMetaData.keyspace(), this::getShardRoutingStates, state);
this.routers.put(indexMetaData.getIndex().getName(), router2);
} else {
this.routers.put(indexMetaData.getIndex().getName(), router);
}
return router;
}
public AbstractSearchStrategy.Router getRouter(IndexMetaData indexMetaData, ClusterState state) {
AbstractSearchStrategy.Router router = this.routers.get(indexMetaData.getIndex().getName());
return router;
}
public UntypedResultSet process(final ConsistencyLevel cl, final String query)
throws RequestExecutionException, RequestValidationException, InvalidRequestException {
return process(cl, null, query, new Long(0), new Object[] {});
}
public UntypedResultSet process(final ConsistencyLevel cl, ClientState clientState, final String query)
throws RequestExecutionException, RequestValidationException, InvalidRequestException {
return process(cl, null, clientState, query, new Long(0), new Object[] {});
}
public UntypedResultSet process(final ConsistencyLevel cl, ClientState clientState, final String query, Object... values)
throws RequestExecutionException, RequestValidationException, InvalidRequestException {
return process(cl, null, clientState, query, new Long(0), values);
}
public UntypedResultSet process(final ConsistencyLevel cl, final String query, Object... values)
throws RequestExecutionException, RequestValidationException, InvalidRequestException {
return process(cl, null, query, new Long(0), values);
}
public UntypedResultSet process(final ConsistencyLevel cl, final ConsistencyLevel serialConsistencyLevel, final String query, final Object... values)
throws RequestExecutionException, RequestValidationException, InvalidRequestException {
return process(cl, serialConsistencyLevel, query, new Long(0), values);
}
public UntypedResultSet process(final ConsistencyLevel cl, final ConsistencyLevel serialConsistencyLevel, final String query, Long writetime, final Object... values) {
return process(cl, serialConsistencyLevel, ClientState.forInternalCalls(), query, writetime, values);
}
public UntypedResultSet process(final ConsistencyLevel cl, final ConsistencyLevel serialConsistencyLevel, ClientState clientState, final String query, Long writetime, final Object... values)
throws RequestExecutionException, RequestValidationException, InvalidRequestException {
if (logger.isDebugEnabled())
logger.debug("processing CL={} SERIAL_CL={} query={}", cl, serialConsistencyLevel, query);
// retreive prepared
QueryState queryState = new QueryState(clientState);
ResultMessage.Prepared prepared = ClientState.getCQLQueryHandler().prepare(query, queryState, Collections.EMPTY_MAP);
// bind
List<ByteBuffer> boundValues = new ArrayList<ByteBuffer>(values.length);
for (int i = 0; i < values.length; i++) {
Object v = values[i];
AbstractType type = prepared.metadata.names.get(i).type;
boundValues.add(v instanceof ByteBuffer || v == null ? (ByteBuffer) v : type.decompose(v));
}
// execute
QueryOptions queryOptions = QueryOptions.forInternalCalls(cl, serialConsistencyLevel, boundValues);
ResultMessage result = ClientState.getCQLQueryHandler().process(query, queryState, queryOptions, Collections.EMPTY_MAP, System.nanoTime());
writetime = queryState.getTimestamp();
return (result instanceof ResultMessage.Rows) ? UntypedResultSet.create(((ResultMessage.Rows) result).result) : null;
}
public boolean processWriteConditional(final ConsistencyLevel cl, final ConsistencyLevel serialCl, final String query, Object... values) {
return processWriteConditional(cl, serialCl, ClientState.forInternalCalls(), query, values);
}
public boolean processWriteConditional(final ConsistencyLevel cl, final ConsistencyLevel serialCl, ClientState clientState, final String query, Object... values)
throws RequestExecutionException, RequestValidationException, InvalidRequestException {
try {
UntypedResultSet result = process(cl, serialCl, clientState, query, new Long(0), values);
if (serialCl == null)
return true;
if (!result.isEmpty()) {
Row row = result.one();
if (row.has("[applied]")) {
return row.getBoolean("[applied]");
}
}
return false;
} catch (WriteTimeoutException e) {
logger.warn("PAXOS phase failed query=" + query + " values=" + Arrays.toString(values), e);
return false;
} catch (UnavailableException e) {
logger.warn("PAXOS commit failed query=" + query + " values=" + Arrays.toString(values), e);
return false;
} catch (Exception e) {
logger.error("Failed to process query=" + query + " values=" + Arrays.toString(values), e);
throw e;
}
}
/**
* Don't use QueryProcessor.executeInternal, we need to propagate this on all nodes.
**/
public void createIndexKeyspace(final String ksname, final int replicationFactor) throws IOException {
Keyspace ks = null;
try {
ks = Keyspace.open(ksname);
if (ks != null && !(ks.getReplicationStrategy() instanceof NetworkTopologyStrategy)) {
throw new IOException("Cannot create index, underlying keyspace requires the NetworkTopologyStrategy.");
}
} catch(AssertionError | NullPointerException e) {
}
try {
if (ks == null)
process(ConsistencyLevel.LOCAL_ONE, ClientState.forInternalCalls(),
String.format(Locale.ROOT, "CREATE KEYSPACE IF NOT EXISTS \"%s\" WITH replication = {'class':'NetworkTopologyStrategy', '%s':'%d' };",
ksname, DatabaseDescriptor.getLocalDataCenter(), replicationFactor));
} catch (Throwable e) {
throw new IOException(e.getMessage(), e);
}
}
public void dropIndexKeyspace(final String ksname) throws IOException {
try {
String query = String.format(Locale.ROOT, "DROP KEYSPACE IF EXISTS \"%s\"", ksname);
logger.debug(query);
QueryProcessor.process(query, ConsistencyLevel.LOCAL_ONE);
} catch (Throwable e) {
throw new IOException(e.getMessage(), e);
}
}
public static Pair<List<String>, List<String>> getUDTInfo(final String ksName, final String typeName) {
try {
UntypedResultSet result = QueryProcessor.executeOnceInternal("SELECT field_names, field_types FROM system_schema.types WHERE keyspace_name = ? AND type_name = ?",
new Object[] { ksName, typeName });
Row row = result.one();
if ((row != null) && row.has("field_names")) {
List<String> field_names = row.getList("field_names", UTF8Type.instance);
List<String> field_types = row.getList("field_types", UTF8Type.instance);
return Pair.<List<String>, List<String>> create(field_names, field_types);
}
} catch (Exception e) {
}
return null;
}
public static MapType<?,?> getMapType(final String ksName, final String cfName, final String colName) {
try {
UntypedResultSet result = QueryProcessor.executeOnceInternal("SELECT validator FROM system.schema_columns WHERE keyspace_name = ? AND columnfamily_name = ? AND column_name = ?",
new Object[] { ksName, cfName, colName });
Row row = result.one();
if ((row != null) && row.has("validator")) {
AbstractType<?> type = TypeParser.parse(row.getString("validator"));
if (type instanceof MapType) {
return (MapType<?,?>)type;
}
}
} catch (Exception e) {
}
return null;
}
// see https://docs.datastax.com/en/cql/3.0/cql/cql_reference/keywords_r.html
public static final Pattern keywordsPattern = Pattern.compile("(ADD|ALLOW|ALTER|AND|ANY|APPLY|ASC|AUTHORIZE|BATCH|BEGIN|BY|COLUMNFAMILY|CREATE|DELETE|DESC|DROP|EACH_QUORUM|GRANT|IN|INDEX|INET|INSERT|INTO|KEYSPACE|KEYSPACES|LIMIT|LOCAL_ONE|LOCAL_QUORUM|MODIFY|NOT|NORECURSIVE|OF|ON|ONE|ORDER|PASSWORD|PRIMARY|QUORUM|RENAME|REVOKE|SCHEMA|SELECT|SET|TABLE|TO|TOKEN|THREE|TRUNCATE|TWO|UNLOGGED|UPDATE|USE|USING|WHERE|WITH)");
public static boolean isReservedKeyword(String identifier) {
return keywordsPattern.matcher(identifier.toUpperCase(Locale.ROOT)).matches();
}
private static Object toJsonValue(Object o) {
if (o instanceof UUID)
return o.toString();
if (o instanceof Date)
return ((Date)o).getTime();
if (o instanceof ByteBuffer) {
// encode byte[] as Base64 encoded string
ByteBuffer bb = ByteBufferUtil.clone((ByteBuffer)o);
return Base64.getEncoder().encodeToString(ByteBufferUtil.getArray((ByteBuffer)o));
}
if (o instanceof InetAddress)
return InetAddresses.toAddrString((InetAddress)o);
return o;
}
private static org.codehaus.jackson.map.ObjectMapper jsonMapper = new org.codehaus.jackson.map.ObjectMapper();
// wrap string values with quotes
private static String stringify(Object o) throws IOException {
Object v = toJsonValue(o);
try {
return v instanceof String ? jsonMapper.writeValueAsString(v) : v.toString();
} catch (IOException e) {
Loggers.getLogger(ClusterService.class).error("Unexpected json encoding error", e);
throw new RuntimeException(e);
}
}
public static String stringify(Object[] cols, int length) {
if (cols.length == 1)
return toJsonValue(cols[0]).toString();
StringBuilder sb = new StringBuilder();
sb.append("[");
for(int i = 0; i < length; i++) {
if (i > 0)
sb.append(",");
Object val = toJsonValue(cols[i]);
if (val instanceof String) {
try {
sb.append(jsonMapper.writeValueAsString(val));
} catch (IOException e) {
Loggers.getLogger(ClusterService.class).error("Unexpected json encoding error", e);
throw new RuntimeException(e);
}
} else {
sb.append(val);
}
}
return sb.append("]").toString();
}
public static ByteBuffer fromString(AbstractType<?> atype, String v) throws IOException {
if (atype instanceof BytesType)
return ByteBuffer.wrap(Base64.getDecoder().decode(v));
return atype.fromString(v);
}
public static void toXContent(XContentBuilder builder, Mapper mapper, String field, Object value) throws IOException {
if (value instanceof Collection) {
if (field == null) {
builder.startArray();
} else {
builder.startArray(field);
}
for(Iterator<Object> i = ((Collection)value).iterator(); i.hasNext(); ) {
toXContent(builder, mapper, null, i.next());
}
builder.endArray();
} else if (value instanceof Map) {
Map<String, Object> map = (Map<String,Object>)value;
if (field != null) {
builder.startObject(field);
} else {
builder.startObject();
}
for(String subField : map.keySet()) {
Object subValue = map.get(subField);
if (subValue == null)
continue;
if (subValue instanceof Collection && ((Collection)subValue).size() == 1)
subValue = ((Collection)subValue).iterator().next();
if (mapper != null) {
if (mapper instanceof ObjectMapper) {
toXContent(builder, ((ObjectMapper)mapper).getMapper(subField), subField, subValue);
} else if (mapper instanceof BaseGeoPointFieldMapper) {
BaseGeoPointFieldMapper geoMapper = (BaseGeoPointFieldMapper)mapper;
if (geoMapper.fieldType() instanceof LegacyGeoPointFieldType && ((LegacyGeoPointFieldType)geoMapper.fieldType()).isLatLonEnabled()) {
Iterator<Mapper> it = geoMapper.iterator();
switch(subField) {
case org.elasticsearch.index.mapper.BaseGeoPointFieldMapper.Names.LAT:
toXContent(builder, it.next(), org.elasticsearch.index.mapper.BaseGeoPointFieldMapper.Names.LAT, map.get(org.elasticsearch.index.mapper.BaseGeoPointFieldMapper.Names.LAT));
break;
case org.elasticsearch.index.mapper.BaseGeoPointFieldMapper.Names.LON:
it.next();
toXContent(builder, it.next(), org.elasticsearch.index.mapper.BaseGeoPointFieldMapper.Names.LON, map.get(org.elasticsearch.index.mapper.BaseGeoPointFieldMapper.Names.LON));
break;
}
} else {
// No mapper known
// TODO: support geohashing
builder.field(subField, subValue);
}
} else {
builder.field(subField, subValue);
}
} else {
builder.field(subField, subValue);
}
}
builder.endObject();
} else {
if (mapper instanceof FieldMapper) {
FieldMapper fieldMapper = (FieldMapper)mapper;
if (!(fieldMapper instanceof MetadataFieldMapper)) {
if (field != null) {
builder.field(field, fieldMapper.fieldType().valueForDisplay(value));
} else {
builder.value((fieldMapper==null) ? value : fieldMapper.fieldType().valueForDisplay(value));
}
}
} else if (mapper instanceof ObjectMapper) {
ObjectMapper objectMapper = (ObjectMapper)mapper;
if (!objectMapper.isEnabled()) {
builder.field(field, value);
} else {
throw new IOException("Unexpected object value ["+value+"]");
}
}
}
}
public static XContentBuilder buildDocument(DocumentMapper documentMapper, Map<String, Object> docMap, boolean humanReadable) throws IOException {
return buildDocument(documentMapper, docMap, humanReadable, false);
}
public static XContentBuilder buildDocument(DocumentMapper documentMapper, Map<String, Object> docMap, boolean humanReadable, boolean forStaticDocument) throws IOException {
XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON).humanReadable(true);
builder.startObject();
for(String field : docMap.keySet()) {
if (field.equals(ParentFieldMapper.NAME)) continue;
FieldMapper fieldMapper = documentMapper.mappers().smartNameFieldMapper(field);
if (fieldMapper != null) {
if (forStaticDocument && !isStaticOrPartitionKey(fieldMapper))
continue;
toXContent(builder, fieldMapper, field, docMap.get(field));
} else {
ObjectMapper objectMapper = documentMapper.objectMappers().get(field);
if (objectMapper != null) {
if (forStaticDocument && !isStaticOrPartitionKey(objectMapper))
continue;
toXContent(builder, objectMapper, field, docMap.get(field));
} else {
Loggers.getLogger(ClusterService.class).error("No mapper found for field "+field);
throw new IOException("No mapper found for field "+field);
}
}
}
builder.endObject();
return builder;
}
public static boolean isStaticOrPartitionKey(Mapper mapper) {
return mapper.cqlStaticColumn() || mapper.cqlPartitionKey();
}
public static final String PERCOLATOR_TABLE = "_percolator";
private static final Map<String, String> cfNameToType = new ConcurrentHashMap<String, String>() {{
put(PERCOLATOR_TABLE, MapperService.PERCOLATOR_LEGACY_TYPE_NAME);
}};
public static String typeToCfName(String type) {
if (type.indexOf('-') >= 0) {
String cfName = type.replaceAll("\\-", "_");
cfNameToType.putIfAbsent(cfName, type);
return cfName;
}
return type;
}
public static String cfNameToType(String cfName) {
if (cfName.indexOf('_') >= 0) {
String type = cfNameToType.get(cfName);
if (type != null)
return type;
}
return cfName;
}
public static String indexToKsName(String index) {
return index.replaceAll("\\.", "_").replaceAll("\\-", "_");
}
public String buildCql(final String ksName, final String cfName, final String name, final ObjectMapper objectMapper) throws RequestExecutionException {
if (objectMapper.cqlStruct().equals(CqlStruct.UDT)) {
return buildUDT(ksName, cfName, name, objectMapper);
} else if (objectMapper.cqlStruct().equals(CqlStruct.MAP)) {
if (objectMapper.iterator().hasNext()) {
Mapper childMapper = objectMapper.iterator().next();
if (childMapper instanceof FieldMapper) {
return "map<text,"+childMapper.cqlType()+">";
} else if (childMapper instanceof ObjectMapper) {
return "map<text,frozen<"+buildCql(ksName,cfName,childMapper.simpleName(),(ObjectMapper)childMapper)+">>";
}
} else {
// default map prototype, no mapper to determine the value type.
return "map<text,text>";
}
}
return null;
}
public String buildUDT(final String ksName, final String cfName, final String name, final ObjectMapper objectMapper) throws RequestExecutionException {
String typeName = (objectMapper.cqlUdtName() == null) ? cfName + "_" + objectMapper.fullPath().replace('.', '_') : objectMapper.cqlUdtName();
if (!objectMapper.iterator().hasNext()) {
throw new InvalidRequestException("Cannot create an empty nested type (not supported)");
}
// create sub-type first
for (Iterator<Mapper> it = objectMapper.iterator(); it.hasNext(); ) {
Mapper mapper = it.next();
if (mapper instanceof ObjectMapper) {
buildCql(ksName, cfName, mapper.simpleName(), (ObjectMapper) mapper);
} else if (mapper instanceof BaseGeoPointFieldMapper) {
buildGeoPointType(ksName);
}
}
Pair<List<String>, List<String>> udt = getUDTInfo(ksName, typeName);
if (udt == null) {
// create new UDT.
StringBuilder create = new StringBuilder(String.format(Locale.ROOT, "CREATE TYPE IF NOT EXISTS \"%s\".\"%s\" ( ", ksName, typeName));
boolean first = true;
for (Iterator<Mapper> it = objectMapper.iterator(); it.hasNext(); ) {
Mapper mapper = it.next();
if (first)
first = false;
else
create.append(", ");
// Use only the last part of the fullname to build UDT.
int lastDotIndex = mapper.name().lastIndexOf('.');
String shortName = (lastDotIndex > 0) ? mapper.name().substring(lastDotIndex+1) : mapper.name();
if (isReservedKeyword(shortName))
logger.warn("Allowing a CQL reserved keyword in ES: {}", shortName);
create.append('\"').append(shortName).append("\" ");
if (mapper instanceof ObjectMapper) {
if (!mapper.cqlCollection().equals(CqlCollection.SINGLETON))
create.append(mapper.cqlCollectionTag()).append("<");
create.append("frozen<")
.append(ColumnIdentifier.maybeQuote(cfName+'_'+((ObjectMapper) mapper).fullPath().replace('.', '_')))
.append(">");
if (!mapper.cqlCollection().equals(CqlCollection.SINGLETON))
create.append(">");
} else if (mapper instanceof BaseGeoPointFieldMapper) {
if (!mapper.cqlCollection().equals(CqlCollection.SINGLETON))
create.append(mapper.cqlCollectionTag()).append("<");
create.append("frozen<")
.append(GEO_POINT_TYPE)
.append(">");
if (!mapper.cqlCollection().equals(CqlCollection.SINGLETON))
create.append(">");
} else if (mapper instanceof GeoShapeFieldMapper) {
if (!mapper.cqlCollection().equals(CqlCollection.SINGLETON))
create.append(mapper.cqlCollectionTag()).append("<");
create.append("frozen<")
.append("text")
.append(">");
if (!mapper.cqlCollection().equals(CqlCollection.SINGLETON))
create.append(">");
} else {
String cqlType = mapper.cqlType();
if (mapper.cqlCollection().equals(CqlCollection.SINGLETON)) {
create.append(cqlType);
} else {
create.append(mapper.cqlCollectionTag()).append("<");
if (!isNativeCql3Type(cqlType)) create.append("frozen<");
create.append(cqlType);
if (!isNativeCql3Type(cqlType)) create.append(">");
create.append(">");
}
}
}
create.append(" )");
if (logger.isDebugEnabled())
logger.debug("create UDT:"+ create.toString());
QueryProcessor.process(create.toString(), ConsistencyLevel.LOCAL_ONE);
} else {
// update existing UDT
for (Iterator<Mapper> it = objectMapper.iterator(); it.hasNext(); ) {
Mapper mapper = it.next();
int lastDotIndex = mapper.name().lastIndexOf('.');
String shortName = (lastDotIndex > 0) ? mapper.name().substring(lastDotIndex+1) : mapper.name();
if (isReservedKeyword(shortName))
logger.warn("Allowing a CQL reserved keyword in ES: {}", shortName);
StringBuilder update = new StringBuilder(String.format(Locale.ROOT, "ALTER TYPE \"%s\".\"%s\" ADD \"%s\" ", ksName, typeName, shortName));
if (!udt.left.contains(shortName)) {
if (mapper instanceof ObjectMapper) {
if (!mapper.cqlCollection().equals(CqlCollection.SINGLETON))
update.append(mapper.cqlCollectionTag()).append("<");
update.append("frozen<")
.append(cfName).append('_').append(((ObjectMapper) mapper).fullPath().replace('.', '_'))
.append(">");
if (!mapper.cqlCollection().equals(CqlCollection.SINGLETON))
update.append(">");
} else if (mapper instanceof BaseGeoPointFieldMapper) {
if (!mapper.cqlCollection().equals(CqlCollection.SINGLETON))
update.append(mapper.cqlCollectionTag()).append("<");
update.append("frozen<")
.append(GEO_POINT_TYPE)
.append(">");
if (!mapper.cqlCollection().equals(CqlCollection.SINGLETON))
update.append(">");
} else {
String cqlType = mapper.cqlType();
if (mapper.cqlCollection().equals(CqlCollection.SINGLETON)) {
update.append(cqlType);
} else {
update.append(mapper.cqlCollectionTag()).append("<");
if (!isNativeCql3Type(cqlType)) update.append("frozen<");
update.append(cqlType);
if (!isNativeCql3Type(cqlType)) update.append(">");
update.append(">");
}
}
if (logger.isDebugEnabled()) {
logger.debug("update UDT: "+update.toString());
}
QueryProcessor.process(update.toString(), ConsistencyLevel.LOCAL_ONE);
}
}
}
return typeName;
}
private static final String GEO_POINT_TYPE = "geo_point";
private static final String ATTACHEMENT_TYPE = "attachement";
private static final String COMPLETION_TYPE = "completion";
private void buildGeoPointType(String ksName) throws RequestExecutionException {
String query = String.format(Locale.ROOT, "CREATE TYPE IF NOT EXISTS \"%s\".\"%s\" ( %s double, %s double)",
ksName, GEO_POINT_TYPE,org.elasticsearch.index.mapper.BaseGeoPointFieldMapper.Names.LAT,org.elasticsearch.index.mapper.BaseGeoPointFieldMapper.Names.LON);
QueryProcessor.process(query, ConsistencyLevel.LOCAL_ONE);
}
private void buildAttachementType(String ksName) throws RequestExecutionException {
String query = String.format(Locale.ROOT, "CREATE TYPE IF NOT EXISTS \"%s\".\"%s\" (context text, content_type text, content_length bigint, date timestamp, title text, author text, keywords text, language text)", ksName, ATTACHEMENT_TYPE);
QueryProcessor.process(query, ConsistencyLevel.LOCAL_ONE);
}
private void buildCompletionType(String ksName) throws RequestExecutionException {
String query = String.format(Locale.ROOT, "CREATE TYPE IF NOT EXISTS \"%s\".\"%s\" (input list<text>, contexts text, weight bigint)", ksName, COMPLETION_TYPE);
QueryProcessor.process(query, ConsistencyLevel.LOCAL_ONE);
}
public static int replicationFactor(String keyspace) {
if (Schema.instance != null && Schema.instance.getKeyspaceInstance(keyspace) != null) {
AbstractReplicationStrategy replicationStrategy = Schema.instance.getKeyspaceInstance(keyspace).getReplicationStrategy();
int rf = replicationStrategy.getReplicationFactor();
if (replicationStrategy instanceof NetworkTopologyStrategy) {
rf = ((NetworkTopologyStrategy)replicationStrategy).getReplicationFactor(DatabaseDescriptor.getLocalDataCenter());
}
return rf;
}
return 0;
}
public ClusterState updateNumberOfReplica(ClusterState currentState) {
MetaData.Builder metaDataBuilder = MetaData.builder(currentState.metaData());
for(Iterator<IndexMetaData> it = currentState.metaData().iterator(); it.hasNext(); ) {
IndexMetaData indexMetaData = it.next();
IndexMetaData.Builder indexMetaDataBuilder = IndexMetaData.builder(indexMetaData);
int rf = replicationFactor(indexMetaData.keyspace());
indexMetaDataBuilder.numberOfReplicas( Math.max(0, rf - 1) );
metaDataBuilder.put(indexMetaDataBuilder.build(), false);
}
return ClusterState.builder(currentState).metaData(metaDataBuilder.build()).build();
}
public ClusterState updateNumberOfShardsAndReplicas(ClusterState currentState) {
int numberOfNodes = currentState.nodes().getSize();
if (numberOfNodes == 0)
return currentState; // for testing purposes.
MetaData.Builder metaDataBuilder = MetaData.builder(currentState.metaData());
for(Iterator<IndexMetaData> it = currentState.metaData().iterator(); it.hasNext(); ) {
IndexMetaData indexMetaData = it.next();
IndexMetaData.Builder indexMetaDataBuilder = IndexMetaData.builder(indexMetaData);
indexMetaDataBuilder.numberOfShards(numberOfNodes);
int rf = replicationFactor(indexMetaData.keyspace());
indexMetaDataBuilder.numberOfReplicas( Math.max(0, rf - 1) );
metaDataBuilder.put(indexMetaDataBuilder.build(), false);
}
return ClusterState.builder(currentState).metaData(metaDataBuilder.build()).build();
}
/**
* Reload cluster metadata from elastic_admin.metadatatable row.
* Should only be called when user keyspaces are initialized.
*/
public void submitRefreshMetaData(final MetaData metaData, final String source) {
submitStateUpdateTask(source, new ClusterStateUpdateTask() {
@Override
public ClusterState execute(ClusterState currentState) {
return ClusterState.builder(currentState).metaData(metaData).build();
}
@Override
public void onFailure(String source, Exception t) {
logger.error((Supplier<?>) () -> new ParameterizedMessage("unexpected failure during [{}]", source), t);
}
});
}
public void submitNumberOfShardsAndReplicasUpdate(final String source) {
submitStateUpdateTask(source, new ClusterStateUpdateTask() {
@Override
public ClusterState execute(ClusterState currentState) {
return updateNumberOfShardsAndReplicas(currentState);
}
@Override
public void onFailure(String source, Exception t) {
logger.error((Supplier<?>) () -> new ParameterizedMessage("unexpected failure during [{}]", source), t);
}
});
}
public void updateRoutingTable() {
submitStateUpdateTask("Update-routing-table" , new ClusterStateUpdateTask() {
@Override
public ClusterState execute(ClusterState currentState) {
return ClusterState.builder(currentState).incrementVersion().build();
}
@Override
public void onFailure(String source, Exception t) {
logger.error((Supplier<?>) () -> new ParameterizedMessage("unexpected failure during [{}]", source), t);
}
});
}
public void updateTableSchema(final MapperService mapperService, final MappingMetaData mappingMd) throws IOException {
try {
String ksName = mapperService.keyspace();
String cfName = ClusterService.typeToCfName(mappingMd.type());
createIndexKeyspace(ksName, settings.getAsInt(SETTING_NUMBER_OF_REPLICAS, 0) +1);
CFMetaData cfm = Schema.instance.getCFMetaData(ksName, cfName);
boolean newTable = (cfm == null);
DocumentMapper docMapper = mapperService.documentMapper(mappingMd.type());
Map<String, Object> mappingMap = mappingMd.sourceAsMap();
Set<String> columns = new HashSet();
if (docMapper.sourceMapper().enabled())
columns.add(SourceFieldMapper.NAME);
if (mappingMap.get("properties") != null)
columns.addAll( ((Map<String, Object>)mappingMap.get("properties")).keySet() );
logger.debug("Updating CQL3 schema {}.{} columns={}", ksName, cfName, columns);
StringBuilder columnsList = new StringBuilder();
Map<String,Boolean> columnsMap = new HashMap<String, Boolean>(columns.size());
String[] primaryKeyList = new String[(newTable) ? columns.size()+1 : cfm.partitionKeyColumns().size()+cfm.clusteringColumns().size()];
int primaryKeyLength = 0;
int partitionKeyLength = 0;
for (String column : columns) {
if (isReservedKeyword(column))
logger.warn("Allowing a CQL reserved keyword in ES: {}", column);
if (column.equals(TokenFieldMapper.NAME))
continue; // ignore pseudo column known by Elasticsearch
if (columnsList.length() > 0)
columnsList.append(',');
String cqlType = null;
boolean isStatic = false;
FieldMapper fieldMapper = docMapper.mappers().smartNameFieldMapper(column);
if (fieldMapper != null) {
if (fieldMapper instanceof BaseGeoPointFieldMapper) {
ColumnDefinition cdef = (newTable) ? null : cfm.getColumnDefinition(new ColumnIdentifier(column, true));
if (cdef != null && cdef.type instanceof UTF8Type) {
// index geohash stored as text in cassandra.
cqlType = "text";
} else {
// create a geo_point UDT to store lat,lon
cqlType = GEO_POINT_TYPE;
buildGeoPointType(ksName);
}
} else if (fieldMapper instanceof GeoShapeFieldMapper) {
cqlType = "text";
} else if (fieldMapper instanceof CompletionFieldMapper) {
cqlType = COMPLETION_TYPE;
buildCompletionType(ksName);
} else if (fieldMapper.getClass().getName().equals("org.elasticsearch.mapper.attachments.AttachmentMapper")) {
// attachement is a plugin, so class may not found.
cqlType = ATTACHEMENT_TYPE;
buildAttachementType(ksName);
} else if (fieldMapper instanceof SourceFieldMapper) {
cqlType = "blob";
} else {
cqlType = fieldMapper.cqlType();
if (cqlType == null) {
logger.warn("Ignoring field [{}] type [{}]", column, fieldMapper.name());
continue;
}
}
columnsMap.put(column, fieldMapper.cqlPartialUpdate());
if (fieldMapper.cqlPrimaryKeyOrder() >= 0) {
if (fieldMapper.cqlPrimaryKeyOrder() < primaryKeyList.length && primaryKeyList[fieldMapper.cqlPrimaryKeyOrder()] == null) {
primaryKeyList[fieldMapper.cqlPrimaryKeyOrder()] = column;
primaryKeyLength = Math.max(primaryKeyLength, fieldMapper.cqlPrimaryKeyOrder()+1);
if (fieldMapper.cqlPartitionKey()) {
partitionKeyLength++;
}
} else {
throw new Exception("Wrong primary key order for column "+column);
}
}
if (!isNativeCql3Type(cqlType)) {
cqlType = "frozen<" + cqlType + ">";
}
if (!fieldMapper.cqlCollection().equals(CqlCollection.SINGLETON)) {
cqlType = fieldMapper.cqlCollectionTag()+"<" + cqlType + ">";
}
isStatic = fieldMapper.cqlStaticColumn();
} else {
ObjectMapper objectMapper = docMapper.objectMappers().get(column);
if (objectMapper == null) {
logger.warn("Cannot infer CQL type from object mapping for field [{}]", column);
continue;
}
columnsMap.put(column, objectMapper.cqlPartialUpdate());
if (objectMapper.cqlPrimaryKeyOrder() >= 0) {
if (objectMapper.cqlPrimaryKeyOrder() < primaryKeyList.length && primaryKeyList[objectMapper.cqlPrimaryKeyOrder()] == null) {
primaryKeyList[objectMapper.cqlPrimaryKeyOrder()] = column;
primaryKeyLength = Math.max(primaryKeyLength, objectMapper.cqlPrimaryKeyOrder()+1);
if (objectMapper.cqlPartitionKey()) {
partitionKeyLength++;
}
} else {
throw new Exception("Wrong primary key order for column "+column);
}
}
if (!objectMapper.isEnabled()) {
logger.debug("Object [{}] not enabled stored as text", column);
cqlType = "text";
} else if (objectMapper.cqlStruct().equals(CqlStruct.MAP)) {
// TODO: check columnName exists and is map<text,?>
cqlType = buildCql(ksName, cfName, column, objectMapper);
if (!objectMapper.cqlCollection().equals(CqlCollection.SINGLETON)) {
cqlType = objectMapper.cqlCollectionTag()+"<"+cqlType+">";
}
//logger.debug("Expecting column [{}] to be a map<text,?>", column);
} else if (objectMapper.cqlStruct().equals(CqlStruct.UDT)) {
// enabled=false => opaque json object
cqlType = (objectMapper.isEnabled()) ? "frozen<" + ColumnIdentifier.maybeQuote(buildCql(ksName, cfName, column, objectMapper)) + ">" : "text";
if (!objectMapper.cqlCollection().equals(CqlCollection.SINGLETON) && !(cfName.equals(PERCOLATOR_TABLE) && column.equals("query"))) {
cqlType = objectMapper.cqlCollectionTag()+"<"+cqlType+">";
}
}
isStatic = objectMapper.cqlStaticColumn();
}
if (newTable) {
if (cqlType != null) {
columnsList.append("\"").append(column).append("\" ").append(cqlType);
if (isStatic) columnsList.append(" static");
}
} else {
ColumnDefinition cdef = cfm.getColumnDefinition(new ColumnIdentifier(column, true));
if (cqlType != null) {
if (cdef == null) {
for(int i=0; i < primaryKeyLength; i++) {
if (primaryKeyList[i] != null && primaryKeyList[i].equals(column))
throw new Exception("Cannot alter primary key of an existing table");
}
try {
String query = String.format(Locale.ROOT, "ALTER TABLE \"%s\".\"%s\" ADD \"%s\" %s %s", ksName, cfName, column, cqlType,(isStatic) ? "static":"");
logger.debug(query);
QueryProcessor.process(query, ConsistencyLevel.LOCAL_ONE);
} catch (Exception e) {
logger.warn("Failed to alter table {}.{} column [{}] with type [{}]", e, ksName, cfName, column, cqlType);
}
} else {
// check that the existing column matches the provided mapping
// TODO: do this check for collection
String existingCqlType = cdef.type.asCQL3Type().toString();
if (!cdef.type.isCollection()) {
if (cqlType.equals("frozen<geo_point>")) {
if (!(existingCqlType.equals("text") || existingCqlType.equals("frozen<geo_point>"))) {
throw new IOException("geo_point cannot be mapped to column ["+column+"] with CQL type ["+cqlType+"]. ");
}
} else
// cdef.type.asCQL3Type() does not include frozen, nor quote, so can do this check for collection.
if (!existingCqlType.equals(cqlType) &&
!cqlType.equals("frozen<"+existingCqlType+">") &&
!(existingCqlType.endsWith("uuid") && cqlType.equals("text")) && // #74 uuid is mapped as keyword
!(existingCqlType.equals("timeuuid") && (cqlType.equals("timestamp") || cqlType.equals("text"))) &&
!(existingCqlType.equals("date") && cqlType.equals("timestamp")) &&
!(existingCqlType.equals("time") && cqlType.equals("bigint"))
) // timeuuid can be mapped to date
throw new IOException("Existing column ["+column+"] type ["+existingCqlType+"] mismatch with inferred type ["+cqlType+"]");
}
}
}
}
}
// add _parent column if necessary. Parent and child documents should have the same partition key.
if (docMapper.parentFieldMapper().active() && docMapper.parentFieldMapper().pkColumns() == null) {
if (newTable) {
// _parent is a JSON array representation of the parent PK.
if (columnsList.length() > 0)
columnsList.append(", ");
columnsList.append("\"_parent\" text");
} else {
try {
String query = String.format(Locale.ROOT, "ALTER TABLE \"%s\".\"%s\" ADD \"_parent\" text", ksName, cfName);
logger.debug(query);
QueryProcessor.process(query, ConsistencyLevel.LOCAL_ONE);
} catch (org.apache.cassandra.exceptions.InvalidRequestException e) {
logger.warn("Cannot alter table {}.{} column _parent with type text", e, ksName, cfName);
}
}
}
if (newTable) {
if (partitionKeyLength == 0) {
// build a default primary key _id text
if (columnsList.length() > 0) columnsList.append(',');
columnsList.append("\"").append(ELASTIC_ID_COLUMN_NAME).append("\" text");
primaryKeyList[0] = ELASTIC_ID_COLUMN_NAME;
primaryKeyLength = 1;
partitionKeyLength = 1;
}
// build the primary key definition
StringBuilder primaryKey = new StringBuilder();
primaryKey.append("(");
for(int i=0; i < primaryKeyLength; i++) {
if (primaryKeyList[i] == null) throw new Exception("Incomplet primary key definition at index "+i);
primaryKey.append("\"").append( primaryKeyList[i] ).append("\"");
if ( i == partitionKeyLength -1) primaryKey.append(")");
if (i+1 < primaryKeyLength ) primaryKey.append(",");
}
String query = String.format(Locale.ROOT, "CREATE TABLE IF NOT EXISTS \"%s\".\"%s\" ( %s, PRIMARY KEY (%s) ) WITH COMMENT='Auto-created by Elassandra'",
ksName, cfName, columnsList.toString(), primaryKey.toString());
logger.debug(query);
QueryProcessor.process(query, ConsistencyLevel.LOCAL_ONE);
}
updateMapping(mapperService.index().getName(), mappingMd);
} catch (Throwable e) {
throw new IOException(e.getMessage(), e);
}
}
@Override
protected void doStart() {
super.doStart();
// add post-applied because 2i shoukd be created/deleted after that cassandra indices have taken the new mapping.
this.addStateApplier(cassandraSecondaryIndicesApplier);
// start a thread for asynchronous CQL schema update, always the last update.
Runnable task = new Runnable() {
@Override
public void run() {
while (true) {
try{
ClusterService.this.metadataToSaveSemaphore.acquire();
MetadataSchemaUpdate metadataSchemaUpdate = ClusterService.this.lastMetadataToSave.getAndSet(null);
if (metadataSchemaUpdate != null) {
if (metadataSchemaUpdate.version < state().metaData().version()) {
logger.trace("Giveup {}.{}.comment obsolete update of metadata.version={} timestamp={}",
ELASTIC_ADMIN_KEYSPACE, ELASTIC_ADMIN_METADATA_TABLE,
metadataSchemaUpdate.version, metadataSchemaUpdate.timestamp);
} else {
logger.trace("Applying {}.{}.comment update with metadata.version={} timestamp={}",
ELASTIC_ADMIN_KEYSPACE, ELASTIC_ADMIN_METADATA_TABLE,
metadataSchemaUpdate.version, metadataSchemaUpdate.timestamp);
// delayed CQL schema update with timestamp = time of cluster state update
CFMetaData cfm = getCFMetaData(ELASTIC_ADMIN_KEYSPACE, ELASTIC_ADMIN_METADATA_TABLE).copy();
TableAttributes attrs = new TableAttributes();
attrs.addProperty(TableParams.Option.COMMENT.toString(), metadataSchemaUpdate.metaDataString);
cfm.params( attrs.asAlteredTableParams(cfm.params) );
MigrationManager.announceColumnFamilyUpdate(cfm, null, false, metadataSchemaUpdate.timestamp);
/*
QueryProcessor.executeOnceInternal(String.format(Locale.ROOT, "ALTER TABLE \"%s\".\"%s\" WITH COMMENT = '%s'",
elasticAdminKeyspaceName, ELASTIC_ADMIN_METADATA_TABLE, metadataSchemaUpdate.metaDataString));
*/
}
}
} catch(Exception e) {
logger.warn("Failed to update CQL schema",e);
}
}
}
};
new Thread(task, "metadataSchemaUpdater").start();
}
public void updateMapping(String ksName, MappingMetaData mapping) {
cassandraSecondaryIndicesApplier.updateMapping( ksName, mapping);
}
public void recoverShard(String index) {
cassandraSecondaryIndicesApplier.recoverShard(index);
}
@Override
protected void publishAndApplyChanges(TaskInputs taskInputs, TaskOutputs taskOutputs) {
ClusterState previousClusterState = taskOutputs.previousClusterState;
ClusterState newClusterState = taskOutputs.newClusterState;
final Discovery.AckListener ackListener = newClusterState.nodes().isLocalNodeElectedMaster() ?
taskOutputs.createAckListener(threadPool, newClusterState) :
null;
// try to update cluster state.
long startTimeNS = System.nanoTime();
boolean presistedMetadata = false;
CassandraDiscovery.MetaDataVersionAckListener metaDataVersionAckListerner = null;
try {
String newClusterStateMetaDataString = MetaData.Builder.toXContent(newClusterState.metaData(), MetaData.CASSANDRA_FORMAT_PARAMS);
String previousClusterStateMetaDataString = MetaData.Builder.toXContent(previousClusterState.metaData(), MetaData.CASSANDRA_FORMAT_PARAMS);
if (!newClusterStateMetaDataString.equals(previousClusterStateMetaDataString) && !newClusterState.blocks().disableStatePersistence() && taskOutputs.doPersistMetadata) {
// update MeteData.version+cluster_uuid
presistedMetadata = true;
newClusterState = ClusterState.builder(newClusterState)
.metaData(MetaData.builder(newClusterState.metaData()).incrementVersion().build())
.incrementVersion()
.build();
// try to persist new metadata in cassandra.
if (presistedMetadata && newClusterState.nodes().getSize() > 1) {
// register the X2 listener before publishing to avoid dead locks !
metaDataVersionAckListerner = this.discovery.new MetaDataVersionAckListener(newClusterState.metaData().version(), ackListener, newClusterState);
}
try {
persistMetaData(previousClusterState.metaData(), newClusterState.metaData(), taskInputs.summary);
publishX2(newClusterState);
} catch (ConcurrentMetaDataUpdateException e) {
if (metaDataVersionAckListerner != null)
metaDataVersionAckListerner.abort();
// should replay the task later when current cluster state will match the expected metadata uuid and version
logger.warn("Cannot overwrite persistent metadata, will resubmit task when metadata.version > {}", previousClusterState.metaData().version());
final long resubmitTimeMillis = System.currentTimeMillis();
ClusterService.this.addListener(new ClusterStateListener() {
@Override
public void clusterChanged(ClusterChangedEvent event) {
if (event.metaDataChanged()) {
final long lostTimeMillis = System.currentTimeMillis() - resubmitTimeMillis;
Priority priority = Priority.URGENT;
TimeValue timeout = TimeValue.timeValueSeconds(30*1000 - lostTimeMillis);
ClusterStateTaskConfig config;
Map<Object, ClusterStateTaskListener> map = new HashMap<Object, ClusterStateTaskListener>();
for (final ClusterServiceTaskBatcher.UpdateTask updateTask : taskInputs.updateTasks) {
map.put( updateTask.task, updateTask.listener);
priority = updateTask.priority();
if (updateTask.task instanceof ClusterStateUpdateTask) {
timeout = TimeValue.timeValueMillis( ((ClusterStateUpdateTask)updateTask.task).timeout().getMillis() - lostTimeMillis);
} else if (updateTask.task instanceof ClusterStateUpdateRequest) {
timeout = TimeValue.timeValueMillis( ((ClusterStateUpdateRequest)updateTask.task).masterNodeTimeout().getMillis() - lostTimeMillis);
}
}
logger.warn("metadata.version={} => resubmit delayed update source={} tasks={} priority={} remaing timeout={}",
ClusterService.this.state().metaData().version(), taskInputs.summary, taskInputs.updateTasks, priority, timeout);
ClusterService.this.submitStateUpdateTasks(taskInputs.summary, map, ClusterStateTaskConfig.build(priority, timeout), taskInputs.executor);
ClusterService.this.removeListener(this); // replay only once.
}
}
});
long currentVersion = readMetaDataVersion(ConsistencyLevel.LOCAL_QUORUM);
if (currentVersion > previousClusterState.metaData().version())
// trigger a metadat update from metadata table if not yet triggered by a gossip change.
this.discovery.updateMetadata("refresh-metadata", currentVersion);
return;
}
}
} catch (Exception e) {
// Unexpected issue => ack with failure.
ackListener.onNodeAck(this.localNode(), e);
TimeValue executionTime = TimeValue.timeValueMillis(Math.max(0, TimeValue.nsecToMSec(System.nanoTime() - startTimeNS)));
if (logger.isTraceEnabled()) {
StringBuilder sb = new StringBuilder("failed to execute cluster state update in ").append(executionTime)
.append(", state:\nversion [")
.append(previousClusterState.version()).
append("], source [").append(taskInputs.summary).append("]\n");
logger.warn(sb.toString(), e);
// TODO resubmit task on next cluster state change
} else {
logger.error("Cassandra issue:", e);
}
if (metaDataVersionAckListerner != null)
metaDataVersionAckListerner.abort();
return;
}
try {
if (logger.isTraceEnabled()) {
StringBuilder sb = new StringBuilder("cluster state updated, source [").append(taskInputs.summary).append("]\n");
sb.append(newClusterState.toString());
logger.trace(sb.toString());
} else if (logger.isDebugEnabled()) {
logger.debug("cluster state updated, version [{}], source [{}]", newClusterState.version(), taskInputs.summary);
}
// update routing table.
newClusterState = ClusterState.builder(newClusterState).routingTable(RoutingTable.build(this, newClusterState)).build();
ClusterChangedEvent clusterChangedEvent = new ClusterChangedEvent(taskInputs.summary, newClusterState, previousClusterState);
// new cluster state, notify all listeners
final DiscoveryNodes.Delta nodesDelta = clusterChangedEvent.nodesDelta();
if (nodesDelta.hasChanges() && logger.isInfoEnabled()) {
String summary = nodesDelta.shortSummary();
if (summary.length() > 0) {
logger.info("{}, reason: {}", summary, taskInputs.summary);
}
}
nodeConnectionsService.connectToNodes(newClusterState.nodes());
logger.debug("applying cluster state version {}", newClusterState.version());
try {
// nothing to do until we actually recover from the gateway or any other block indicates we need to disable persistency
if (clusterChangedEvent.state().blocks().disableStatePersistence() == false && clusterChangedEvent.metaDataChanged()) {
final Settings incomingSettings = clusterChangedEvent.state().metaData().settings();
clusterSettings.applySettings(incomingSettings);
}
} catch (Exception ex) {
logger.warn("failed to apply cluster settings", ex);
}
nodeConnectionsService.disconnectFromNodesExcept(newClusterState.nodes());
// notify highPriorityStateAppliers, including IndicesClusterStateService to start shards and update mapperServices.
if (logger.isTraceEnabled())
logger.trace("notfiy highPriorityStateAppliers={}",highPriorityStateAppliers);
for (ClusterStateApplier applier : this.highPriorityStateAppliers) {
try {
applier.applyClusterState(clusterChangedEvent);
} catch (Exception ex) {
logger.warn("failed to notify ClusterStateListener", ex);
}
}
// update the current cluster state
final ClusterState newClusterState2 = newClusterState;
updateState(css -> newClusterState2);
if (logger.isTraceEnabled())
logger.trace("set local clusterState version={} metadata.version={}", newClusterState.version(), newClusterState.metaData().version());
// notifiy listener, including ElasticSecondaryIndex instances.
Stream.concat(clusterStateListeners.stream(), timeoutClusterStateListeners.stream()).forEach(listener -> {
try {
logger.trace("calling [{}] with change to version [{}] metadata.version=[{}]", listener, newClusterState2.version(), newClusterState2.metaData().version());
listener.clusterChanged(clusterChangedEvent);
} catch (Exception ex) {
logger.warn("failed to notify ClusterStateListener", ex);
}
});
// update cluster state routing table
// TODO: update the routing table only for updated indices.
newClusterState = ClusterState.builder(newClusterState).routingTable(RoutingTable.build(this, newClusterState)).build();
final ClusterState newClusterState3 = newClusterState;
updateState(css -> newClusterState3);
// coordinator node
if (presistedMetadata && metaDataVersionAckListerner != null && newClusterState.nodes().getSize() > 1) {
try {
if (logger.isInfoEnabled())
logger.debug("Waiting MetaData.version = {} for all other alive nodes", newClusterState.metaData().version() );
if (!metaDataVersionAckListerner.await(30L, TimeUnit.SECONDS)) {
logger.warn("Timeout waiting MetaData.version={}", newClusterState.metaData().version());
} else {
logger.debug("Metadata.version={} applied by all alive nodes", newClusterState.metaData().version());
}
} catch (Throwable e) {
final long version = newClusterState.metaData().version();
logger.error((Supplier<?>) () -> new ParameterizedMessage("Interruped while waiting MetaData.version = {}", version), e);
}
}
// notify normalPriorityStateAppliers with the new cluster state,
// including CassandraSecondaryIndicesApplier to create new C* 2i instances when newClusterState is applied by all nodes.
if (logger.isTraceEnabled())
logger.trace("notifiy normalPriorityStateAppliers={} before acknowlegdging listeners",normalPriorityStateAppliers);
for (ClusterStateApplier applier : normalPriorityStateAppliers) {
try {
applier.applyClusterState(clusterChangedEvent);
} catch (Exception ex) {
logger.warn("failed to notify ClusterStateListener", ex);
}
}
// non-coordinator node
if (!presistedMetadata && newClusterState.metaData().version() > previousClusterState.metaData().version()) {
// For non-coordinator nodes, publish in gossip state the applied metadata.uuid and version.
// after mapping change have been applied to secondary index in normalPriorityStateAppliers
publishX2(newClusterState);
}
//manual ack only from the master at the end of the publish
if (newClusterState.nodes().isLocalNodeElectedMaster()) {
try {
ackListener.onNodeAck(newClusterState.nodes().getLocalNode(), null);
} catch (Exception e) {
final DiscoveryNode localNode = newClusterState.nodes().getLocalNode();
logger.debug(
(Supplier<?>) () -> new ParameterizedMessage("error while processing ack for master node [{}]", localNode),
e);
}
}
if (logger.isTraceEnabled())
logger.trace("notify lowPriorityStateAppliers={} after acknowlegdging listeners", lowPriorityStateAppliers);
for (ClusterStateApplier applier : lowPriorityStateAppliers) {
try {
applier.applyClusterState(clusterChangedEvent);
} catch (Exception ex) {
logger.warn("failed to notify ClusterStateListener", ex);
}
}
// notify processed listeners
taskOutputs.processedDifferentClusterState(previousClusterState, newClusterState);
if (newClusterState.nodes().isLocalNodeElectedMaster()) {
try {
taskOutputs.clusterStatePublished(clusterChangedEvent);
} catch (Exception e) {
logger.error(
(Supplier<?>) () -> new ParameterizedMessage(
"exception thrown while notifying executor of new cluster state publication [{}]",
taskInputs.summary),
e);
}
}
if (this.shardStartedBarrier != null) {
shardStartedBarrier.isReadyToIndex(newClusterState);
}
TimeValue executionTime = TimeValue.timeValueMillis(Math.max(0, TimeValue.nsecToMSec(System.nanoTime() - startTimeNS)));
logger.debug("processed [{}]: took {} done applying updated cluster_state (version: {}, uuid: {}, metadata.version: {})", taskInputs.summary, executionTime, newClusterState.version(), newClusterState.stateUUID(), newClusterState.metaData().version());
warnAboutSlowTaskIfNeeded(executionTime, taskInputs.summary);
} catch (Throwable t) {
TimeValue executionTime = TimeValue.timeValueMillis(Math.max(0, TimeValue.nsecToMSec(System.nanoTime() - startTimeNS)));
StringBuilder sb = new StringBuilder("failed to apply updated cluster state in ").append(executionTime).append(":\nversion [").append(newClusterState.version())
.append("], uuid [").append(newClusterState.stateUUID()).append("], source [").append(taskInputs.summary).append("]\n");
sb.append(newClusterState.nodes());
sb.append(newClusterState.routingTable());
sb.append(newClusterState.getRoutingNodes());
logger.warn(sb.toString(), t);
// TODO: do we want to call updateTask.onFailure here?
}
}
public void createSecondaryIndices(final IndexMetaData indexMetaData) throws IOException {
String ksName = indexMetaData.keyspace();
String className = indexMetaData.getSettings().get(IndexMetaData.SETTING_SECONDARY_INDEX_CLASS, this.settings.get(SETTING_CLUSTER_SECONDARY_INDEX_CLASS, defaultSecondaryIndexClass.getName()));
for(ObjectCursor<MappingMetaData> cursor: indexMetaData.getMappings().values()) {
createSecondaryIndex(ksName, cursor.value, className);
}
}
// build secondary indices when shard is started and mapping applied
public void createSecondaryIndex(String ksName, MappingMetaData mapping, String className) throws IOException {
final String cfName = typeToCfName(mapping.type());
final CFMetaData cfm = Schema.instance.getCFMetaData(ksName, cfName);
boolean found = false;
if (cfm != null && cfm.getIndexes() != null) {
for(IndexMetadata indexMetadata : cfm.getIndexes()) {
if (indexMetadata.isCustom() && indexMetadata.options.get(IndexTarget.CUSTOM_INDEX_OPTION_NAME).equals(className)) {
found = true;
break;
}
}
if (!found) {
String indexName = buildIndexName(cfName);
String query = String.format(Locale.ROOT, "CREATE CUSTOM INDEX IF NOT EXISTS \"%s\" ON \"%s\".\"%s\" () USING '%s'",
indexName, ksName, cfName, className);
logger.debug(query);
try {
QueryProcessor.process(query, ConsistencyLevel.LOCAL_ONE);
} catch (Throwable e) {
throw new IOException("Failed to process query=["+query+"]:"+e.getMessage(), e);
}
}
} else {
logger.warn("Cannot create SECONDARY INDEX, [{}.{}] does not exist",ksName, cfName);
}
}
public void dropSecondaryIndices(final IndexMetaData indexMetaData) throws RequestExecutionException {
String ksName = indexMetaData.keyspace();
for(CFMetaData cfMetaData : Schema.instance.getKSMetaData(ksName).tablesAndViews()) {
if (cfMetaData.isCQLTable())
dropSecondaryIndex(cfMetaData);
}
}
public void dropSecondaryIndex(String ksName, String cfName) throws RequestExecutionException {
CFMetaData cfMetaData = Schema.instance.getCFMetaData(ksName, cfName);
if (cfMetaData != null)
dropSecondaryIndex(cfMetaData);
}
public void dropSecondaryIndex(CFMetaData cfMetaData) throws RequestExecutionException {
for(IndexMetadata idx : cfMetaData.getIndexes()) {
if (idx.isCustom()) {
String className = idx.options.get(IndexTarget.CUSTOM_INDEX_OPTION_NAME);
if (className != null && className.endsWith("ElasticSecondaryIndex")) {
logger.debug("DROP INDEX IF EXISTS {}.{}", cfMetaData.ksName, idx.name);
QueryProcessor.process(String.format(Locale.ROOT, "DROP INDEX IF EXISTS \"%s\".\"%s\"",
cfMetaData.ksName, idx.name),
ConsistencyLevel.LOCAL_ONE);
}
}
}
}
public void dropTables(final IndexMetaData indexMetaData) throws RequestExecutionException {
String ksName = indexMetaData.keyspace();
for(ObjectCursor<String> cfName : indexMetaData.getMappings().keys()) {
dropTable(ksName, cfName.value);
}
}
public void dropTable(String ksName, String cfName) throws RequestExecutionException {
CFMetaData cfm = Schema.instance.getCFMetaData(ksName, cfName);
if (cfm != null) {
logger.warn("DROP TABLE IF EXISTS {}.{}", ksName, cfName);
QueryProcessor.process(String.format(Locale.ROOT, "DROP TABLE IF EXISTS \"%s\".\"%s\"", ksName, cfName), ConsistencyLevel.LOCAL_ONE);
}
}
public static String buildIndexName(final String cfName) {
return new StringBuilder("elastic_")
.append(cfName)
.append("_idx").toString();
}
public static String buildIndexName(final String cfName, final String colName) {
return new StringBuilder("elastic_")
.append(cfName).append('_')
.append(colName.replaceAll("\\W+", "_"))
.append("_idx").toString();
}
public static CFMetaData getCFMetaData(final String ksName, final String cfName) throws ActionRequestValidationException {
CFMetaData metadata = Schema.instance.getCFMetaData(ksName, cfName);
if (metadata == null) {
ActionRequestValidationException arve = new ActionRequestValidationException();
arve.addValidationError(ksName+"."+cfName+" table does not exists");;
throw arve;
}
return metadata;
}
public Map<String, GetField> flattenGetField(final String[] fieldFilter, final String path, final Object node, Map<String, GetField> flatFields) {
if ((node instanceof List) || (node instanceof Set)) {
for(Object o : ((Collection)node)) {
flattenGetField(fieldFilter, path, o, flatFields);
}
} else if (node instanceof Map) {
for (String key : ((Map<String,Object>)node).keySet()) {
String fullname = (path.length() > 0) ? path + '.' + key : key;
flattenGetField(fieldFilter, fullname, ((Map<String,Object>)node).get(key), flatFields);
}
} else {
if (fieldFilter != null) {
for (String f : fieldFilter) {
if (path.equals(f)) {
GetField gf = flatFields.get(path);
if (gf == null) {
gf = new GetField(path, ImmutableList.builder().add(node).build());
} else {
gf = new GetField(path, ImmutableList.builder().addAll(gf.getValues()).add(node).build());
}
flatFields.put(path, gf);
break;
}
}
}
}
return flatFields;
}
public Map<String, List<Object>> flattenTree(final Set<String> neededFiedls, final String path, final Object node, Map<String, List<Object>> flatMap) {
if ((node instanceof List) || (node instanceof Set)) {
for(Object o : ((Collection)node)) {
flattenTree(neededFiedls, path, o, flatMap);
}
} else if (node instanceof Map) {
for (String key : ((Map<String,Object>)node).keySet()) {
String fullname = (path.length() > 0) ? path + '.' + key : key;
flattenTree(neededFiedls, fullname, ((Map<String,Object>)node).get(key), flatMap);
}
} else {
if ((neededFiedls == null) || (neededFiedls.contains(path))) {
List<Object> values = (List<Object>) flatMap.get(path);
if (values == null) {
values = new ArrayList<Object>();
flatMap.put(path, values);
}
values.add(node);
}
}
return flatMap;
}
public boolean rowExists(final IndexService indexService, final String type, final String id)
throws InvalidRequestException, RequestExecutionException, RequestValidationException, IOException {
DocPrimaryKey docPk = parseElasticId(indexService, type, id);
return process(ConsistencyLevel.LOCAL_ONE, buildExistsQuery(indexService.mapperService().documentMapper(type), indexService.keyspace(), typeToCfName(type), id), docPk.values).size() > 0;
}
public UntypedResultSet fetchRow(final IndexService indexService, final String type, final String id, final String[] columns, Map<String,ColumnDefinition> columnDefs) throws InvalidRequestException, RequestExecutionException,
RequestValidationException, IOException {
return fetchRow(indexService, type, id, columns, ConsistencyLevel.LOCAL_ONE, columnDefs);
}
/**
* Fetch from the coordinator node.
*/
public UntypedResultSet fetchRow(final IndexService indexService, final String type, final String id, final String[] columns, final ConsistencyLevel cl, Map<String,ColumnDefinition> columnDefs) throws InvalidRequestException,
RequestExecutionException, RequestValidationException, IOException {
DocPrimaryKey docPk = parseElasticId(indexService, type, id);
return fetchRow(indexService, type, docPk, columns, cl, columnDefs);
}
/**
* Fetch from the coordinator node.
*/
public UntypedResultSet fetchRow(final IndexService indexService, final String type, final DocPrimaryKey docPk, final String[] columns, final ConsistencyLevel cl, Map<String,ColumnDefinition> columnDefs) throws InvalidRequestException,
RequestExecutionException, RequestValidationException, IOException {
return process(cl, buildFetchQuery(indexService, type, columns, docPk.isStaticDocument, columnDefs), docPk. values);
}
public Engine.GetResult fetchSourceInternal(final IndexService indexService, String type, String id, Map<String,ColumnDefinition> columnDefs, LongConsumer onRefresh) throws IOException {
long time = System.nanoTime();
DocPrimaryKey docPk = parseElasticId(indexService, type, id);
UntypedResultSet result = fetchRowInternal(indexService, type, docPk, columnDefs.keySet().toArray(new String[columnDefs.size()]), columnDefs);
onRefresh.accept(System.nanoTime() - time);
if (!result.isEmpty()) {
Map<String, Object> sourceMap = rowAsMap(indexService, type, result.one());
BytesReference source = XContentFactory.contentBuilder(XContentType.JSON).map(sourceMap).bytes();
Long timestamp = 0L;
if (sourceMap.get(TimestampFieldMapper.NAME) != null) {
timestamp = (Long) sourceMap.get(TimestampFieldMapper.NAME);
}
Long ttl = 0L;
if (sourceMap.get(TTLFieldMapper.NAME) != null) {
ttl = (Long) sourceMap.get(TTLFieldMapper.NAME);
}
// build termVector form the Cassandra doc.
return new Engine.GetResult(true, 1L, null, null);
}
return Engine.GetResult.NOT_EXISTS;
}
public UntypedResultSet fetchRowInternal(final IndexService indexService, final String cfName, final String id, final String[] columns, Map<String,ColumnDefinition> columnDefs) throws ConfigurationException, IOException {
DocPrimaryKey docPk = parseElasticId(indexService, cfName, id);
return fetchRowInternal(indexService, cfName, columns, docPk.values, docPk.isStaticDocument, columnDefs);
}
public UntypedResultSet fetchRowInternal(final IndexService indexService, final String cfName, final DocPrimaryKey docPk, final String[] columns, Map<String,ColumnDefinition> columnDefs) throws ConfigurationException, IOException {
return fetchRowInternal(indexService, cfName, columns, docPk.values, docPk.isStaticDocument, columnDefs);
}
public UntypedResultSet fetchRowInternal(final IndexService indexService, final String cfName, final String[] columns, final Object[] pkColumns, boolean forStaticDocument, Map<String,ColumnDefinition> columnDefs) throws ConfigurationException, IOException, IndexNotFoundException {
return QueryProcessor.executeInternal(buildFetchQuery(indexService, cfName, columns, forStaticDocument, columnDefs), pkColumns);
}
private String regularColumn(final IndexService indexService, final String type) throws IOException {
if (indexService != null) {
DocumentMapper docMapper = indexService.mapperService().documentMapper(type);
if (docMapper != null) {
for(FieldMapper fieldMapper : docMapper.mappers()) {
if (fieldMapper instanceof MetadataFieldMapper)
continue;
if (fieldMapper.cqlPrimaryKeyOrder() == -1 && !fieldMapper.cqlStaticColumn() && fieldMapper.cqlCollection() == Mapper.CqlCollection.SINGLETON) {
return fieldMapper.name();
}
}
}
}
if (logger.isDebugEnabled())
logger.debug("no regular columns for index=[{}] type=[{}]", indexService.index().getName(), type);
return null;
}
public String buildFetchQuery(final IndexService indexService, final String type, String cqlProjection, boolean forStaticDocument)
throws IndexNotFoundException, IOException
{
DocumentMapper docMapper = indexService.mapperService().documentMapper(type);
String cfName = typeToCfName(type);
DocumentMapper.CqlFragments cqlFragment = docMapper.getCqlFragments();
StringBuilder query = new StringBuilder();
final String SELECT_ = "SELECT ";
query.append("SELECT ")
.append(cqlProjection)
.append(" FROM \"").append(indexService.keyspace()).append("\".\"").append(cfName)
.append("\" WHERE ").append((forStaticDocument) ? cqlFragment.ptWhere : cqlFragment.pkWhere )
.append(" LIMIT 1");
return query.toString();
}
public String buildFetchQuery(final IndexService indexService, final String type, final String[] requiredColumns, boolean forStaticDocument, Map<String, ColumnDefinition> columnDefs)
throws IndexNotFoundException, IOException
{
DocumentMapper docMapper = indexService.mapperService().documentMapper(type);
String cfName = typeToCfName(type);
CFMetaData metadata = getCFMetaData(indexService.keyspace(), cfName);
DocumentMapper.CqlFragments cqlFragment = docMapper.getCqlFragments();
String regularColumn = null;
StringBuilder query = new StringBuilder();
final String SELECT_ = "SELECT ";
query.append(SELECT_);
for (String c : requiredColumns) {
switch(c){
case TokenFieldMapper.NAME:
query.append(query.length() > 7 ? ',':' ')
.append("token(")
.append(cqlFragment.ptCols)
.append(") as \"_token\"");
break;
case RoutingFieldMapper.NAME:
query.append(query.length() > 7 ? ',':' ')
.append( (metadata.partitionKeyColumns().size() > 1) ? "toJsonArray(" : "toString(" )
.append(cqlFragment.ptCols)
.append(") as \"_routing\"");
break;
case TTLFieldMapper.NAME:
if (regularColumn == null)
regularColumn = regularColumn(indexService, cfName);
if (regularColumn != null)
query.append(query.length() > 7 ? ',':' ').append("TTL(").append(regularColumn).append(") as \"_ttl\"");
break;
case TimestampFieldMapper.NAME:
if (regularColumn == null)
regularColumn = regularColumn(indexService, cfName);
if (regularColumn != null)
query.append(query.length() > 7 ? ',':' ').append("WRITETIME(").append(regularColumn).append(") as \"_timestamp\"");
break;
case ParentFieldMapper.NAME:
ParentFieldMapper parentMapper = docMapper.parentFieldMapper();
if (parentMapper.active()) {
query.append(query.length() > 7 ? ',':' ');
if (parentMapper.pkColumns() == null) {
// default column name for _parent should be string.
query.append("\"_parent\"");
} else {
query.append( (parentMapper.pkColumns().indexOf(',') > 0) ? "toJsonArray(" : "toString(")
.append(parentMapper.pkColumns())
.append(") as \"_parent\"");
}
}
break;
case NodeFieldMapper.NAME:
// nothing to add.
break;
default:
ColumnDefinition cd = columnDefs.get(c);
if (cd != null && (cd.isPartitionKey() || cd.isStatic() || !forStaticDocument)) {
query.append(query.length() > SELECT_.length() ? ',':' ').append("\"").append(c).append("\"");
}
}
}
if (query.length() == SELECT_.length()) {
// no column match or requiredColumn is empty, add _id to avoid CQL syntax error...
query.append("\"_id\"");
}
query.append(" FROM \"").append(indexService.keyspace()).append("\".\"").append(cfName)
.append("\" WHERE ").append((forStaticDocument) ? cqlFragment.ptWhere : cqlFragment.pkWhere )
.append(" LIMIT 1");
return query.toString();
}
public static String buildDeleteQuery(final DocumentMapper docMapper, final String ksName, final String cfName, final String id) {
return "DELETE FROM \""+ksName+"\".\""+cfName+"\" WHERE "+ docMapper.getCqlFragments().pkWhere;
}
public static String buildExistsQuery(final DocumentMapper docMapper, final String ksName, final String cfName, final String id) {
return "SELECT "+docMapper.getCqlFragments().pkCols+" FROM \""+ksName+"\".\""+cfName+"\" WHERE "+ docMapper.getCqlFragments().pkWhere;
}
public void deleteRow(final IndexService indexService, final String type, final String id, final ConsistencyLevel cl) throws InvalidRequestException, RequestExecutionException, RequestValidationException,
IOException {
String cfName = typeToCfName(type);
DocumentMapper docMapper = indexService.mapperService().documentMapper(type);
process(cl, buildDeleteQuery(docMapper, indexService.keyspace(), cfName, id), parseElasticId(indexService, type, id).values);
}
public Map<String, Object> rowAsMap(final IndexService indexService, final String type, UntypedResultSet.Row row) throws IOException {
Map<String, Object> mapObject = new HashMap<String, Object>();
rowAsMap(indexService, type, row, mapObject);
return mapObject;
}
public int rowAsMap(final IndexService indexService, final String type, UntypedResultSet.Row row, Map<String, Object> mapObject) throws IOException {
Object[] values = rowAsArray(indexService, type, row);
int i=0;
int j=0;
for(ColumnSpecification colSpec: row.getColumns()) {
if (values[i] != null && !IdFieldMapper.NAME.equals(colSpec.name.toString())) {
mapObject.put(colSpec.name.toString(), values[i]);
j++;
}
i++;
}
return j;
}
public Object[] rowAsArray(final IndexService indexService, final String type, UntypedResultSet.Row row) throws IOException {
return rowAsArray(indexService, type, row, false);
}
private Object value(FieldMapper fieldMapper, Object rowValue, boolean valueForSearch) {
if (fieldMapper != null) {
final MappedFieldType fieldType = fieldMapper.fieldType();
return (valueForSearch) ? fieldType.valueForDisplay( rowValue ) : fieldType.cqlValue( rowValue );
} else {
return rowValue;
}
}
// TODO: return raw values if no mapper found.
public Object[] rowAsArray(final IndexService indexService, final String type, UntypedResultSet.Row row, boolean valueForSearch) throws IOException {
final Object values[] = new Object[row.getColumns().size()];
final DocumentMapper documentMapper = indexService.mapperService().documentMapper(type);
final DocumentFieldMappers docFieldMappers = documentMapper.mappers();
int i = 0;
for (ColumnSpecification colSpec : row.getColumns()) {
String columnName = colSpec.name.toString();
CQL3Type cql3Type = colSpec.type.asCQL3Type();
if (!row.has(columnName) || ByteBufferUtil.EMPTY_BYTE_BUFFER.equals(row.getBlob(columnName)) ) {
values[i++] = null;
continue;
}
if (cql3Type instanceof CQL3Type.Native) {
final FieldMapper fieldMapper = docFieldMappers.smartNameFieldMapper(columnName);
switch ((CQL3Type.Native) cql3Type) {
case ASCII:
case TEXT:
case VARCHAR:
values[i] = row.getString(columnName);
if (values[i] != null && fieldMapper == null) {
ObjectMapper objectMapper = documentMapper.objectMappers().get(columnName);
if (objectMapper != null && !objectMapper.isEnabled()) {
// parse text as JSON Map (not enabled object)
values[i] = FBUtilities.fromJsonMap(row.getString(columnName));
}
}
break;
case TIMEUUID:
if (fieldMapper instanceof DateFieldMapper) {
// Timeuuid can be mapped to date rather than keyword.
values[i] = UUIDGen.unixTimestamp(row.getUUID(columnName));
break;
}
values[i] = row.getUUID(columnName).toString();
break;
case UUID:
values[i] = row.getUUID(columnName).toString();
break;
case TIMESTAMP:
values[i] = value(fieldMapper, row.getTimestamp(columnName).getTime(), valueForSearch);
break;
case DATE:
values[i] = value(fieldMapper, row.getInt(columnName)*86400L*1000L, valueForSearch);
break;
case TIME:
values[i] = value(fieldMapper, row.getLong(columnName), valueForSearch);
break;
case INT:
values[i] = value(fieldMapper, row.getInt(columnName), valueForSearch);
break;
case SMALLINT:
values[i] = value(fieldMapper, row.getShort(columnName), valueForSearch);
break;
case TINYINT:
values[i] = value(fieldMapper, row.getByte(columnName), valueForSearch);
break;
case BIGINT:
values[i] = value(fieldMapper, row.getLong(columnName), valueForSearch);
break;
case DOUBLE:
values[i] = value(fieldMapper, row.getDouble(columnName), valueForSearch);
break;
case FLOAT:
values[i] = value(fieldMapper, row.getFloat(columnName), valueForSearch);
break;
case BLOB:
values[i] = value(fieldMapper,
row.getBlob(columnName),
valueForSearch);
break;
case BOOLEAN:
values[i] = value(fieldMapper, row.getBoolean(columnName), valueForSearch);
break;
case COUNTER:
logger.warn("Ignoring unsupported counter {} for column {}", cql3Type, columnName);
break;
case INET:
values[i] = value(fieldMapper, row.getInetAddress(columnName), valueForSearch);
break;
default:
logger.error("Ignoring unsupported type {} for column {}", cql3Type, columnName);
}
} else if (cql3Type.isCollection()) {
AbstractType<?> elementType;
switch (((CollectionType<?>) colSpec.type).kind) {
case LIST:
List list;
elementType = ((ListType<?>) colSpec.type).getElementsType();
if (elementType instanceof UserType) {
final ObjectMapper objectMapper = documentMapper.objectMappers().get(columnName);
final List<ByteBuffer> lbb = row.getList(columnName, BytesType.instance);
list = new ArrayList(lbb.size());
for (ByteBuffer bb : lbb) {
list.add(deserialize(elementType, bb, objectMapper));
}
} else {
final FieldMapper fieldMapper = docFieldMappers.smartNameFieldMapper(columnName);
final List list2 = row.getList(colSpec.name.toString(), elementType);
list = new ArrayList(list2.size());
for(Object v : list2) {
list.add(value(fieldMapper, v, valueForSearch));
}
}
values[i] = (list.size() == 1) ? list.get(0) : list;
break;
case SET :
Set set;
elementType = ((SetType<?>) colSpec.type).getElementsType();
if (elementType instanceof UserType) {
final ObjectMapper objectMapper = documentMapper.objectMappers().get(columnName);
final Set<ByteBuffer> lbb = row.getSet(columnName, BytesType.instance);
set = new HashSet(lbb.size());
for (ByteBuffer bb : lbb) {
set.add(deserialize(elementType, bb, objectMapper));
}
} else {
final FieldMapper fieldMapper = docFieldMappers.smartNameFieldMapper(columnName);
final Set set2 = row.getSet(columnName, elementType);
set = new HashSet(set2.size());
for(Object v : set2) {
set.add( value(fieldMapper, v, valueForSearch) );
}
}
values[i] = (set.size() == 1) ? set.iterator().next() : set;
break;
case MAP :
Map map;
if (((MapType<?,?>) colSpec.type).getKeysType().asCQL3Type() != CQL3Type.Native.TEXT) {
throw new IOException("Only support map<text,?>, bad type for column "+columnName);
}
UTF8Type keyType = (UTF8Type) ((MapType<?,?>) colSpec.type).getKeysType();
elementType = ((MapType<?,?>) colSpec.type).getValuesType();
final ObjectMapper objectMapper = documentMapper.objectMappers().get(columnName);
if (elementType instanceof UserType) {
final Map<String, ByteBuffer> lbb = row.getMap(columnName, keyType, BytesType.instance);
map = new HashMap<String , Map<String, Object>>(lbb.size());
for(String key : lbb.keySet()) {
map.put(key, deserialize(elementType, lbb.get(key), objectMapper.getMapper(key)));
}
} else {
Map<String,Object> map2 = (Map<String,Object>) row.getMap(columnName, keyType, elementType);
map = new HashMap<String, Object>(map2.size());
for(String key : map2.keySet()) {
FieldMapper subMapper = (FieldMapper)objectMapper.getMapper(key);
map.put(key, value(subMapper, map2.get(key), valueForSearch) );
}
}
values[i] = map;
break;
}
} else if (colSpec.type instanceof UserType) {
ByteBuffer bb = row.getBytes(columnName);
values[i] = deserialize(colSpec.type, bb, documentMapper.objectMappers().get(columnName));
} else if (cql3Type instanceof CQL3Type.Custom) {
logger.warn("CQL3.Custum type not supported for column "+columnName);
}
i++;
}
return values;
}
public static class BlockingActionListener implements ActionListener<ClusterStateUpdateResponse> {
private final CountDownLatch latch = new CountDownLatch(1);
private volatile Throwable error = null;
public void waitForUpdate(TimeValue timeValue) throws Exception {
if (timeValue != null && timeValue.millis() > 0) {
if (!latch.await(timeValue.millis(), TimeUnit.MILLISECONDS)) {
throw new ElasticsearchTimeoutException("blocking update timeout");
}
} else {
latch.await();
}
if (error != null)
throw new RuntimeException(error);
}
@Override
public void onResponse(ClusterStateUpdateResponse response) {
latch.countDown();
}
@Override
public void onFailure(Exception e) {
error = e;
latch.countDown();
}
}
/**
* CQL schema update must be asynchronous when triggered by a new dynamic field (see #91)
* @param indexService
* @param type
* @param source
* @throws Exception
*/
public void blockingMappingUpdate(IndexService indexService, String type, String source) throws Exception {
TimeValue timeout = settings.getAsTime(SETTING_CLUSTER_MAPPING_UPDATE_TIMEOUT, TimeValue.timeValueSeconds(Integer.getInteger(SETTING_SYSTEM_MAPPING_UPDATE_TIMEOUT, 30)));
BlockingActionListener mappingUpdateListener = new BlockingActionListener();
MetaDataMappingService metaDataMappingService = ElassandraDaemon.injector().getInstance(MetaDataMappingService.class);
PutMappingClusterStateUpdateRequest putRequest = new PutMappingClusterStateUpdateRequest()
.indices(new org.elasticsearch.index.Index[] {indexService.index()})
.type(type)
.source(source)
.ackTimeout(timeout);
metaDataMappingService.putMapping(putRequest, mappingUpdateListener);
mappingUpdateListener.waitForUpdate(timeout);
}
public void updateDocument(final IndicesService indicesService, final IndexRequest request, final IndexMetaData indexMetaData) throws Exception {
upsertDocument(indicesService, request, indexMetaData, true);
}
public void insertDocument(final IndicesService indicesService, final IndexRequest request, final IndexMetaData indexMetaData) throws Exception {
upsertDocument(indicesService, request, indexMetaData, false);
}
private void upsertDocument(final IndicesService indicesService, final IndexRequest request, final IndexMetaData indexMetaData, boolean updateOperation) throws Exception {
final IndexService indexService = indicesService.indexService(indexMetaData.getIndex());
final IndexShard indexShard = indexService.getShard(0);
final SourceToParse sourceToParse = SourceToParse.source(SourceToParse.Origin.PRIMARY, request.index(), request.type(), request.id(), request.source(), XContentType.JSON);
if (request.routing() != null)
sourceToParse.routing(request.routing());
if (request.parent() != null)
sourceToParse.parent(request.parent());
if (request.timestamp() != null)
sourceToParse.timestamp(request.timestamp());
if (request.ttl() != null)
sourceToParse.ttl(request.ttl());
final String keyspaceName = indexMetaData.keyspace();
final String cfName = typeToCfName(request.type());
final Engine.Index operation = indexShard.prepareIndexOnPrimary(sourceToParse, request.version(), request.versionType(), request.getAutoGeneratedTimestamp(), false);
final Mapping update = operation.parsedDoc().dynamicMappingsUpdate();
final boolean dynamicMappingEnable = indexService.mapperService().dynamic();
if (update != null && dynamicMappingEnable) {
if (logger.isDebugEnabled())
logger.debug("Document source={} require a blocking mapping update of [{}]", request.sourceAsMap(), indexService.index().getName());
// blocking Elasticsearch mapping update (required to update cassandra schema before inserting a row, this is the cost of dynamic mapping)
blockingMappingUpdate(indexService, request.type(), update.toString());
}
// get the docMapper after a potential mapping update
final DocumentMapper docMapper = indexShard.mapperService().documentMapperWithAutoCreate(request.type()).getDocumentMapper();
// insert document into cassandra keyspace=index, table = type
final Map<String, Object> sourceMap = request.sourceAsMap();
final Map<String, ObjectMapper> objectMappers = docMapper.objectMappers();
final DocumentFieldMappers fieldMappers = docMapper.mappers();
Long timestamp = null;
if (docMapper.timestampFieldMapper().enabled() && request.timestamp() != null) {
timestamp = docMapper.timestampFieldMapper().fieldType().cqlValue(request.timestamp());
}
if (logger.isTraceEnabled())
logger.trace("Insert metadata.version={} index=[{}] table=[{}] id=[{}] source={} consistency={} ttl={}",
state().metaData().version(),
indexService.index().getName(), cfName, request.id(), sourceMap,
request.waitForActiveShards().toCassandraConsistencyLevel(), request.ttl());
final CFMetaData metadata = getCFMetaData(keyspaceName, cfName);
String id = request.id();
Map<String, ByteBuffer> map = new HashMap<String, ByteBuffer>();
if (request.parent() != null)
sourceMap.put(ParentFieldMapper.NAME, request.parent());
// normalize the _id and may find some column value in _id.
// if the provided columns does not contains all the primary key columns, parse the _id to populate the columns in map.
parseElasticId(indexService, cfName, request.id(), sourceMap);
// workaround because ParentFieldMapper.value() and UidFieldMapper.value() create an Uid.
if (sourceMap.get(ParentFieldMapper.NAME) != null && ((String)sourceMap.get(ParentFieldMapper.NAME)).indexOf(Uid.DELIMITER) < 0) {
sourceMap.put(ParentFieldMapper.NAME, request.type() + Uid.DELIMITER + sourceMap.get(ParentFieldMapper.NAME));
}
if (docMapper.sourceMapper().enabled()) {
sourceMap.put(SourceFieldMapper.NAME, request.source());
}
for (String field : sourceMap.keySet()) {
FieldMapper fieldMapper = field.startsWith(ParentFieldMapper.NAME) ? // workaround for _parent#<join_type>
docMapper.parentFieldMapper() : fieldMappers.getMapper( field );
Mapper mapper = (fieldMapper != null) ? fieldMapper : objectMappers.get(field);
ByteBuffer colName;
if (mapper == null) {
if (dynamicMappingEnable)
throw new MapperException("Unmapped field ["+field+"]");
colName = ByteBufferUtil.bytes(field);
} else {
colName = mapper.cqlName(); // cached ByteBuffer column name.
}
final ColumnDefinition cd = metadata.getColumnDefinition(colName);
if (cd != null) {
// we got a CQL column.
Object fieldValue = sourceMap.get(field);
try {
if (fieldValue == null) {
if (cd.type.isCollection()) {
switch (((CollectionType<?>)cd.type).kind) {
case LIST :
case SET :
map.put(field, CollectionSerializer.pack(Collections.emptyList(), 0, ProtocolVersion.CURRENT));
break;
case MAP :
break;
}
} else {
map.put(field, null);
}
continue;
}
if (mapper != null && mapper.cqlCollection().equals(CqlCollection.SINGLETON) && (fieldValue instanceof Collection)) {
throw new MapperParsingException("field " + fieldMapper.name() + " should be a single value");
}
// hack to store percolate query as a string while mapper is an object mapper.
if (metadata.cfName.equals("_percolator") && field.equals("query")) {
if (cd.type.isCollection()) {
switch (((CollectionType<?>)cd.type).kind) {
case LIST :
if ( ((ListType)cd.type).getElementsType().asCQL3Type().equals(CQL3Type.Native.TEXT) && !(fieldValue instanceof String)) {
// opaque list of objects serialized to JSON text
fieldValue = Collections.singletonList( stringify(fieldValue) );
}
break;
case SET :
if ( ((SetType)cd.type).getElementsType().asCQL3Type().equals(CQL3Type.Native.TEXT) && !(fieldValue instanceof String)) {
// opaque set of objects serialized to JSON text
fieldValue = Collections.singleton( stringify(fieldValue) );
}
break;
}
} else {
if (cd.type.asCQL3Type().equals(CQL3Type.Native.TEXT) && !(fieldValue instanceof String)) {
// opaque singleton object serialized to JSON text
fieldValue = stringify(fieldValue);
}
}
}
map.put(field, serialize(request.index(), cfName, cd.type, field, fieldValue, mapper));
} catch (Exception e) {
logger.error("[{}].[{}] failed to parse field {}={}", e, request.index(), cfName, field, fieldValue );
throw e;
}
}
}
String query;
ByteBuffer[] values;
if (request.opType() == DocWriteRequest.OpType.CREATE) {
values = new ByteBuffer[map.size()];
query = buildInsertQuery(keyspaceName, cfName, map, id,
true,
(request.ttl() != null) ? request.ttl().getSeconds() : null, // ttl
timestamp,
values, 0);
final boolean applied = processWriteConditional(request.waitForActiveShards().toCassandraConsistencyLevel(), ConsistencyLevel.LOCAL_SERIAL, query, (Object[])values);
if (!applied)
throw new VersionConflictEngineException(indexShard.shardId(), cfName, request.id(), "PAXOS insert failed, document already exists");
} else {
// set empty top-level fields to null to overwrite existing columns.
for(FieldMapper m : fieldMappers) {
String fullname = m.name();
if (map.get(fullname) == null && !fullname.startsWith("_") && fullname.indexOf('.') == -1 && metadata.getColumnDefinition(m.cqlName()) != null)
map.put(fullname, null);
}
for(String m : objectMappers.keySet()) {
if (map.get(m) == null && m.indexOf('.') == -1 && metadata.getColumnDefinition(objectMappers.get(m).cqlName()) != null)
map.put(m, null);
}
values = new ByteBuffer[map.size()];
query = buildInsertQuery(keyspaceName, cfName, map, id,
false,
(request.ttl() != null) ? request.ttl().getSeconds() : null,
timestamp,
values, 0);
process(request.waitForActiveShards().toCassandraConsistencyLevel(), query, (Object[])values);
}
}
public String buildInsertQuery(final String ksName, final String cfName, Map<String, ByteBuffer> map, String id, final boolean ifNotExists, final Long ttl,
final Long writetime, ByteBuffer[] values, int valuesOffset) throws Exception {
final StringBuilder questionsMarks = new StringBuilder();
final StringBuilder columnNames = new StringBuilder();
int i=0;
for (Entry<String,ByteBuffer> entry : map.entrySet()) {
if (entry.getKey().equals(TokenFieldMapper.NAME))
continue;
if (columnNames.length() > 0) {
columnNames.append(',');
questionsMarks.append(',');
}
columnNames.append("\"").append(entry.getKey()).append("\"");
questionsMarks.append('?');
values[valuesOffset + i] = entry.getValue();
i++;
}
final StringBuilder query = new StringBuilder();
query.append("INSERT INTO \"").append(ksName).append("\".\"").append(cfName)
.append("\" (").append(columnNames.toString()).append(") VALUES (").append(questionsMarks.toString()).append(") ");
if (ifNotExists) query.append("IF NOT EXISTS ");
if (ttl != null && ttl > 0 || writetime != null) query.append("USING ");
if (ttl != null && ttl > 0) query.append("TTL ").append(Long.toString(ttl));
if (ttl != null &&ttl > 0 && writetime != null) query.append(" AND ");
if (writetime != null) query.append("TIMESTAMP ").append(Long.toString(writetime*1000));
return query.toString();
}
public BytesReference source(IndexService indexService, DocumentMapper docMapper, Map sourceAsMap, Uid uid) throws JsonParseException, JsonMappingException, IOException {
if (docMapper.sourceMapper().enabled()) {
// retreive from _source columns stored as blob in cassandra if available.
ByteBuffer bb = (ByteBuffer) sourceAsMap.get(SourceFieldMapper.NAME);
if (bb != null)
return new BytesArray(bb.array(), bb.position(), bb.limit() - bb.position());
}
// rebuild _source from all cassandra columns.
XContentBuilder builder = buildDocument(docMapper, sourceAsMap, true, isStaticDocument(indexService, uid));
builder.humanReadable(true);
return builder.bytes();
}
public BytesReference source(IndexService indexService, DocumentMapper docMapper, Map sourceAsMap, String id) throws JsonParseException, JsonMappingException, IOException {
return source( indexService, docMapper, sourceAsMap, new Uid(docMapper.type(), id));
}
public DocPrimaryKey parseElasticId(final IndexService indexService, final String type, final String id) throws IOException {
return parseElasticId(indexService, type, id, null);
}
/**
* Parse elastic _id (a value or a JSON array) to build a DocPrimaryKey or populate map.
*/
public DocPrimaryKey parseElasticId(final IndexService indexService, final String type, final String id, Map<String, Object> map) throws JsonParseException, JsonMappingException, IOException {
String ksName = indexService.keyspace();
String cfName = typeToCfName(type);
CFMetaData metadata = getCFMetaData(ksName, cfName);
List<ColumnDefinition> partitionColumns = metadata.partitionKeyColumns();
List<ColumnDefinition> clusteringColumns = metadata.clusteringColumns();
int ptLen = partitionColumns.size();
if (id.startsWith("[") && id.endsWith("]")) {
// _id is JSON array of values.
org.codehaus.jackson.map.ObjectMapper jsonMapper = new org.codehaus.jackson.map.ObjectMapper();
Object[] elements = jsonMapper.readValue(id, Object[].class);
Object[] values = (map != null) ? null : new Object[elements.length];
String[] names = (map != null) ? null : new String[elements.length];
if (elements.length > ptLen + clusteringColumns.size())
throw new JsonMappingException("_id="+id+" longer than the primary key size="+(ptLen+clusteringColumns.size()) );
for(int i=0; i < elements.length; i++) {
ColumnDefinition cd = (i < ptLen) ? partitionColumns.get(i) : clusteringColumns.get(i - ptLen);
AbstractType<?> atype = cd.type;
if (map == null) {
names[i] = cd.name.toString();
values[i] = atype.compose( fromString(atype, elements[i].toString()) );
} else {
map.put(cd.name.toString(), atype.compose( fromString(atype, elements[i].toString()) ) );
}
}
return (map != null) ? null : new DocPrimaryKey(names, values, (clusteringColumns.size() > 0 && elements.length == partitionColumns.size()) ) ;
} else {
// _id is a single columns, parse its value.
AbstractType<?> atype = partitionColumns.get(0).type;
if (map == null) {
return new DocPrimaryKey( new String[] { partitionColumns.get(0).name.toString() } , new Object[] { atype.compose(fromString(atype, id)) }, clusteringColumns.size() != 0);
} else {
map.put(partitionColumns.get(0).name.toString(), atype.compose( fromString(atype, id) ) );
return null;
}
}
}
public DocPrimaryKey parseElasticRouting(final IndexService indexService, final String type, final String routing) throws JsonParseException, JsonMappingException, IOException {
String ksName = indexService.keyspace();
String cfName = typeToCfName(type);
CFMetaData metadata = getCFMetaData(ksName, cfName);
List<ColumnDefinition> partitionColumns = metadata.partitionKeyColumns();
int ptLen = partitionColumns.size();
if (routing.startsWith("[") && routing.endsWith("]")) {
// _routing is JSON array of values.
org.codehaus.jackson.map.ObjectMapper jsonMapper = new org.codehaus.jackson.map.ObjectMapper();
Object[] elements = jsonMapper.readValue(routing, Object[].class);
Object[] values = new Object[elements.length];
String[] names = new String[elements.length];
if (elements.length != ptLen)
throw new JsonMappingException("_routing="+routing+" does not match the partition key size="+ptLen);
for(int i=0; i < elements.length; i++) {
ColumnDefinition cd = partitionColumns.get(i);
AbstractType<?> atype = cd.type;
names[i] = cd.name.toString();
values[i] = atype.compose( fromString(atype, elements[i].toString()) );
i++;
}
return new DocPrimaryKey(names, values) ;
} else {
// _id is a single columns, parse its value.
AbstractType<?> atype = partitionColumns.get(0).type;
return new DocPrimaryKey( new String[] { partitionColumns.get(0).name.toString() } , new Object[] { atype.compose( fromString(atype, routing) ) });
}
}
public Token getToken(final IndexService indexService, final String type, final String routing) throws JsonParseException, JsonMappingException, IOException {
DocPrimaryKey pk = parseElasticRouting(indexService, type, routing);
CFMetaData cfm = getCFMetaData(indexService.keyspace(), type);
CBuilder builder = CBuilder.create(cfm.getKeyValidatorAsClusteringComparator());
for (int i = 0; i < cfm.partitionKeyColumns().size(); i++)
builder.add(pk.values[i]);
return cfm.partitioner.getToken(CFMetaData.serializePartitionKey(builder.build()));
}
public Set<Token> getTokens(final IndexService indexService, final String[] types, final String routing) throws JsonParseException, JsonMappingException, IOException {
Set<Token> tokens = new HashSet<Token>();
if (types != null && types.length > 0) {
for(String type : types)
tokens.add(getToken(indexService, type, routing));
}
return tokens;
}
public boolean isStaticDocument(final IndexService indexService, Uid uid) throws JsonParseException, JsonMappingException, IOException {
CFMetaData metadata = getCFMetaData(indexService.keyspace(), typeToCfName(uid.type()));
String id = uid.id();
if (id.startsWith("[") && id.endsWith("]")) {
org.codehaus.jackson.map.ObjectMapper jsonMapper = new org.codehaus.jackson.map.ObjectMapper();
Object[] elements = jsonMapper.readValue(id, Object[].class);
return metadata.clusteringColumns().size() > 0 && elements.length == metadata.partitionKeyColumns().size();
} else {
return metadata.clusteringColumns().size() != 0;
}
}
@SuppressForbidden(reason = "toUpperCase() for consistency level")
public static ConsistencyLevel consistencyLevelFromString(String value) {
switch(value.toUpperCase(Locale.ROOT)) {
case "ANY": return ConsistencyLevel.ANY;
case "ONE": return ConsistencyLevel.ONE;
case "TWO": return ConsistencyLevel.TWO;
case "THREE": return ConsistencyLevel.THREE;
case "QUORUM": return ConsistencyLevel.QUORUM;
case "ALL": return ConsistencyLevel.ALL;
case "LOCAL_QUORUM": return ConsistencyLevel.LOCAL_QUORUM;
case "EACH_QUORUM": return ConsistencyLevel.EACH_QUORUM;
case "SERIAL": return ConsistencyLevel.SERIAL;
case "LOCAL_SERIAL": return ConsistencyLevel.LOCAL_SERIAL;
case "LOCAL_ONE": return ConsistencyLevel.LOCAL_ONE;
default :
throw new IllegalArgumentException("No write consistency match [" + value + "]");
}
}
public boolean isDatacenterGroupMember(InetAddress endpoint) {
String endpointDc = DatabaseDescriptor.getEndpointSnitch().getDatacenter(endpoint);
KeyspaceMetadata elasticAdminMetadata = Schema.instance.getKSMetaData(this.elasticAdminKeyspaceName);
if (elasticAdminMetadata != null) {
ReplicationParams replicationParams = elasticAdminMetadata.params.replication;
if (replicationParams.klass == NetworkTopologyStrategy.class && replicationParams.options.get(endpointDc) != null) {
return true;
}
}
return false;
}
public class MetadataSchemaUpdate {
long version;
long timestamp;
String metaDataString;
MetadataSchemaUpdate(String metaDataString, long version) {
this.metaDataString = metaDataString;
this.version = version;
this.timestamp = FBUtilities.timestampMicros();
}
}
public void writeMetaDataAsComment(MetaData metaData) throws ConfigurationException, IOException {
writeMetaDataAsComment( MetaData.Builder.toXContent(metaData, MetaData.CASSANDRA_FORMAT_PARAMS), metaData.version());
}
public void writeMetaDataAsComment(String metaDataString, long version) throws ConfigurationException, IOException {
// Issue #91, update C* schema asynchronously to avoid inter-locking with map column as nested object.
logger.trace("Submit asynchronous CQL schema update for metadata={}", metaDataString);
this.lastMetadataToSave.set(new MetadataSchemaUpdate(metaDataString, version));
this.metadataToSaveSemaphore.release();
}
/**
* Should only be used after a SCHEMA change.
*/
public MetaData readMetaDataAsComment() throws NoPersistedMetaDataException {
try {
String query = String.format(Locale.ROOT, "SELECT comment FROM system_schema.tables WHERE keyspace_name='%s' AND table_name='%s'",
this.elasticAdminKeyspaceName, ELASTIC_ADMIN_METADATA_TABLE);
UntypedResultSet result = QueryProcessor.executeInternal(query);
if (result.isEmpty())
throw new NoPersistedMetaDataException("Failed to read comment from "+elasticAdminKeyspaceName+"+"+ELASTIC_ADMIN_METADATA_TABLE);
String metadataString = result.one().getString("comment");
logger.debug("Recover metadata from {}.{} = {}", elasticAdminKeyspaceName, ELASTIC_ADMIN_METADATA_TABLE, metadataString);
return parseMetaDataString( metadataString );
} catch (RequestValidationException | RequestExecutionException e) {
throw new NoPersistedMetaDataException("Failed to read comment from "+elasticAdminKeyspaceName+"+"+ELASTIC_ADMIN_METADATA_TABLE, e);
}
}
private MetaData parseMetaDataString(String metadataString) throws NoPersistedMetaDataException {
if (metadataString != null && metadataString.length() > 0) {
MetaData metaData;
try {
metaData = metaStateService.loadGlobalState(metadataString);
} catch (Exception e) {
logger.error("Failed to parse metadata={}", e, metadataString);
throw new NoPersistedMetaDataException("Failed to parse metadata="+metadataString, e);
}
return metaData;
}
throw new NoPersistedMetaDataException("metadata null or empty");
}
/**
* Try to read fresher metadata from cassandra.
*/
public MetaData checkForNewMetaData(Long expectedVersion) throws NoPersistedMetaDataException {
MetaData localMetaData = readMetaDataAsRow(ConsistencyLevel.ONE);
if (localMetaData != null && localMetaData.version() >= expectedVersion) {
return localMetaData;
}
if (localMetaData == null) {
throw new NoPersistedMetaDataException("No cluster metadata in "+this.elasticAdminKeyspaceName);
}
MetaData quorumMetaData = readMetaDataAsRow(this.metadataReadCL);
if (quorumMetaData.version() >= expectedVersion) {
return quorumMetaData;
}
return null;
}
public MetaData readInternalMetaDataAsRow() throws NoPersistedMetaDataException {
try {
UntypedResultSet rs = QueryProcessor.executeInternal(selectMetadataQuery, DatabaseDescriptor.getClusterName());
if (rs != null && !rs.isEmpty()) {
Row row = rs.one();
if (row.has("metadata"))
return parseMetaDataString(row.getString("metadata"));
}
} catch (Exception e) {
logger.warn("Cannot read metadata locally",e);
}
return null;
}
public MetaData readMetaDataAsRow(ConsistencyLevel cl) throws NoPersistedMetaDataException {
try {
UntypedResultSet rs = process(cl, ClientState.forInternalCalls(), selectMetadataQuery, DatabaseDescriptor.getClusterName());
if (rs != null && !rs.isEmpty()) {
Row row = rs.one();
if (row.has("metadata"))
return parseMetaDataString(row.getString("metadata"));
}
} catch (UnavailableException e) {
logger.warn("Cannot read metadata with consistency="+cl,e);
return null;
} catch (KeyspaceNotDefinedException e) {
logger.warn("Keyspace {} not yet defined", ELASTIC_ADMIN_KEYSPACE);
return null;
} catch (Exception e) {
throw new NoPersistedMetaDataException("Unexpected error",e);
}
throw new NoPersistedMetaDataException("Unexpected error");
}
public Long readMetaDataVersion(ConsistencyLevel cl) throws NoPersistedMetaDataException {
try {
UntypedResultSet rs = process(cl, ClientState.forInternalCalls(), selectVersionMetadataQuery, DatabaseDescriptor.getClusterName());
if (rs != null && !rs.isEmpty()) {
Row row = rs.one();
if (row.has("version"))
return row.getLong("version");
}
} catch (Exception e) {
logger.warn("unexpected error", e);
}
return -1L;
}
public static String getElasticsearchClusterName(Settings settings) {
String clusterName = DatabaseDescriptor.getClusterName();
String datacenterGroup = settings.get(ClusterService.SETTING_CLUSTER_DATACENTER_GROUP);
if (datacenterGroup != null) {
clusterName = DatabaseDescriptor.getClusterName() + "@" + datacenterGroup.trim();
}
return clusterName;
}
public int getLocalDataCenterSize() {
int count = 1;
for (UntypedResultSet.Row row : executeInternal("SELECT data_center, rpc_address FROM system." + SystemKeyspace.PEERS))
if (row.has("rpc_address") && DatabaseDescriptor.getLocalDataCenter().equals(row.getString("data_center")))
count++;
logger.info(" datacenter=[{}] size={} from peers", DatabaseDescriptor.getLocalDataCenter(), count);
return count;
}
Void createElasticAdminKeyspace() {
try {
Map<String, String> replication = new HashMap<String, String>();
replication.put("class", NetworkTopologyStrategy.class.getName());
replication.put(DatabaseDescriptor.getLocalDataCenter(), Integer.toString(getLocalDataCenterSize()));
String createKeyspace = String.format(Locale.ROOT, "CREATE KEYSPACE IF NOT EXISTS \"%s\" WITH replication = %s;",
elasticAdminKeyspaceName, FBUtilities.json(replication).replaceAll("\"", "'"));
logger.info(createKeyspace);
process(ConsistencyLevel.LOCAL_ONE, ClientState.forInternalCalls(), createKeyspace);
} catch (Exception e) {
logger.error((Supplier<?>) () -> new ParameterizedMessage("Failed to initialize keyspace {}", elasticAdminKeyspaceName), e);
throw e;
}
return null;
}
// Modify keyspace replication
public void alterKeyspaceReplicationFactor(String keyspaceName, int rf) {
ReplicationParams replication = Schema.instance.getKSMetaData(keyspaceName).params.replication;
if (!NetworkTopologyStrategy.class.getName().equals(replication.klass))
throw new ConfigurationException("Keyspace ["+keyspaceName+"] should use "+NetworkTopologyStrategy.class.getName()+" replication strategy");
Map<String, String> repMap = replication.asMap();
if (!repMap.containsKey(DatabaseDescriptor.getLocalDataCenter()) || !Integer.toString(rf).equals(repMap.get(DatabaseDescriptor.getLocalDataCenter()))) {
repMap.put(DatabaseDescriptor.getLocalDataCenter(), Integer.toString(rf));
logger.debug("Updating keyspace={} replication={}", keyspaceName, repMap);
try {
String query = String.format(Locale.ROOT, "ALTER KEYSPACE \"%s\" WITH replication = %s",
keyspaceName, FBUtilities.json(repMap).replaceAll("\"", "'"));
logger.info(query);
process(ConsistencyLevel.LOCAL_ONE, ClientState.forInternalCalls(), query);
} catch (Throwable e) {
logger.error((Supplier<?>) () -> new ParameterizedMessage("Failed to alter keyspace [{}]",keyspaceName), e);
throw e;
}
} else {
logger.info("Keep unchanged keyspace={} datacenter={} RF={}", keyspaceName, DatabaseDescriptor.getLocalDataCenter(), rf);
}
}
// Create The meta Data Table if needed
Void createElasticAdminMetaTable(final String metaDataString) {
try {
String createTable = String.format(Locale.ROOT, "CREATE TABLE IF NOT EXISTS \"%s\".%s ( cluster_name text PRIMARY KEY, owner uuid, version bigint, metadata text) WITH comment='%s';",
elasticAdminKeyspaceName, ELASTIC_ADMIN_METADATA_TABLE, metaDataString);
logger.info(createTable);
process(ConsistencyLevel.LOCAL_ONE, ClientState.forInternalCalls(), createTable);
} catch (Exception e) {
logger.error((Supplier<?>) () -> new ParameterizedMessage("Failed to initialize table {}.{}", elasticAdminKeyspaceName, ELASTIC_ADMIN_METADATA_TABLE), e);
throw e;
}
return null;
}
// initialize a first row if needed
Void insertFirstMetaRow(final MetaData metadata, final String metaDataString) {
try {
logger.info(insertMetadataQuery);
process(ConsistencyLevel.LOCAL_ONE, ClientState.forInternalCalls(), insertMetadataQuery,
DatabaseDescriptor.getClusterName(), UUID.fromString(StorageService.instance.getLocalHostId()), metadata.version(), metaDataString);
} catch (Exception e) {
logger.error((Supplier<?>) () -> new ParameterizedMessage("Failed insert first row into table {}.{}", elasticAdminKeyspaceName, ELASTIC_ADMIN_METADATA_TABLE), e);
throw e;
}
return null;
}
void retry (final Supplier<Void> function, final String label) {
for (int i = 0; ; ++i) {
try {
function.get();
break;
} catch (final Exception e) {
if (i >= CREATE_ELASTIC_ADMIN_RETRY_ATTEMPTS) {
logger.error("Failed to {} after {} attempts", label, CREATE_ELASTIC_ADMIN_RETRY_ATTEMPTS);
throw new NoPersistedMetaDataException("Failed to " + label + " after " + CREATE_ELASTIC_ADMIN_RETRY_ATTEMPTS + " attempts", e);
} else
logger.info("Retrying: {}", label);
}
}
}
/**
* Create or update elastic_admin keyspace.
*/
public void createOrUpdateElasticAdminKeyspace() {
UntypedResultSet result = QueryProcessor.executeOnceInternal(String.format(Locale.ROOT, "SELECT replication FROM system_schema.keyspaces WHERE keyspace_name='%s'", elasticAdminKeyspaceName));
if (result.isEmpty()) {
MetaData metadata = state().metaData();
try {
final String metaDataString;
try {
metaDataString = MetaData.Builder.toXContent(metadata);
} catch (IOException e) {
logger.error("Failed to build metadata", e);
throw new NoPersistedMetaDataException("Failed to build metadata", e);
}
// create elastic_admin if not exists after joining the ring and before allowing metadata update.
retry(() -> createElasticAdminKeyspace(), "create elastic admin keyspace");
retry(() -> createElasticAdminMetaTable(metaDataString), "create elastic admin metadata table");
retry(() -> insertFirstMetaRow(metadata, metaDataString), "write first row to metadata table");
logger.info("Succefully initialize {}.{} = {}", elasticAdminKeyspaceName, ELASTIC_ADMIN_METADATA_TABLE, metaDataString);
try {
writeMetaDataAsComment(metaDataString, metadata.version());
} catch (IOException e) {
logger.error("Failed to write metadata as comment", e);
}
} catch (Throwable e) {
logger.error((Supplier<?>) () -> new ParameterizedMessage("Failed to initialize table {}.{}", elasticAdminKeyspaceName, ELASTIC_ADMIN_METADATA_TABLE),e);
}
} else {
Map<String,String> replication = result.one().getFrozenTextMap("replication");
logger.debug("keyspace={} replication={}", elasticAdminKeyspaceName, replication);
if (!NetworkTopologyStrategy.class.getName().equals(replication.get("class")))
throw new ConfigurationException("Keyspace ["+this.elasticAdminKeyspaceName+"] should use "+NetworkTopologyStrategy.class.getName()+" replication strategy");
int currentRF = -1;
if (replication.get(DatabaseDescriptor.getLocalDataCenter()) != null) {
currentRF = Integer.valueOf(replication.get(DatabaseDescriptor.getLocalDataCenter()).toString());
}
int targetRF = getLocalDataCenterSize();
if (targetRF != currentRF) {
replication.put(DatabaseDescriptor.getLocalDataCenter(), Integer.toString(targetRF));
try {
String query = String.format(Locale.ROOT, "ALTER KEYSPACE \"%s\" WITH replication = %s",
elasticAdminKeyspaceName, FBUtilities.json(replication).replaceAll("\"", "'"));
logger.info(query);
process(ConsistencyLevel.LOCAL_ONE, ClientState.forInternalCalls(), query);
} catch (Throwable e) {
logger.error((Supplier<?>) () -> new ParameterizedMessage("Failed to alter keyspace [{}]", elasticAdminKeyspaceName),e);
throw e;
}
} else {
logger.info("Keep unchanged keyspace={} datacenter={} RF={}", elasticAdminKeyspaceName, DatabaseDescriptor.getLocalDataCenter(), targetRF);
}
}
}
public ShardInfo shardInfo(String index, ConsistencyLevel cl) {
Keyspace keyspace = Schema.instance.getKeyspaceInstance(state().metaData().index(index).keyspace());
AbstractReplicationStrategy replicationStrategy = keyspace.getReplicationStrategy();
int rf = replicationStrategy.getReplicationFactor();
if (replicationStrategy instanceof NetworkTopologyStrategy)
rf = ((NetworkTopologyStrategy)replicationStrategy).getReplicationFactor(DatabaseDescriptor.getLocalDataCenter());
return new ShardInfo(rf, cl.blockFor(keyspace));
}
public void persistMetaData(MetaData oldMetaData, MetaData newMetaData, String source) throws IOException, InvalidRequestException, RequestExecutionException, RequestValidationException {
if (!newMetaData.clusterUUID().equals(localNode().getId())) {
logger.error("should not push metadata updated from another node {}/{}", newMetaData.clusterUUID(), newMetaData.version());
return;
}
if (newMetaData.clusterUUID().equals(state().metaData().clusterUUID()) && newMetaData.version() < state().metaData().version()) {
logger.warn("don't push obsolete metadata uuid={} version {} < {}", newMetaData.clusterUUID(), newMetaData.version(), state().metaData().version());
return;
}
String metaDataString = MetaData.Builder.toXContent(newMetaData, MetaData.CASSANDRA_FORMAT_PARAMS);
UUID owner = UUID.fromString(localNode().getId());
boolean applied = processWriteConditional(
this.metadataWriteCL,
this.metadataSerialCL,
ClientState.forInternalCalls(),
updateMetaDataQuery,
new Object[] { owner, newMetaData.version(), metaDataString, DatabaseDescriptor.getClusterName(), newMetaData.version() });
if (applied) {
logger.debug("PAXOS Succefully update metadata source={} newMetaData={} in cluster {}", source, metaDataString, DatabaseDescriptor.getClusterName());
writeMetaDataAsComment(metaDataString, newMetaData.version());
return;
} else {
logger.warn("PAXOS Failed to update metadata oldMetadata={}/{} currentMetaData={}/{} in cluster {}",
oldMetaData.clusterUUID(), oldMetaData.version(), localNode().getId(), newMetaData.version(), DatabaseDescriptor.getClusterName());
throw new ConcurrentMetaDataUpdateException(owner, newMetaData.version());
}
}
public static Collection flattenCollection(Collection c) {
List l = new ArrayList(c.size());
for(Object o : c) {
if (o instanceof Collection) {
l.addAll( flattenCollection((Collection)o) );
} else {
l.add(o);
}
}
return l;
}
/**
* Duplicate code from org.apache.cassandra.service.StorageService.setLoggingLevel, allowing to set log level without StorageService.instance for tests.
* @param classQualifier
* @param rawLevel
*/
public static void setLoggingLevel(String classQualifier, String rawLevel)
{
ch.qos.logback.classic.Logger logBackLogger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(classQualifier);
// if both classQualifer and rawLevel are empty, reload from configuration
if (StringUtils.isBlank(classQualifier) && StringUtils.isBlank(rawLevel) )
{
try {
JMXConfiguratorMBean jmxConfiguratorMBean = JMX.newMBeanProxy(ManagementFactory.getPlatformMBeanServer(),
new ObjectName("ch.qos.logback.classic:Name=default,Type=ch.qos.logback.classic.jmx.JMXConfigurator"),
JMXConfiguratorMBean.class);
jmxConfiguratorMBean.reloadDefaultConfiguration();
return;
} catch (MalformedObjectNameException | JoranException e) {
throw new RuntimeException(e);
}
}
// classQualifer is set, but blank level given
else if (StringUtils.isNotBlank(classQualifier) && StringUtils.isBlank(rawLevel) )
{
if (logBackLogger.getLevel() != null || hasAppenders(logBackLogger))
logBackLogger.setLevel(null);
return;
}
ch.qos.logback.classic.Level level = ch.qos.logback.classic.Level.toLevel(rawLevel);
logBackLogger.setLevel(level);
//logger.info("set log level to {} for classes under '{}' (if the level doesn't look like '{}' then the logger couldn't parse '{}')", level, classQualifier, rawLevel, rawLevel);
}
private static boolean hasAppenders(ch.qos.logback.classic.Logger logger)
{
Iterator<Appender<ILoggingEvent>> it = logger.iteratorForAppenders();
return it.hasNext();
}
/**
* Serialize a cassandra typed object.
*/
public static ByteBuffer serialize(final String ksName, final String cfName, final AbstractType type, final String name, final Object value, final Mapper mapper)
throws SyntaxException, ConfigurationException, JsonGenerationException, JsonMappingException, IOException {
if (value == null) {
return null;
}
if (type instanceof UserType) {
UserType udt = (UserType) type;
ByteBuffer[] components = new ByteBuffer[udt.size()];
int i=0;
if (GEO_POINT_TYPE.equals(ByteBufferUtil.string(udt.name))) {
GeoPoint geoPoint = new GeoPoint();
if (value instanceof String) {
// parse from string lat,lon (ex: "41.12,-71.34") or geohash (ex:"drm3btev3e86")
geoPoint.resetFromString((String)value);
} else {
// parse from lat, lon fields as map
Map<String, Object> mapValue = (Map<String, Object>) value;
geoPoint.reset((Double)mapValue.get(GeoPointFieldMapper.Names.LAT), (Double)mapValue.get(GeoPointFieldMapper.Names.LON));
}
components[i++]=serialize(ksName, cfName, udt.fieldType(0), GeoPointFieldMapper.Names.LAT, geoPoint.lat(), null);
components[i++]=serialize(ksName, cfName, udt.fieldType(1), GeoPointFieldMapper.Names.LON, geoPoint.lon(), null);
} else if (COMPLETION_TYPE.equals(ByteBufferUtil.string(udt.name))) {
// input list<text>, output text, weight int, payload text
Map<String, Object> mapValue = (Map<String, Object>) value;
components[i++]=(mapValue.get(CompletionFieldMapper.Fields.CONTENT_FIELD_NAME_INPUT) == null) ? null : serialize(ksName, cfName, udt.fieldType(0), CompletionFieldMapper.Fields.CONTENT_FIELD_NAME_INPUT, mapValue.get(CompletionFieldMapper.Fields.CONTENT_FIELD_NAME_INPUT), null);
components[i++]=(mapValue.get(CompletionFieldMapper.Fields.CONTENT_FIELD_NAME_WEIGHT) == null) ? null : serialize(ksName, cfName, udt.fieldType(2), CompletionFieldMapper.Fields.CONTENT_FIELD_NAME_WEIGHT, new Long((Integer) mapValue.get(CompletionFieldMapper.Fields.CONTENT_FIELD_NAME_WEIGHT)), null);
components[i++]=(mapValue.get(CompletionFieldMapper.Fields.CONTENT_FIELD_NAME_CONTEXTS) == null) ? null : serialize(ksName, cfName, udt.fieldType(3), CompletionFieldMapper.Fields.CONTENT_FIELD_NAME_CONTEXTS, stringify(mapValue.get(CompletionFieldMapper.Fields.CONTENT_FIELD_NAME_CONTEXTS)), null);
} else {
Map<String, Object> mapValue = (Map<String, Object>) value;
for (int j = 0; j < udt.size(); j++) {
String subName = UTF8Type.instance.compose(udt.fieldName(j).bytes);
AbstractType<?> subType = udt.fieldType(j);
Object subValue = mapValue.get(subName);
Mapper subMapper = (mapper instanceof ObjectMapper) ? ((ObjectMapper) mapper).getMapper(subName) : null;
components[i++]=serialize(ksName, cfName, subType, subName, subValue, subMapper);
}
}
return TupleType.buildValue(components);
} else if (type instanceof MapType) {
MapType mapType = ClusterService.getMapType(ksName, cfName, name);
MapSerializer serializer = mapType.getSerializer();
Map map = (Map)value;
List<ByteBuffer> buffers = serializer.serializeValues((Map)value);
return CollectionSerializer.pack(buffers, map.size(), ProtocolVersion.CURRENT);
} else if (type instanceof CollectionType) {
AbstractType elementType = (type instanceof ListType) ? ((ListType)type).getElementsType() : ((SetType)type).getElementsType();
if (elementType instanceof UserType && ClusterService.GEO_POINT_TYPE.equals(ByteBufferUtil.string(((UserType)elementType).name)) && value instanceof List && ((List)value).get(0) instanceof Double) {
// geo_point as array of double lon,lat like [1.2, 1.3]
UserType udt = (UserType)elementType;
List<Double> values = (List<Double>)value;
ByteBuffer[] elements = new ByteBuffer[] {
serialize(ksName, cfName, udt.fieldType(0), GeoPointFieldMapper.Names.LAT, values.get(1), null),
serialize(ksName, cfName, udt.fieldType(1), GeoPointFieldMapper.Names.LON, values.get(0), null)
};
ByteBuffer geo_point = TupleType.buildValue(elements);
return CollectionSerializer.pack(ImmutableList.of(geo_point), 1, ProtocolVersion.CURRENT);
}
if (value instanceof Collection) {
// list of elementType
List<ByteBuffer> elements = new ArrayList<ByteBuffer>();
for(Object v : flattenCollection((Collection) value)) {
ByteBuffer bb = serialize(ksName, cfName, elementType, name, v, mapper);
elements.add(bb);
}
return CollectionSerializer.pack(elements, elements.size(), ProtocolVersion.CURRENT);
} else {
// singleton list
ByteBuffer bb = serialize(ksName, cfName, elementType, name, value, mapper);
return CollectionSerializer.pack(ImmutableList.of(bb), 1, ProtocolVersion.CURRENT);
}
} else {
// Native cassandra type, encoded with mapper if available.
if (mapper != null) {
if (mapper instanceof FieldMapper) {
return type.decompose( ((FieldMapper) mapper).fieldType().cqlValue(value, type) );
} else if (mapper instanceof ObjectMapper && !((ObjectMapper)mapper).isEnabled()) {
// enabled=false => store field as json text
if (value instanceof Map) {
XContentBuilder builder = XContentFactory.jsonBuilder();
builder.map( (Map) value);
return type.decompose( builder.string() );
}
return type.decompose( value );
}
}
return type.decompose( value );
}
}
public static Object deserialize(AbstractType<?> type, ByteBuffer bb) throws CharacterCodingException {
return deserialize(type, bb, null);
}
public static Object deserialize(AbstractType<?> type, ByteBuffer bb, Mapper mapper) throws CharacterCodingException {
if (type instanceof UserType) {
UserType udt = (UserType) type;
Map<String, Object> mapValue = new HashMap<String, Object>();
ByteBuffer[] components = udt.split(bb);
if (GEO_POINT_TYPE.equals(ByteBufferUtil.string(udt.name))) {
if (components[0] != null)
mapValue.put(GeoPointFieldMapper.Names.LAT, deserialize(udt.type(0), components[0], null));
if (components[1] != null)
mapValue.put(GeoPointFieldMapper.Names.LON, deserialize(udt.type(1), components[1], null));
} else {
for (int i = 0; i < components.length; i++) {
String fieldName = UTF8Type.instance.compose(udt.fieldName(i).bytes);
AbstractType<?> ctype = udt.type(i);
Mapper subMapper = null;
if (mapper != null && mapper instanceof ObjectMapper)
subMapper = ((ObjectMapper)mapper).getMapper(fieldName);
Object value = (components[i] == null) ? null : deserialize(ctype, components[i], subMapper);
mapValue.put(fieldName, value);
}
}
return mapValue;
} else if (type instanceof ListType) {
ListType<?> ltype = (ListType<?>)type;
ByteBuffer input = bb.duplicate();
int size = CollectionSerializer.readCollectionSize(input, ProtocolVersion.CURRENT);
List list = new ArrayList(size);
for (int i = 0; i < size; i++) {
list.add( deserialize(ltype.getElementsType(), CollectionSerializer.readValue(input, ProtocolVersion.CURRENT), mapper));
}
if (input.hasRemaining())
throw new MarshalException("Unexpected extraneous bytes after map value");
return list;
} else if (type instanceof SetType) {
SetType<?> ltype = (SetType<?>)type;
ByteBuffer input = bb.duplicate();
int size = CollectionSerializer.readCollectionSize(input, ProtocolVersion.CURRENT);
Set set = new HashSet(size);
for (int i = 0; i < size; i++) {
set.add( deserialize(ltype.getElementsType(), CollectionSerializer.readValue(input, ProtocolVersion.CURRENT), mapper));
}
if (input.hasRemaining())
throw new MarshalException("Unexpected extraneous bytes after map value");
return set;
} else if (type instanceof MapType) {
MapType<?,?> ltype = (MapType<?,?>)type;
ByteBuffer input = bb.duplicate();
int size = CollectionSerializer.readCollectionSize(input, ProtocolVersion.CURRENT);
Map map = new LinkedHashMap(size);
for (int i = 0; i < size; i++) {
ByteBuffer kbb = CollectionSerializer.readValue(input, ProtocolVersion.CURRENT);
ByteBuffer vbb = CollectionSerializer.readValue(input, ProtocolVersion.CURRENT);
String key = (String) ltype.getKeysType().compose(kbb);
Mapper subMapper = null;
if (mapper != null) {
assert mapper instanceof ObjectMapper : "Expecting an object mapper for MapType";
subMapper = ((ObjectMapper)mapper).getMapper(key);
}
map.put(key, deserialize(ltype.getValuesType(), vbb, subMapper));
}
if (input.hasRemaining())
throw new MarshalException("Unexpected extraneous bytes after map value");
return map;
} else {
Object value = type.compose(bb);
if (mapper != null && mapper instanceof FieldMapper) {
return ((FieldMapper)mapper).fieldType().valueForDisplay(value);
}
return value;
}
}
public IndexService indexServiceSafe(org.elasticsearch.index.Index index) {
return this.indicesService.indexServiceSafe(index);
}
/**
* Return a set of started shards according t the gossip state map and the local shard state.
*/
public ShardRoutingState getShardRoutingStates(org.elasticsearch.index.Index index, UUID nodeUuid) {
if (nodeUuid.equals(this.localNode().uuid())) {
if (this.discovery.isSearchEnabled()) {
try {
IndexShard localIndexShard = indexServiceSafe(index).getShardOrNull(0);
if (localIndexShard != null && localIndexShard.routingEntry() != null)
return localIndexShard.routingEntry().state();
} catch (IndexNotFoundException e) {
}
}
return ShardRoutingState.UNASSIGNED;
}
// read-only map.
Map<String, ShardRoutingState> shards = (this.discovery).getShardRoutingState(nodeUuid);
if (shards == null) {
if (logger.isDebugEnabled() && state().nodes().get(nodeUuid.toString()).status().equals(DiscoveryNodeStatus.ALIVE))
logger.debug("No ShardRoutingState for alive node=[{}]",nodeUuid.toString());
return ShardRoutingState.UNASSIGNED;
}
return shards.get(index.getName());
}
/**
* Set index shard state in the gossip endpoint map (must be synchronized).
*/
public void publishShardRoutingState(final String index, final ShardRoutingState shardRoutingState) throws JsonGenerationException, JsonMappingException, IOException {
if (this.discovery != null)
this.discovery.publishShardRoutingState(index, shardRoutingState);
}
/**
* Publish cluster metadata uuid and version in gossip state.
*/
public void publishX2(final ClusterState clusterState) {
if (this.discovery != null)
this.discovery.publishX2(clusterState);
}
/**
* publish gossip states when setup completed.
*/
public void publishGossipStates() {
if (this.discovery != null) {
this.discovery.publishX2(state());
try {
this.discovery.publishX1();
} catch (IOException e) {
logger.error("Unexpected error", e);
}
}
}
}
| core/src/main/java/org/elasticsearch/cluster/service/ClusterService.java | /*
* Copyright (c) 2017 Strapdata (http://www.strapdata.com)
* Contains some code from Elasticsearch (http://www.elastic.co)
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.elasticsearch.cluster.service;
import ch.qos.logback.classic.jmx.JMXConfiguratorMBean;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.Appender;
import ch.qos.logback.core.joran.spi.JoranException;
import com.carrotsearch.hppc.cursors.ObjectCursor;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.net.InetAddresses;
import org.apache.cassandra.config.CFMetaData;
import org.apache.cassandra.config.ColumnDefinition;
import org.apache.cassandra.config.DatabaseDescriptor;
import org.apache.cassandra.config.Schema;
import org.apache.cassandra.cql3.CQL3Type;
import org.apache.cassandra.cql3.ColumnIdentifier;
import org.apache.cassandra.cql3.ColumnSpecification;
import org.apache.cassandra.cql3.QueryOptions;
import org.apache.cassandra.cql3.QueryProcessor;
import org.apache.cassandra.cql3.UntypedResultSet;
import org.apache.cassandra.cql3.UntypedResultSet.Row;
import org.apache.cassandra.cql3.statements.IndexTarget;
import org.apache.cassandra.cql3.statements.ParsedStatement;
import org.apache.cassandra.cql3.statements.TableAttributes;
import org.apache.cassandra.db.CBuilder;
import org.apache.cassandra.db.ConsistencyLevel;
import org.apache.cassandra.db.Keyspace;
import org.apache.cassandra.db.KeyspaceNotDefinedException;
import org.apache.cassandra.db.SystemKeyspace;
import org.apache.cassandra.db.marshal.AbstractType;
import org.apache.cassandra.db.marshal.BytesType;
import org.apache.cassandra.db.marshal.CollectionType;
import org.apache.cassandra.db.marshal.ListType;
import org.apache.cassandra.db.marshal.MapType;
import org.apache.cassandra.db.marshal.SetType;
import org.apache.cassandra.db.marshal.TupleType;
import org.apache.cassandra.db.marshal.TypeParser;
import org.apache.cassandra.db.marshal.UTF8Type;
import org.apache.cassandra.db.marshal.UserType;
import org.apache.cassandra.dht.Token;
import org.apache.cassandra.exceptions.ConfigurationException;
import org.apache.cassandra.exceptions.InvalidRequestException;
import org.apache.cassandra.exceptions.RequestExecutionException;
import org.apache.cassandra.exceptions.RequestValidationException;
import org.apache.cassandra.exceptions.SyntaxException;
import org.apache.cassandra.exceptions.UnavailableException;
import org.apache.cassandra.exceptions.WriteTimeoutException;
import org.apache.cassandra.index.Index;
import org.apache.cassandra.locator.AbstractReplicationStrategy;
import org.apache.cassandra.locator.NetworkTopologyStrategy;
import org.apache.cassandra.schema.IndexMetadata;
import org.apache.cassandra.schema.KeyspaceMetadata;
import org.apache.cassandra.schema.ReplicationParams;
import org.apache.cassandra.schema.TableParams;
import org.apache.cassandra.serializers.CollectionSerializer;
import org.apache.cassandra.serializers.MapSerializer;
import org.apache.cassandra.serializers.MarshalException;
import org.apache.cassandra.service.ClientState;
import org.apache.cassandra.service.ElassandraDaemon;
import org.apache.cassandra.service.MigrationManager;
import org.apache.cassandra.service.QueryState;
import org.apache.cassandra.service.StorageService;
import org.apache.cassandra.transport.ProtocolVersion;
import org.apache.cassandra.transport.messages.ResultMessage;
import org.apache.cassandra.utils.ByteBufferUtil;
import org.apache.cassandra.utils.FBUtilities;
import org.apache.cassandra.utils.Pair;
import org.apache.cassandra.utils.UUIDGen;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.message.ParameterizedMessage;
import org.apache.logging.log4j.util.Supplier;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.elassandra.ConcurrentMetaDataUpdateException;
import org.elassandra.NoPersistedMetaDataException;
import org.elassandra.cluster.routing.AbstractSearchStrategy;
import org.elassandra.cluster.routing.PrimaryFirstSearchStrategy;
import org.elassandra.discovery.CassandraDiscovery;
import org.elassandra.index.ExtendedElasticSecondaryIndex;
import org.elassandra.index.mapper.internal.NodeFieldMapper;
import org.elassandra.index.mapper.internal.TokenFieldMapper;
import org.elassandra.index.search.TokenRangesService;
import org.elassandra.indices.CassandraSecondaryIndicesApplier;
import org.elassandra.shard.CassandraShardStartedBarrier;
import org.elasticsearch.ElasticsearchTimeoutException;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.ActionRequestValidationException;
import org.elasticsearch.action.DocWriteRequest;
import org.elasticsearch.action.admin.indices.mapping.put.PutMappingClusterStateUpdateRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.support.replication.ReplicationResponse.ShardInfo;
import org.elasticsearch.cluster.ClusterChangedEvent;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.ClusterStateApplier;
import org.elasticsearch.cluster.ClusterStateListener;
import org.elasticsearch.cluster.ClusterStateTaskConfig;
import org.elasticsearch.cluster.ClusterStateTaskListener;
import org.elasticsearch.cluster.ClusterStateUpdateTask;
import org.elasticsearch.cluster.ack.ClusterStateUpdateRequest;
import org.elasticsearch.cluster.ack.ClusterStateUpdateResponse;
import org.elasticsearch.cluster.action.index.MappingUpdatedAction;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.cluster.metadata.MappingMetaData;
import org.elasticsearch.cluster.metadata.MetaData;
import org.elasticsearch.cluster.metadata.MetaDataMappingService;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.node.DiscoveryNode.DiscoveryNodeStatus;
import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.cluster.routing.OperationRouting;
import org.elasticsearch.cluster.routing.RoutingTable;
import org.elasticsearch.cluster.routing.ShardRoutingState;
import org.elasticsearch.common.Priority;
import org.elasticsearch.common.SuppressForbidden;
import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.logging.Loggers;
import org.elasticsearch.common.settings.ClusterSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.discovery.Discovery;
import org.elasticsearch.gateway.MetaStateService;
import org.elasticsearch.index.IndexNotFoundException;
import org.elasticsearch.index.IndexService;
import org.elasticsearch.index.engine.Engine;
import org.elasticsearch.index.engine.VersionConflictEngineException;
import org.elasticsearch.index.get.GetField;
import org.elasticsearch.index.mapper.BaseGeoPointFieldMapper;
import org.elasticsearch.index.mapper.BaseGeoPointFieldMapper.LegacyGeoPointFieldType;
import org.elasticsearch.index.mapper.CompletionFieldMapper;
import org.elasticsearch.index.mapper.DateFieldMapper;
import org.elasticsearch.index.mapper.DocumentFieldMappers;
import org.elasticsearch.index.mapper.DocumentMapper;
import org.elasticsearch.index.mapper.FieldMapper;
import org.elasticsearch.index.mapper.GeoPointFieldMapper;
import org.elasticsearch.index.mapper.GeoShapeFieldMapper;
import org.elasticsearch.index.mapper.IdFieldMapper;
import org.elasticsearch.index.mapper.MappedFieldType;
import org.elasticsearch.index.mapper.Mapper;
import org.elasticsearch.index.mapper.Mapper.CqlCollection;
import org.elasticsearch.index.mapper.Mapper.CqlStruct;
import org.elasticsearch.index.mapper.MapperException;
import org.elasticsearch.index.mapper.MapperParsingException;
import org.elasticsearch.index.mapper.MapperService;
import org.elasticsearch.index.mapper.Mapping;
import org.elasticsearch.index.mapper.MetadataFieldMapper;
import org.elasticsearch.index.mapper.ObjectMapper;
import org.elasticsearch.index.mapper.ParentFieldMapper;
import org.elasticsearch.index.mapper.RoutingFieldMapper;
import org.elasticsearch.index.mapper.SourceFieldMapper;
import org.elasticsearch.index.mapper.SourceToParse;
import org.elasticsearch.index.mapper.TTLFieldMapper;
import org.elasticsearch.index.mapper.TimestampFieldMapper;
import org.elasticsearch.index.mapper.Uid;
import org.elasticsearch.index.shard.IndexShard;
import org.elasticsearch.indices.IndicesService;
import org.elasticsearch.threadpool.ThreadPool;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.nio.ByteBuffer;
import java.nio.charset.CharacterCodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.LongConsumer;
import java.util.regex.Pattern;
import java.util.stream.Stream;
import javax.management.JMX;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import static org.apache.cassandra.cql3.QueryProcessor.executeInternal;
import static org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_NUMBER_OF_REPLICAS;
public class ClusterService extends org.elasticsearch.cluster.service.BaseClusterService {
public static final String ELASTIC_ID_COLUMN_NAME = "_id";
public static final String ELASTIC_ADMIN_KEYSPACE = "elastic_admin";
public static final String ELASTIC_ADMIN_METADATA_TABLE = "metadata";
public static final String SETTING_CLUSTER_DATACENTER_GROUP = "datacenter.group";
// settings levels : system, cluster, index, table(_meta)
public static final String SYSTEM_PREFIX = "es.";
public static final String CLUSTER_PREFIX = "cluster.";
public static final String INDEX_PREFIX = "index.";
public static final String TABLE_PREFIX = "";
private static final int CREATE_ELASTIC_ADMIN_RETRY_ATTEMPTS = Integer.getInteger(SYSTEM_PREFIX + "create_elastic_admin_retry_attempts", 5);
/**
* Dynamic mapping update timeout
*/
public static final String MAPPING_UPDATE_TIMEOUT = "mapping_update_timeout";
/**
* Secondary index class
*/
public static final String SECONDARY_INDEX_CLASS = "secondary_index_class";
/**
* Search strategy class
*/
public static final String SEARCH_STRATEGY_CLASS = "search_strategy_class";
/**
* When true, add the cassandra node id to documents (for use with the token aggregation feature)
*/
public static final String INCLUDE_NODE_ID = "include_node_id";
/**
* When true, re-indexes a row when compacting, usefull to delete expired documents or columns.
*/
public static final String INDEX_ON_COMPACTION = "index_on_compaction";
/**
* When true, refreshes ES index after each update (used for testing).
*/
public static final String SYNCHRONOUS_REFRESH = "synchronous_refresh";
/**
* When true, delete kespace/table when removing an index.
*/
public static final String DROP_ON_DELETE_INDEX = "drop_on_delete_index";
/**
* When true, snapshot lucene files with sstables.
*/
public static final String SNAPSHOT_WITH_SSTABLE = "snapshot_with_sstable";
/**
* When true, use the optimized version less Elasticsearch engine.
*/
public static final String VERSION_LESS_ENGINE = "version_less_engine";
/**
* Lucene numeric precision to store _token , see http://blog-archive.griddynamics.com/2014/10/numeric-range-queries-in-lucenesolr.html
*/
public static final String TOKEN_PRECISION_STEP = "token_precision_step";
/**
* Enable the token_ranges bitset cache (cache the token_ranges filter result at the lucene liveDocs level).
*/
public static final String TOKEN_RANGES_BITSET_CACHE = "token_ranges_bitset_cache";
/**
* Expiration time for unused cached token_ranges queries.
*/
public static final String TOKEN_RANGES_QUERY_EXPIRE = "token_ranges_query_expire";
/**
* Add static columns to indexed documents (default is false).
*/
public static final String INDEX_STATIC_COLUMNS = "index_static_columns";
/**
* Index only static columns (one document per partition row, ex: timeseries tags).
*/
public static final String INDEX_STATIC_ONLY = "index_static_only";
// system property settings
public static final String SETTING_SYSTEM_MAPPING_UPDATE_TIMEOUT = SYSTEM_PREFIX+MAPPING_UPDATE_TIMEOUT;
public static final String SETTING_SYSTEM_SECONDARY_INDEX_CLASS = SYSTEM_PREFIX+SECONDARY_INDEX_CLASS;
public static final String SETTING_SYSTEM_SEARCH_STRATEGY_CLASS = SYSTEM_PREFIX+SEARCH_STRATEGY_CLASS;
public static final String SETTING_SYSTEM_INCLUDE_NODE_ID = SYSTEM_PREFIX+INCLUDE_NODE_ID;
public static final String SETTING_SYSTEM_INDEX_ON_COMPACTION = SYSTEM_PREFIX+INDEX_ON_COMPACTION;
public static final String SETTING_SYSTEM_SYNCHRONOUS_REFRESH = SYSTEM_PREFIX+SYNCHRONOUS_REFRESH;
public static final String SETTING_SYSTEM_DROP_ON_DELETE_INDEX = SYSTEM_PREFIX+DROP_ON_DELETE_INDEX;
public static final String SETTING_SYSTEM_SNAPSHOT_WITH_SSTABLE = SYSTEM_PREFIX+SNAPSHOT_WITH_SSTABLE;
public static final String SETTING_SYSTEM_VERSION_LESS_ENGINE = SYSTEM_PREFIX+VERSION_LESS_ENGINE;
public static final String SETTING_SYSTEM_TOKEN_PRECISION_STEP = SYSTEM_PREFIX+TOKEN_PRECISION_STEP;
public static final String SETTING_SYSTEM_TOKEN_RANGES_BITSET_CACHE = SYSTEM_PREFIX+TOKEN_RANGES_BITSET_CACHE;
public static final String SETTING_SYSTEM_TOKEN_RANGES_QUERY_EXPIRE = SYSTEM_PREFIX+TOKEN_RANGES_QUERY_EXPIRE;
// elassandra cluster settings
public static final String SETTING_CLUSTER_MAPPING_UPDATE_TIMEOUT = CLUSTER_PREFIX+MAPPING_UPDATE_TIMEOUT;
public static final String SETTING_CLUSTER_SECONDARY_INDEX_CLASS = CLUSTER_PREFIX+SECONDARY_INDEX_CLASS;
public static final String SETTING_CLUSTER_SEARCH_STRATEGY_CLASS = CLUSTER_PREFIX+SEARCH_STRATEGY_CLASS;
public static final String SETTING_CLUSTER_INCLUDE_NODE_ID = CLUSTER_PREFIX+INCLUDE_NODE_ID;
public static final String SETTING_CLUSTER_INDEX_ON_COMPACTION = CLUSTER_PREFIX+INDEX_ON_COMPACTION;
public static final String SETTING_CLUSTER_SYNCHRONOUS_REFRESH = CLUSTER_PREFIX+SYNCHRONOUS_REFRESH;
public static final String SETTING_CLUSTER_DROP_ON_DELETE_INDEX = CLUSTER_PREFIX+DROP_ON_DELETE_INDEX;
public static final String SETTING_CLUSTER_SNAPSHOT_WITH_SSTABLE = CLUSTER_PREFIX+SNAPSHOT_WITH_SSTABLE;
public static final String SETTING_CLUSTER_VERSION_LESS_ENGINE = CLUSTER_PREFIX+VERSION_LESS_ENGINE;
public static final String SETTING_CLUSTER_TOKEN_PRECISION_STEP = CLUSTER_PREFIX+TOKEN_PRECISION_STEP;
public static final String SETTING_CLUSTER_TOKEN_RANGES_BITSET_CACHE = CLUSTER_PREFIX+TOKEN_RANGES_BITSET_CACHE;
public static int defaultPrecisionStep = Integer.getInteger(SETTING_SYSTEM_TOKEN_PRECISION_STEP, 6);
public static class DocPrimaryKey {
public String[] names;
public Object[] values;
public boolean isStaticDocument; // pk = partition key and pk has clustering key.
public DocPrimaryKey(String[] names, Object[] values, boolean isStaticDocument) {
this.names = names;
this.values = values;
this.isStaticDocument = isStaticDocument;
}
public DocPrimaryKey(String[] names, Object[] values) {
this.names = names;
this.values = values;
this.isStaticDocument = false;
}
public List<ByteBuffer> serialize(ParsedStatement.Prepared prepared) {
List<ByteBuffer> boundValues = new ArrayList<ByteBuffer>(values.length);
for (int i = 0; i < values.length; i++) {
Object v = values[i];
AbstractType type = prepared.boundNames.get(i).type;
boundValues.add(v instanceof ByteBuffer || v == null ? (ByteBuffer) v : type.decompose(v));
}
return boundValues;
}
}
public static Map<String, String> cqlMapping = new ImmutableMap.Builder<String,String>()
.put("text", "keyword")
.put("varchar", "keyword")
.put("timestamp", "date")
.put("date", "date")
.put("time", "long")
.put("int", "integer")
.put("double", "double")
.put("float", "float")
.put("bigint", "long")
.put("boolean", "boolean")
.put("blob", "binary")
.put("inet", "ip" )
.put("uuid", "keyword" )
.put("timeuuid", "keyword" )
.build();
private MetaStateService metaStateService;
private IndicesService indicesService;
private CassandraDiscovery discovery;
private final TokenRangesService tokenRangeService;
private final CassandraSecondaryIndicesApplier cassandraSecondaryIndicesApplier;
// manage asynchronous CQL schema update
protected final AtomicReference<MetadataSchemaUpdate> lastMetadataToSave = new AtomicReference<MetadataSchemaUpdate>(null);
protected final Semaphore metadataToSaveSemaphore = new Semaphore(0);
protected final MappingUpdatedAction mappingUpdatedAction;
public final static Class<? extends Index> defaultSecondaryIndexClass = ExtendedElasticSecondaryIndex.class;
protected final PrimaryFirstSearchStrategy primaryFirstSearchStrategy = new PrimaryFirstSearchStrategy();
protected final Map<String, AbstractSearchStrategy> strategies = new ConcurrentHashMap<String, AbstractSearchStrategy>();
protected final Map<String, AbstractSearchStrategy.Router> routers = new ConcurrentHashMap<String, AbstractSearchStrategy.Router>();
private final ConsistencyLevel metadataWriteCL = consistencyLevelFromString(System.getProperty("elassandra.metadata.write.cl","QUORUM"));
private final ConsistencyLevel metadataReadCL = consistencyLevelFromString(System.getProperty("elassandra.metadata.read.cl","QUORUM"));
private final ConsistencyLevel metadataSerialCL = consistencyLevelFromString(System.getProperty("elassandra.metadata.serial.cl","SERIAL"));
private final String elasticAdminKeyspaceName;
private final String selectMetadataQuery;
private final String selectVersionMetadataQuery;
private final String insertMetadataQuery;
private final String updateMetaDataQuery;
private volatile CassandraShardStartedBarrier shardStartedBarrier;
private final OperationRouting operationRouting;
@Inject
public ClusterService(Settings settings, ClusterSettings clusterSettings, ThreadPool threadPool, Supplier<DiscoveryNode> localNodeSupplier) {
super(settings, clusterSettings, threadPool, localNodeSupplier);
this.mappingUpdatedAction = null;
this.tokenRangeService = new TokenRangesService(settings);
this.cassandraSecondaryIndicesApplier = new CassandraSecondaryIndicesApplier(settings, this);
this.operationRouting = new OperationRouting(settings, clusterSettings, this);
String datacenterGroup = settings.get(SETTING_CLUSTER_DATACENTER_GROUP);
if (datacenterGroup != null && datacenterGroup.length() > 0) {
logger.info("Starting with datacenter.group=[{}]", datacenterGroup.trim().toLowerCase(Locale.ROOT));
elasticAdminKeyspaceName = String.format(Locale.ROOT, "%s_%s", ELASTIC_ADMIN_KEYSPACE,datacenterGroup.trim().toLowerCase(Locale.ROOT));
} else {
elasticAdminKeyspaceName = ELASTIC_ADMIN_KEYSPACE;
}
selectMetadataQuery = String.format(Locale.ROOT, "SELECT metadata,version,owner FROM \"%s\".\"%s\" WHERE cluster_name = ?", elasticAdminKeyspaceName, ELASTIC_ADMIN_METADATA_TABLE);
selectVersionMetadataQuery = String.format(Locale.ROOT, "SELECT version FROM \"%s\".\"%s\" WHERE cluster_name = ?", elasticAdminKeyspaceName, ELASTIC_ADMIN_METADATA_TABLE);
insertMetadataQuery = String.format(Locale.ROOT, "INSERT INTO \"%s\".\"%s\" (cluster_name,owner,version,metadata) VALUES (?,?,?,?) IF NOT EXISTS", elasticAdminKeyspaceName, ELASTIC_ADMIN_METADATA_TABLE);
updateMetaDataQuery = String.format(Locale.ROOT, "UPDATE \"%s\".\"%s\" SET owner = ?, version = ?, metadata = ? WHERE cluster_name = ? IF version < ?", elasticAdminKeyspaceName, ELASTIC_ADMIN_METADATA_TABLE);
}
public OperationRouting operationRouting() {
return operationRouting;
}
public void setMetaStateService(MetaStateService metaStateService) {
this.metaStateService = metaStateService;
}
public void setIndicesService(IndicesService indicesService) {
this.indicesService = indicesService;
}
public IndicesService getIndicesService() {
return this.indicesService;
}
public void setDiscovery(Discovery discovery) {
this.discovery = (CassandraDiscovery)discovery;
}
public TokenRangesService tokenRangesService() {
return this.tokenRangeService;
}
public void addShardStartedBarrier() {
this.shardStartedBarrier = new CassandraShardStartedBarrier(settings, this);
}
public void removeShardStartedBarrier() {
this.shardStartedBarrier = null;
}
public void blockUntilShardsStarted() {
if (shardStartedBarrier != null) {
shardStartedBarrier.blockUntilShardsStarted();
}
}
public String getElasticAdminKeyspaceName() {
return this.elasticAdminKeyspaceName;
}
public boolean isNativeCql3Type(String cqlType) {
return cqlMapping.keySet().contains(cqlType) && !cqlType.startsWith("geo_");
}
public Class<? extends AbstractSearchStrategy> searchStrategyClass(IndexMetaData indexMetaData, ClusterState state) {
try {
return AbstractSearchStrategy.getSearchStrategyClass(
indexMetaData.getSettings().get(IndexMetaData.SETTING_SEARCH_STRATEGY_CLASS,
state.metaData().settings().get(ClusterService.SETTING_CLUSTER_SEARCH_STRATEGY_CLASS,PrimaryFirstSearchStrategy.class.getName()))
);
} catch(ConfigurationException e) {
logger.error((Supplier<?>) () -> new ParameterizedMessage("Bad search strategy class, fallback to [{}]", PrimaryFirstSearchStrategy.class.getName()), e);
return PrimaryFirstSearchStrategy.class;
}
}
private AbstractSearchStrategy searchStrategyInstance(Class<? extends AbstractSearchStrategy> clazz) {
AbstractSearchStrategy searchStrategy = strategies.get(clazz.getName());
if (searchStrategy == null) {
try {
searchStrategy = clazz.newInstance();
} catch (Exception e) {
logger.error((Supplier<?>) () -> new ParameterizedMessage("Cannot instanciate search strategy [{}]", clazz.getName()), e);
searchStrategy = new PrimaryFirstSearchStrategy();
}
strategies.putIfAbsent(clazz.getName(), searchStrategy);
}
return searchStrategy;
}
public PrimaryFirstSearchStrategy.PrimaryFirstRouter updateRouter(IndexMetaData indexMetaData, ClusterState state) {
// update and returns a PrimaryFirstRouter for the build table.
PrimaryFirstSearchStrategy.PrimaryFirstRouter router = (PrimaryFirstSearchStrategy.PrimaryFirstRouter)this.primaryFirstSearchStrategy.newRouter(indexMetaData.getIndex(), indexMetaData.keyspace(), this::getShardRoutingStates, state);
// update the router cache with the effective router
AbstractSearchStrategy effectiveSearchStrategy = searchStrategyInstance(searchStrategyClass(indexMetaData, state));
if (! effectiveSearchStrategy.equals(PrimaryFirstSearchStrategy.class) ) {
AbstractSearchStrategy.Router router2 = effectiveSearchStrategy.newRouter(indexMetaData.getIndex(), indexMetaData.keyspace(), this::getShardRoutingStates, state);
this.routers.put(indexMetaData.getIndex().getName(), router2);
} else {
this.routers.put(indexMetaData.getIndex().getName(), router);
}
return router;
}
public AbstractSearchStrategy.Router getRouter(IndexMetaData indexMetaData, ClusterState state) {
AbstractSearchStrategy.Router router = this.routers.get(indexMetaData.getIndex().getName());
return router;
}
public UntypedResultSet process(final ConsistencyLevel cl, final String query)
throws RequestExecutionException, RequestValidationException, InvalidRequestException {
return process(cl, null, query, new Long(0), new Object[] {});
}
public UntypedResultSet process(final ConsistencyLevel cl, ClientState clientState, final String query)
throws RequestExecutionException, RequestValidationException, InvalidRequestException {
return process(cl, null, clientState, query, new Long(0), new Object[] {});
}
public UntypedResultSet process(final ConsistencyLevel cl, ClientState clientState, final String query, Object... values)
throws RequestExecutionException, RequestValidationException, InvalidRequestException {
return process(cl, null, clientState, query, new Long(0), values);
}
public UntypedResultSet process(final ConsistencyLevel cl, final String query, Object... values)
throws RequestExecutionException, RequestValidationException, InvalidRequestException {
return process(cl, null, query, new Long(0), values);
}
public UntypedResultSet process(final ConsistencyLevel cl, final ConsistencyLevel serialConsistencyLevel, final String query, final Object... values)
throws RequestExecutionException, RequestValidationException, InvalidRequestException {
return process(cl, serialConsistencyLevel, query, new Long(0), values);
}
public UntypedResultSet process(final ConsistencyLevel cl, final ConsistencyLevel serialConsistencyLevel, final String query, Long writetime, final Object... values) {
ClientState clientState = this.threadPool.getThreadContext().getTransient("_client_state");
if (clientState == null)
clientState = ClientState.forInternalCalls();
return process(cl, serialConsistencyLevel, clientState, query, writetime, values);
}
public UntypedResultSet process(final ConsistencyLevel cl, final ConsistencyLevel serialConsistencyLevel, ClientState clientState, final String query, Long writetime, final Object... values)
throws RequestExecutionException, RequestValidationException, InvalidRequestException {
if (logger.isDebugEnabled())
logger.debug("processing CL={} SERIAL_CL={} query={}", cl, serialConsistencyLevel, query);
// retreive prepared
QueryState queryState = new QueryState(clientState);
ResultMessage.Prepared prepared = ClientState.getCQLQueryHandler().prepare(query, queryState, Collections.EMPTY_MAP);
// bind
List<ByteBuffer> boundValues = new ArrayList<ByteBuffer>(values.length);
for (int i = 0; i < values.length; i++) {
Object v = values[i];
AbstractType type = prepared.metadata.names.get(i).type;
boundValues.add(v instanceof ByteBuffer || v == null ? (ByteBuffer) v : type.decompose(v));
}
// execute
QueryOptions queryOptions = QueryOptions.forInternalCalls(cl, serialConsistencyLevel, boundValues);
ResultMessage result = ClientState.getCQLQueryHandler().process(query, queryState, queryOptions, Collections.EMPTY_MAP, System.nanoTime());
writetime = queryState.getTimestamp();
return (result instanceof ResultMessage.Rows) ? UntypedResultSet.create(((ResultMessage.Rows) result).result) : null;
}
public boolean processWriteConditional(final ConsistencyLevel cl, final ConsistencyLevel serialCl, final String query, Object... values) {
ClientState clientState = this.threadPool.getThreadContext().getTransient("_client_state");
if (clientState == null)
clientState = ClientState.forInternalCalls();
return processWriteConditional(cl, serialCl, clientState, query, values);
}
public boolean processWriteConditional(final ConsistencyLevel cl, final ConsistencyLevel serialCl, ClientState clientState, final String query, Object... values)
throws RequestExecutionException, RequestValidationException, InvalidRequestException {
try {
UntypedResultSet result = process(cl, serialCl, clientState, query, new Long(0), values);
if (serialCl == null)
return true;
if (!result.isEmpty()) {
Row row = result.one();
if (row.has("[applied]")) {
return row.getBoolean("[applied]");
}
}
return false;
} catch (WriteTimeoutException e) {
logger.warn("PAXOS phase failed query=" + query + " values=" + Arrays.toString(values), e);
return false;
} catch (UnavailableException e) {
logger.warn("PAXOS commit failed query=" + query + " values=" + Arrays.toString(values), e);
return false;
} catch (Exception e) {
logger.error("Failed to process query=" + query + " values=" + Arrays.toString(values), e);
throw e;
}
}
/**
* Don't use QueryProcessor.executeInternal, we need to propagate this on all nodes.
**/
public void createIndexKeyspace(final String ksname, final int replicationFactor) throws IOException {
Keyspace ks = null;
try {
ks = Keyspace.open(ksname);
if (ks != null && !(ks.getReplicationStrategy() instanceof NetworkTopologyStrategy)) {
throw new IOException("Cannot create index, underlying keyspace requires the NetworkTopologyStrategy.");
}
} catch(AssertionError | NullPointerException e) {
}
try {
if (ks == null)
process(ConsistencyLevel.LOCAL_ONE, ClientState.forInternalCalls(),
String.format(Locale.ROOT, "CREATE KEYSPACE IF NOT EXISTS \"%s\" WITH replication = {'class':'NetworkTopologyStrategy', '%s':'%d' };",
ksname, DatabaseDescriptor.getLocalDataCenter(), replicationFactor));
} catch (Throwable e) {
throw new IOException(e.getMessage(), e);
}
}
public void dropIndexKeyspace(final String ksname) throws IOException {
try {
String query = String.format(Locale.ROOT, "DROP KEYSPACE IF EXISTS \"%s\"", ksname);
logger.debug(query);
QueryProcessor.process(query, ConsistencyLevel.LOCAL_ONE);
} catch (Throwable e) {
throw new IOException(e.getMessage(), e);
}
}
public static Pair<List<String>, List<String>> getUDTInfo(final String ksName, final String typeName) {
try {
UntypedResultSet result = QueryProcessor.executeOnceInternal("SELECT field_names, field_types FROM system_schema.types WHERE keyspace_name = ? AND type_name = ?",
new Object[] { ksName, typeName });
Row row = result.one();
if ((row != null) && row.has("field_names")) {
List<String> field_names = row.getList("field_names", UTF8Type.instance);
List<String> field_types = row.getList("field_types", UTF8Type.instance);
return Pair.<List<String>, List<String>> create(field_names, field_types);
}
} catch (Exception e) {
}
return null;
}
public static MapType<?,?> getMapType(final String ksName, final String cfName, final String colName) {
try {
UntypedResultSet result = QueryProcessor.executeOnceInternal("SELECT validator FROM system.schema_columns WHERE keyspace_name = ? AND columnfamily_name = ? AND column_name = ?",
new Object[] { ksName, cfName, colName });
Row row = result.one();
if ((row != null) && row.has("validator")) {
AbstractType<?> type = TypeParser.parse(row.getString("validator"));
if (type instanceof MapType) {
return (MapType<?,?>)type;
}
}
} catch (Exception e) {
}
return null;
}
// see https://docs.datastax.com/en/cql/3.0/cql/cql_reference/keywords_r.html
public static final Pattern keywordsPattern = Pattern.compile("(ADD|ALLOW|ALTER|AND|ANY|APPLY|ASC|AUTHORIZE|BATCH|BEGIN|BY|COLUMNFAMILY|CREATE|DELETE|DESC|DROP|EACH_QUORUM|GRANT|IN|INDEX|INET|INSERT|INTO|KEYSPACE|KEYSPACES|LIMIT|LOCAL_ONE|LOCAL_QUORUM|MODIFY|NOT|NORECURSIVE|OF|ON|ONE|ORDER|PASSWORD|PRIMARY|QUORUM|RENAME|REVOKE|SCHEMA|SELECT|SET|TABLE|TO|TOKEN|THREE|TRUNCATE|TWO|UNLOGGED|UPDATE|USE|USING|WHERE|WITH)");
public static boolean isReservedKeyword(String identifier) {
return keywordsPattern.matcher(identifier.toUpperCase(Locale.ROOT)).matches();
}
private static Object toJsonValue(Object o) {
if (o instanceof UUID)
return o.toString();
if (o instanceof Date)
return ((Date)o).getTime();
if (o instanceof ByteBuffer) {
// encode byte[] as Base64 encoded string
ByteBuffer bb = ByteBufferUtil.clone((ByteBuffer)o);
return Base64.getEncoder().encodeToString(ByteBufferUtil.getArray((ByteBuffer)o));
}
if (o instanceof InetAddress)
return InetAddresses.toAddrString((InetAddress)o);
return o;
}
private static org.codehaus.jackson.map.ObjectMapper jsonMapper = new org.codehaus.jackson.map.ObjectMapper();
// wrap string values with quotes
private static String stringify(Object o) throws IOException {
Object v = toJsonValue(o);
try {
return v instanceof String ? jsonMapper.writeValueAsString(v) : v.toString();
} catch (IOException e) {
Loggers.getLogger(ClusterService.class).error("Unexpected json encoding error", e);
throw new RuntimeException(e);
}
}
public static String stringify(Object[] cols, int length) {
if (cols.length == 1)
return toJsonValue(cols[0]).toString();
StringBuilder sb = new StringBuilder();
sb.append("[");
for(int i = 0; i < length; i++) {
if (i > 0)
sb.append(",");
Object val = toJsonValue(cols[i]);
if (val instanceof String) {
try {
sb.append(jsonMapper.writeValueAsString(val));
} catch (IOException e) {
Loggers.getLogger(ClusterService.class).error("Unexpected json encoding error", e);
throw new RuntimeException(e);
}
} else {
sb.append(val);
}
}
return sb.append("]").toString();
}
public static ByteBuffer fromString(AbstractType<?> atype, String v) throws IOException {
if (atype instanceof BytesType)
return ByteBuffer.wrap(Base64.getDecoder().decode(v));
return atype.fromString(v);
}
public static void toXContent(XContentBuilder builder, Mapper mapper, String field, Object value) throws IOException {
if (value instanceof Collection) {
if (field == null) {
builder.startArray();
} else {
builder.startArray(field);
}
for(Iterator<Object> i = ((Collection)value).iterator(); i.hasNext(); ) {
toXContent(builder, mapper, null, i.next());
}
builder.endArray();
} else if (value instanceof Map) {
Map<String, Object> map = (Map<String,Object>)value;
if (field != null) {
builder.startObject(field);
} else {
builder.startObject();
}
for(String subField : map.keySet()) {
Object subValue = map.get(subField);
if (subValue == null)
continue;
if (subValue instanceof Collection && ((Collection)subValue).size() == 1)
subValue = ((Collection)subValue).iterator().next();
if (mapper != null) {
if (mapper instanceof ObjectMapper) {
toXContent(builder, ((ObjectMapper)mapper).getMapper(subField), subField, subValue);
} else if (mapper instanceof BaseGeoPointFieldMapper) {
BaseGeoPointFieldMapper geoMapper = (BaseGeoPointFieldMapper)mapper;
if (geoMapper.fieldType() instanceof LegacyGeoPointFieldType && ((LegacyGeoPointFieldType)geoMapper.fieldType()).isLatLonEnabled()) {
Iterator<Mapper> it = geoMapper.iterator();
switch(subField) {
case org.elasticsearch.index.mapper.BaseGeoPointFieldMapper.Names.LAT:
toXContent(builder, it.next(), org.elasticsearch.index.mapper.BaseGeoPointFieldMapper.Names.LAT, map.get(org.elasticsearch.index.mapper.BaseGeoPointFieldMapper.Names.LAT));
break;
case org.elasticsearch.index.mapper.BaseGeoPointFieldMapper.Names.LON:
it.next();
toXContent(builder, it.next(), org.elasticsearch.index.mapper.BaseGeoPointFieldMapper.Names.LON, map.get(org.elasticsearch.index.mapper.BaseGeoPointFieldMapper.Names.LON));
break;
}
} else {
// No mapper known
// TODO: support geohashing
builder.field(subField, subValue);
}
} else {
builder.field(subField, subValue);
}
} else {
builder.field(subField, subValue);
}
}
builder.endObject();
} else {
if (mapper instanceof FieldMapper) {
FieldMapper fieldMapper = (FieldMapper)mapper;
if (!(fieldMapper instanceof MetadataFieldMapper)) {
if (field != null) {
builder.field(field, fieldMapper.fieldType().valueForDisplay(value));
} else {
builder.value((fieldMapper==null) ? value : fieldMapper.fieldType().valueForDisplay(value));
}
}
} else if (mapper instanceof ObjectMapper) {
ObjectMapper objectMapper = (ObjectMapper)mapper;
if (!objectMapper.isEnabled()) {
builder.field(field, value);
} else {
throw new IOException("Unexpected object value ["+value+"]");
}
}
}
}
public static XContentBuilder buildDocument(DocumentMapper documentMapper, Map<String, Object> docMap, boolean humanReadable) throws IOException {
return buildDocument(documentMapper, docMap, humanReadable, false);
}
public static XContentBuilder buildDocument(DocumentMapper documentMapper, Map<String, Object> docMap, boolean humanReadable, boolean forStaticDocument) throws IOException {
XContentBuilder builder = XContentFactory.contentBuilder(XContentType.JSON).humanReadable(true);
builder.startObject();
for(String field : docMap.keySet()) {
if (field.equals(ParentFieldMapper.NAME)) continue;
FieldMapper fieldMapper = documentMapper.mappers().smartNameFieldMapper(field);
if (fieldMapper != null) {
if (forStaticDocument && !isStaticOrPartitionKey(fieldMapper))
continue;
toXContent(builder, fieldMapper, field, docMap.get(field));
} else {
ObjectMapper objectMapper = documentMapper.objectMappers().get(field);
if (objectMapper != null) {
if (forStaticDocument && !isStaticOrPartitionKey(objectMapper))
continue;
toXContent(builder, objectMapper, field, docMap.get(field));
} else {
Loggers.getLogger(ClusterService.class).error("No mapper found for field "+field);
throw new IOException("No mapper found for field "+field);
}
}
}
builder.endObject();
return builder;
}
public static boolean isStaticOrPartitionKey(Mapper mapper) {
return mapper.cqlStaticColumn() || mapper.cqlPartitionKey();
}
public static final String PERCOLATOR_TABLE = "_percolator";
private static final Map<String, String> cfNameToType = new ConcurrentHashMap<String, String>() {{
put(PERCOLATOR_TABLE, MapperService.PERCOLATOR_LEGACY_TYPE_NAME);
}};
public static String typeToCfName(String type) {
if (type.indexOf('-') >= 0) {
String cfName = type.replaceAll("\\-", "_");
cfNameToType.putIfAbsent(cfName, type);
return cfName;
}
return type;
}
public static String cfNameToType(String cfName) {
if (cfName.indexOf('_') >= 0) {
String type = cfNameToType.get(cfName);
if (type != null)
return type;
}
return cfName;
}
public static String indexToKsName(String index) {
return index.replaceAll("\\.", "_").replaceAll("\\-", "_");
}
public String buildCql(final String ksName, final String cfName, final String name, final ObjectMapper objectMapper) throws RequestExecutionException {
if (objectMapper.cqlStruct().equals(CqlStruct.UDT)) {
return buildUDT(ksName, cfName, name, objectMapper);
} else if (objectMapper.cqlStruct().equals(CqlStruct.MAP)) {
if (objectMapper.iterator().hasNext()) {
Mapper childMapper = objectMapper.iterator().next();
if (childMapper instanceof FieldMapper) {
return "map<text,"+childMapper.cqlType()+">";
} else if (childMapper instanceof ObjectMapper) {
return "map<text,frozen<"+buildCql(ksName,cfName,childMapper.simpleName(),(ObjectMapper)childMapper)+">>";
}
} else {
// default map prototype, no mapper to determine the value type.
return "map<text,text>";
}
}
return null;
}
public String buildUDT(final String ksName, final String cfName, final String name, final ObjectMapper objectMapper) throws RequestExecutionException {
String typeName = (objectMapper.cqlUdtName() == null) ? cfName + "_" + objectMapper.fullPath().replace('.', '_') : objectMapper.cqlUdtName();
if (!objectMapper.iterator().hasNext()) {
throw new InvalidRequestException("Cannot create an empty nested type (not supported)");
}
// create sub-type first
for (Iterator<Mapper> it = objectMapper.iterator(); it.hasNext(); ) {
Mapper mapper = it.next();
if (mapper instanceof ObjectMapper) {
buildCql(ksName, cfName, mapper.simpleName(), (ObjectMapper) mapper);
} else if (mapper instanceof BaseGeoPointFieldMapper) {
buildGeoPointType(ksName);
}
}
Pair<List<String>, List<String>> udt = getUDTInfo(ksName, typeName);
if (udt == null) {
// create new UDT.
StringBuilder create = new StringBuilder(String.format(Locale.ROOT, "CREATE TYPE IF NOT EXISTS \"%s\".\"%s\" ( ", ksName, typeName));
boolean first = true;
for (Iterator<Mapper> it = objectMapper.iterator(); it.hasNext(); ) {
Mapper mapper = it.next();
if (first)
first = false;
else
create.append(", ");
// Use only the last part of the fullname to build UDT.
int lastDotIndex = mapper.name().lastIndexOf('.');
String shortName = (lastDotIndex > 0) ? mapper.name().substring(lastDotIndex+1) : mapper.name();
if (isReservedKeyword(shortName))
logger.warn("Allowing a CQL reserved keyword in ES: {}", shortName);
create.append('\"').append(shortName).append("\" ");
if (mapper instanceof ObjectMapper) {
if (!mapper.cqlCollection().equals(CqlCollection.SINGLETON))
create.append(mapper.cqlCollectionTag()).append("<");
create.append("frozen<")
.append(ColumnIdentifier.maybeQuote(cfName+'_'+((ObjectMapper) mapper).fullPath().replace('.', '_')))
.append(">");
if (!mapper.cqlCollection().equals(CqlCollection.SINGLETON))
create.append(">");
} else if (mapper instanceof BaseGeoPointFieldMapper) {
if (!mapper.cqlCollection().equals(CqlCollection.SINGLETON))
create.append(mapper.cqlCollectionTag()).append("<");
create.append("frozen<")
.append(GEO_POINT_TYPE)
.append(">");
if (!mapper.cqlCollection().equals(CqlCollection.SINGLETON))
create.append(">");
} else if (mapper instanceof GeoShapeFieldMapper) {
if (!mapper.cqlCollection().equals(CqlCollection.SINGLETON))
create.append(mapper.cqlCollectionTag()).append("<");
create.append("frozen<")
.append("text")
.append(">");
if (!mapper.cqlCollection().equals(CqlCollection.SINGLETON))
create.append(">");
} else {
String cqlType = mapper.cqlType();
if (mapper.cqlCollection().equals(CqlCollection.SINGLETON)) {
create.append(cqlType);
} else {
create.append(mapper.cqlCollectionTag()).append("<");
if (!isNativeCql3Type(cqlType)) create.append("frozen<");
create.append(cqlType);
if (!isNativeCql3Type(cqlType)) create.append(">");
create.append(">");
}
}
}
create.append(" )");
if (logger.isDebugEnabled())
logger.debug("create UDT:"+ create.toString());
QueryProcessor.process(create.toString(), ConsistencyLevel.LOCAL_ONE);
} else {
// update existing UDT
for (Iterator<Mapper> it = objectMapper.iterator(); it.hasNext(); ) {
Mapper mapper = it.next();
int lastDotIndex = mapper.name().lastIndexOf('.');
String shortName = (lastDotIndex > 0) ? mapper.name().substring(lastDotIndex+1) : mapper.name();
if (isReservedKeyword(shortName))
logger.warn("Allowing a CQL reserved keyword in ES: {}", shortName);
StringBuilder update = new StringBuilder(String.format(Locale.ROOT, "ALTER TYPE \"%s\".\"%s\" ADD \"%s\" ", ksName, typeName, shortName));
if (!udt.left.contains(shortName)) {
if (mapper instanceof ObjectMapper) {
if (!mapper.cqlCollection().equals(CqlCollection.SINGLETON))
update.append(mapper.cqlCollectionTag()).append("<");
update.append("frozen<")
.append(cfName).append('_').append(((ObjectMapper) mapper).fullPath().replace('.', '_'))
.append(">");
if (!mapper.cqlCollection().equals(CqlCollection.SINGLETON))
update.append(">");
} else if (mapper instanceof BaseGeoPointFieldMapper) {
if (!mapper.cqlCollection().equals(CqlCollection.SINGLETON))
update.append(mapper.cqlCollectionTag()).append("<");
update.append("frozen<")
.append(GEO_POINT_TYPE)
.append(">");
if (!mapper.cqlCollection().equals(CqlCollection.SINGLETON))
update.append(">");
} else {
String cqlType = mapper.cqlType();
if (mapper.cqlCollection().equals(CqlCollection.SINGLETON)) {
update.append(cqlType);
} else {
update.append(mapper.cqlCollectionTag()).append("<");
if (!isNativeCql3Type(cqlType)) update.append("frozen<");
update.append(cqlType);
if (!isNativeCql3Type(cqlType)) update.append(">");
update.append(">");
}
}
if (logger.isDebugEnabled()) {
logger.debug("update UDT: "+update.toString());
}
QueryProcessor.process(update.toString(), ConsistencyLevel.LOCAL_ONE);
}
}
}
return typeName;
}
private static final String GEO_POINT_TYPE = "geo_point";
private static final String ATTACHEMENT_TYPE = "attachement";
private static final String COMPLETION_TYPE = "completion";
private void buildGeoPointType(String ksName) throws RequestExecutionException {
String query = String.format(Locale.ROOT, "CREATE TYPE IF NOT EXISTS \"%s\".\"%s\" ( %s double, %s double)",
ksName, GEO_POINT_TYPE,org.elasticsearch.index.mapper.BaseGeoPointFieldMapper.Names.LAT,org.elasticsearch.index.mapper.BaseGeoPointFieldMapper.Names.LON);
QueryProcessor.process(query, ConsistencyLevel.LOCAL_ONE);
}
private void buildAttachementType(String ksName) throws RequestExecutionException {
String query = String.format(Locale.ROOT, "CREATE TYPE IF NOT EXISTS \"%s\".\"%s\" (context text, content_type text, content_length bigint, date timestamp, title text, author text, keywords text, language text)", ksName, ATTACHEMENT_TYPE);
QueryProcessor.process(query, ConsistencyLevel.LOCAL_ONE);
}
private void buildCompletionType(String ksName) throws RequestExecutionException {
String query = String.format(Locale.ROOT, "CREATE TYPE IF NOT EXISTS \"%s\".\"%s\" (input list<text>, contexts text, weight bigint)", ksName, COMPLETION_TYPE);
QueryProcessor.process(query, ConsistencyLevel.LOCAL_ONE);
}
public static int replicationFactor(String keyspace) {
if (Schema.instance != null && Schema.instance.getKeyspaceInstance(keyspace) != null) {
AbstractReplicationStrategy replicationStrategy = Schema.instance.getKeyspaceInstance(keyspace).getReplicationStrategy();
int rf = replicationStrategy.getReplicationFactor();
if (replicationStrategy instanceof NetworkTopologyStrategy) {
rf = ((NetworkTopologyStrategy)replicationStrategy).getReplicationFactor(DatabaseDescriptor.getLocalDataCenter());
}
return rf;
}
return 0;
}
public ClusterState updateNumberOfReplica(ClusterState currentState) {
MetaData.Builder metaDataBuilder = MetaData.builder(currentState.metaData());
for(Iterator<IndexMetaData> it = currentState.metaData().iterator(); it.hasNext(); ) {
IndexMetaData indexMetaData = it.next();
IndexMetaData.Builder indexMetaDataBuilder = IndexMetaData.builder(indexMetaData);
int rf = replicationFactor(indexMetaData.keyspace());
indexMetaDataBuilder.numberOfReplicas( Math.max(0, rf - 1) );
metaDataBuilder.put(indexMetaDataBuilder.build(), false);
}
return ClusterState.builder(currentState).metaData(metaDataBuilder.build()).build();
}
public ClusterState updateNumberOfShardsAndReplicas(ClusterState currentState) {
int numberOfNodes = currentState.nodes().getSize();
if (numberOfNodes == 0)
return currentState; // for testing purposes.
MetaData.Builder metaDataBuilder = MetaData.builder(currentState.metaData());
for(Iterator<IndexMetaData> it = currentState.metaData().iterator(); it.hasNext(); ) {
IndexMetaData indexMetaData = it.next();
IndexMetaData.Builder indexMetaDataBuilder = IndexMetaData.builder(indexMetaData);
indexMetaDataBuilder.numberOfShards(numberOfNodes);
int rf = replicationFactor(indexMetaData.keyspace());
indexMetaDataBuilder.numberOfReplicas( Math.max(0, rf - 1) );
metaDataBuilder.put(indexMetaDataBuilder.build(), false);
}
return ClusterState.builder(currentState).metaData(metaDataBuilder.build()).build();
}
/**
* Reload cluster metadata from elastic_admin.metadatatable row.
* Should only be called when user keyspaces are initialized.
*/
public void submitRefreshMetaData(final MetaData metaData, final String source) {
submitStateUpdateTask(source, new ClusterStateUpdateTask() {
@Override
public ClusterState execute(ClusterState currentState) {
return ClusterState.builder(currentState).metaData(metaData).build();
}
@Override
public void onFailure(String source, Exception t) {
logger.error((Supplier<?>) () -> new ParameterizedMessage("unexpected failure during [{}]", source), t);
}
});
}
public void submitNumberOfShardsAndReplicasUpdate(final String source) {
submitStateUpdateTask(source, new ClusterStateUpdateTask() {
@Override
public ClusterState execute(ClusterState currentState) {
return updateNumberOfShardsAndReplicas(currentState);
}
@Override
public void onFailure(String source, Exception t) {
logger.error((Supplier<?>) () -> new ParameterizedMessage("unexpected failure during [{}]", source), t);
}
});
}
public void updateRoutingTable() {
submitStateUpdateTask("Update-routing-table" , new ClusterStateUpdateTask() {
@Override
public ClusterState execute(ClusterState currentState) {
return ClusterState.builder(currentState).incrementVersion().build();
}
@Override
public void onFailure(String source, Exception t) {
logger.error((Supplier<?>) () -> new ParameterizedMessage("unexpected failure during [{}]", source), t);
}
});
}
public void updateTableSchema(final MapperService mapperService, final MappingMetaData mappingMd) throws IOException {
try {
String ksName = mapperService.keyspace();
String cfName = ClusterService.typeToCfName(mappingMd.type());
createIndexKeyspace(ksName, settings.getAsInt(SETTING_NUMBER_OF_REPLICAS, 0) +1);
CFMetaData cfm = Schema.instance.getCFMetaData(ksName, cfName);
boolean newTable = (cfm == null);
DocumentMapper docMapper = mapperService.documentMapper(mappingMd.type());
Map<String, Object> mappingMap = mappingMd.sourceAsMap();
Set<String> columns = new HashSet();
if (docMapper.sourceMapper().enabled())
columns.add(SourceFieldMapper.NAME);
if (mappingMap.get("properties") != null)
columns.addAll( ((Map<String, Object>)mappingMap.get("properties")).keySet() );
logger.debug("Updating CQL3 schema {}.{} columns={}", ksName, cfName, columns);
StringBuilder columnsList = new StringBuilder();
Map<String,Boolean> columnsMap = new HashMap<String, Boolean>(columns.size());
String[] primaryKeyList = new String[(newTable) ? columns.size()+1 : cfm.partitionKeyColumns().size()+cfm.clusteringColumns().size()];
int primaryKeyLength = 0;
int partitionKeyLength = 0;
for (String column : columns) {
if (isReservedKeyword(column))
logger.warn("Allowing a CQL reserved keyword in ES: {}", column);
if (column.equals(TokenFieldMapper.NAME))
continue; // ignore pseudo column known by Elasticsearch
if (columnsList.length() > 0)
columnsList.append(',');
String cqlType = null;
boolean isStatic = false;
FieldMapper fieldMapper = docMapper.mappers().smartNameFieldMapper(column);
if (fieldMapper != null) {
if (fieldMapper instanceof BaseGeoPointFieldMapper) {
ColumnDefinition cdef = (newTable) ? null : cfm.getColumnDefinition(new ColumnIdentifier(column, true));
if (cdef != null && cdef.type instanceof UTF8Type) {
// index geohash stored as text in cassandra.
cqlType = "text";
} else {
// create a geo_point UDT to store lat,lon
cqlType = GEO_POINT_TYPE;
buildGeoPointType(ksName);
}
} else if (fieldMapper instanceof GeoShapeFieldMapper) {
cqlType = "text";
} else if (fieldMapper instanceof CompletionFieldMapper) {
cqlType = COMPLETION_TYPE;
buildCompletionType(ksName);
} else if (fieldMapper.getClass().getName().equals("org.elasticsearch.mapper.attachments.AttachmentMapper")) {
// attachement is a plugin, so class may not found.
cqlType = ATTACHEMENT_TYPE;
buildAttachementType(ksName);
} else if (fieldMapper instanceof SourceFieldMapper) {
cqlType = "blob";
} else {
cqlType = fieldMapper.cqlType();
if (cqlType == null) {
logger.warn("Ignoring field [{}] type [{}]", column, fieldMapper.name());
continue;
}
}
columnsMap.put(column, fieldMapper.cqlPartialUpdate());
if (fieldMapper.cqlPrimaryKeyOrder() >= 0) {
if (fieldMapper.cqlPrimaryKeyOrder() < primaryKeyList.length && primaryKeyList[fieldMapper.cqlPrimaryKeyOrder()] == null) {
primaryKeyList[fieldMapper.cqlPrimaryKeyOrder()] = column;
primaryKeyLength = Math.max(primaryKeyLength, fieldMapper.cqlPrimaryKeyOrder()+1);
if (fieldMapper.cqlPartitionKey()) {
partitionKeyLength++;
}
} else {
throw new Exception("Wrong primary key order for column "+column);
}
}
if (!isNativeCql3Type(cqlType)) {
cqlType = "frozen<" + cqlType + ">";
}
if (!fieldMapper.cqlCollection().equals(CqlCollection.SINGLETON)) {
cqlType = fieldMapper.cqlCollectionTag()+"<" + cqlType + ">";
}
isStatic = fieldMapper.cqlStaticColumn();
} else {
ObjectMapper objectMapper = docMapper.objectMappers().get(column);
if (objectMapper == null) {
logger.warn("Cannot infer CQL type from object mapping for field [{}]", column);
continue;
}
columnsMap.put(column, objectMapper.cqlPartialUpdate());
if (objectMapper.cqlPrimaryKeyOrder() >= 0) {
if (objectMapper.cqlPrimaryKeyOrder() < primaryKeyList.length && primaryKeyList[objectMapper.cqlPrimaryKeyOrder()] == null) {
primaryKeyList[objectMapper.cqlPrimaryKeyOrder()] = column;
primaryKeyLength = Math.max(primaryKeyLength, objectMapper.cqlPrimaryKeyOrder()+1);
if (objectMapper.cqlPartitionKey()) {
partitionKeyLength++;
}
} else {
throw new Exception("Wrong primary key order for column "+column);
}
}
if (!objectMapper.isEnabled()) {
logger.debug("Object [{}] not enabled stored as text", column);
cqlType = "text";
} else if (objectMapper.cqlStruct().equals(CqlStruct.MAP)) {
// TODO: check columnName exists and is map<text,?>
cqlType = buildCql(ksName, cfName, column, objectMapper);
if (!objectMapper.cqlCollection().equals(CqlCollection.SINGLETON)) {
cqlType = objectMapper.cqlCollectionTag()+"<"+cqlType+">";
}
//logger.debug("Expecting column [{}] to be a map<text,?>", column);
} else if (objectMapper.cqlStruct().equals(CqlStruct.UDT)) {
// enabled=false => opaque json object
cqlType = (objectMapper.isEnabled()) ? "frozen<" + ColumnIdentifier.maybeQuote(buildCql(ksName, cfName, column, objectMapper)) + ">" : "text";
if (!objectMapper.cqlCollection().equals(CqlCollection.SINGLETON) && !(cfName.equals(PERCOLATOR_TABLE) && column.equals("query"))) {
cqlType = objectMapper.cqlCollectionTag()+"<"+cqlType+">";
}
}
isStatic = objectMapper.cqlStaticColumn();
}
if (newTable) {
if (cqlType != null) {
columnsList.append("\"").append(column).append("\" ").append(cqlType);
if (isStatic) columnsList.append(" static");
}
} else {
ColumnDefinition cdef = cfm.getColumnDefinition(new ColumnIdentifier(column, true));
if (cqlType != null) {
if (cdef == null) {
for(int i=0; i < primaryKeyLength; i++) {
if (primaryKeyList[i] != null && primaryKeyList[i].equals(column))
throw new Exception("Cannot alter primary key of an existing table");
}
try {
String query = String.format(Locale.ROOT, "ALTER TABLE \"%s\".\"%s\" ADD \"%s\" %s %s", ksName, cfName, column, cqlType,(isStatic) ? "static":"");
logger.debug(query);
QueryProcessor.process(query, ConsistencyLevel.LOCAL_ONE);
} catch (Exception e) {
logger.warn("Failed to alter table {}.{} column [{}] with type [{}]", e, ksName, cfName, column, cqlType);
}
} else {
// check that the existing column matches the provided mapping
// TODO: do this check for collection
String existingCqlType = cdef.type.asCQL3Type().toString();
if (!cdef.type.isCollection()) {
if (cqlType.equals("frozen<geo_point>")) {
if (!(existingCqlType.equals("text") || existingCqlType.equals("frozen<geo_point>"))) {
throw new IOException("geo_point cannot be mapped to column ["+column+"] with CQL type ["+cqlType+"]. ");
}
} else
// cdef.type.asCQL3Type() does not include frozen, nor quote, so can do this check for collection.
if (!existingCqlType.equals(cqlType) &&
!cqlType.equals("frozen<"+existingCqlType+">") &&
!(existingCqlType.endsWith("uuid") && cqlType.equals("text")) && // #74 uuid is mapped as keyword
!(existingCqlType.equals("timeuuid") && (cqlType.equals("timestamp") || cqlType.equals("text"))) &&
!(existingCqlType.equals("date") && cqlType.equals("timestamp")) &&
!(existingCqlType.equals("time") && cqlType.equals("bigint"))
) // timeuuid can be mapped to date
throw new IOException("Existing column ["+column+"] type ["+existingCqlType+"] mismatch with inferred type ["+cqlType+"]");
}
}
}
}
}
// add _parent column if necessary. Parent and child documents should have the same partition key.
if (docMapper.parentFieldMapper().active() && docMapper.parentFieldMapper().pkColumns() == null) {
if (newTable) {
// _parent is a JSON array representation of the parent PK.
if (columnsList.length() > 0)
columnsList.append(", ");
columnsList.append("\"_parent\" text");
} else {
try {
String query = String.format(Locale.ROOT, "ALTER TABLE \"%s\".\"%s\" ADD \"_parent\" text", ksName, cfName);
logger.debug(query);
QueryProcessor.process(query, ConsistencyLevel.LOCAL_ONE);
} catch (org.apache.cassandra.exceptions.InvalidRequestException e) {
logger.warn("Cannot alter table {}.{} column _parent with type text", e, ksName, cfName);
}
}
}
if (newTable) {
if (partitionKeyLength == 0) {
// build a default primary key _id text
if (columnsList.length() > 0) columnsList.append(',');
columnsList.append("\"").append(ELASTIC_ID_COLUMN_NAME).append("\" text");
primaryKeyList[0] = ELASTIC_ID_COLUMN_NAME;
primaryKeyLength = 1;
partitionKeyLength = 1;
}
// build the primary key definition
StringBuilder primaryKey = new StringBuilder();
primaryKey.append("(");
for(int i=0; i < primaryKeyLength; i++) {
if (primaryKeyList[i] == null) throw new Exception("Incomplet primary key definition at index "+i);
primaryKey.append("\"").append( primaryKeyList[i] ).append("\"");
if ( i == partitionKeyLength -1) primaryKey.append(")");
if (i+1 < primaryKeyLength ) primaryKey.append(",");
}
String query = String.format(Locale.ROOT, "CREATE TABLE IF NOT EXISTS \"%s\".\"%s\" ( %s, PRIMARY KEY (%s) ) WITH COMMENT='Auto-created by Elassandra'",
ksName, cfName, columnsList.toString(), primaryKey.toString());
logger.debug(query);
QueryProcessor.process(query, ConsistencyLevel.LOCAL_ONE);
}
updateMapping(mapperService.index().getName(), mappingMd);
} catch (Throwable e) {
throw new IOException(e.getMessage(), e);
}
}
@Override
protected void doStart() {
super.doStart();
// add post-applied because 2i shoukd be created/deleted after that cassandra indices have taken the new mapping.
this.addStateApplier(cassandraSecondaryIndicesApplier);
// start a thread for asynchronous CQL schema update, always the last update.
Runnable task = new Runnable() {
@Override
public void run() {
while (true) {
try{
ClusterService.this.metadataToSaveSemaphore.acquire();
MetadataSchemaUpdate metadataSchemaUpdate = ClusterService.this.lastMetadataToSave.getAndSet(null);
if (metadataSchemaUpdate != null) {
if (metadataSchemaUpdate.version < state().metaData().version()) {
logger.trace("Giveup {}.{}.comment obsolete update of metadata.version={} timestamp={}",
ELASTIC_ADMIN_KEYSPACE, ELASTIC_ADMIN_METADATA_TABLE,
metadataSchemaUpdate.version, metadataSchemaUpdate.timestamp);
} else {
logger.trace("Applying {}.{}.comment update with metadata.version={} timestamp={}",
ELASTIC_ADMIN_KEYSPACE, ELASTIC_ADMIN_METADATA_TABLE,
metadataSchemaUpdate.version, metadataSchemaUpdate.timestamp);
// delayed CQL schema update with timestamp = time of cluster state update
CFMetaData cfm = getCFMetaData(ELASTIC_ADMIN_KEYSPACE, ELASTIC_ADMIN_METADATA_TABLE).copy();
TableAttributes attrs = new TableAttributes();
attrs.addProperty(TableParams.Option.COMMENT.toString(), metadataSchemaUpdate.metaDataString);
cfm.params( attrs.asAlteredTableParams(cfm.params) );
MigrationManager.announceColumnFamilyUpdate(cfm, null, false, metadataSchemaUpdate.timestamp);
/*
QueryProcessor.executeOnceInternal(String.format(Locale.ROOT, "ALTER TABLE \"%s\".\"%s\" WITH COMMENT = '%s'",
elasticAdminKeyspaceName, ELASTIC_ADMIN_METADATA_TABLE, metadataSchemaUpdate.metaDataString));
*/
}
}
} catch(Exception e) {
logger.warn("Failed to update CQL schema",e);
}
}
}
};
new Thread(task, "metadataSchemaUpdater").start();
}
public void updateMapping(String ksName, MappingMetaData mapping) {
cassandraSecondaryIndicesApplier.updateMapping( ksName, mapping);
}
public void recoverShard(String index) {
cassandraSecondaryIndicesApplier.recoverShard(index);
}
@Override
protected void publishAndApplyChanges(TaskInputs taskInputs, TaskOutputs taskOutputs) {
ClusterState previousClusterState = taskOutputs.previousClusterState;
ClusterState newClusterState = taskOutputs.newClusterState;
final Discovery.AckListener ackListener = newClusterState.nodes().isLocalNodeElectedMaster() ?
taskOutputs.createAckListener(threadPool, newClusterState) :
null;
// try to update cluster state.
long startTimeNS = System.nanoTime();
boolean presistedMetadata = false;
CassandraDiscovery.MetaDataVersionAckListener metaDataVersionAckListerner = null;
try {
String newClusterStateMetaDataString = MetaData.Builder.toXContent(newClusterState.metaData(), MetaData.CASSANDRA_FORMAT_PARAMS);
String previousClusterStateMetaDataString = MetaData.Builder.toXContent(previousClusterState.metaData(), MetaData.CASSANDRA_FORMAT_PARAMS);
if (!newClusterStateMetaDataString.equals(previousClusterStateMetaDataString) && !newClusterState.blocks().disableStatePersistence() && taskOutputs.doPersistMetadata) {
// update MeteData.version+cluster_uuid
presistedMetadata = true;
newClusterState = ClusterState.builder(newClusterState)
.metaData(MetaData.builder(newClusterState.metaData()).incrementVersion().build())
.incrementVersion()
.build();
// try to persist new metadata in cassandra.
if (presistedMetadata && newClusterState.nodes().getSize() > 1) {
// register the X2 listener before publishing to avoid dead locks !
metaDataVersionAckListerner = this.discovery.new MetaDataVersionAckListener(newClusterState.metaData().version(), ackListener, newClusterState);
}
try {
persistMetaData(previousClusterState.metaData(), newClusterState.metaData(), taskInputs.summary);
publishX2(newClusterState);
} catch (ConcurrentMetaDataUpdateException e) {
if (metaDataVersionAckListerner != null)
metaDataVersionAckListerner.abort();
// should replay the task later when current cluster state will match the expected metadata uuid and version
logger.warn("Cannot overwrite persistent metadata, will resubmit task when metadata.version > {}", previousClusterState.metaData().version());
final long resubmitTimeMillis = System.currentTimeMillis();
ClusterService.this.addListener(new ClusterStateListener() {
@Override
public void clusterChanged(ClusterChangedEvent event) {
if (event.metaDataChanged()) {
final long lostTimeMillis = System.currentTimeMillis() - resubmitTimeMillis;
Priority priority = Priority.URGENT;
TimeValue timeout = TimeValue.timeValueSeconds(30*1000 - lostTimeMillis);
ClusterStateTaskConfig config;
Map<Object, ClusterStateTaskListener> map = new HashMap<Object, ClusterStateTaskListener>();
for (final ClusterServiceTaskBatcher.UpdateTask updateTask : taskInputs.updateTasks) {
map.put( updateTask.task, updateTask.listener);
priority = updateTask.priority();
if (updateTask.task instanceof ClusterStateUpdateTask) {
timeout = TimeValue.timeValueMillis( ((ClusterStateUpdateTask)updateTask.task).timeout().getMillis() - lostTimeMillis);
} else if (updateTask.task instanceof ClusterStateUpdateRequest) {
timeout = TimeValue.timeValueMillis( ((ClusterStateUpdateRequest)updateTask.task).masterNodeTimeout().getMillis() - lostTimeMillis);
}
}
logger.warn("metadata.version={} => resubmit delayed update source={} tasks={} priority={} remaing timeout={}",
ClusterService.this.state().metaData().version(), taskInputs.summary, taskInputs.updateTasks, priority, timeout);
ClusterService.this.submitStateUpdateTasks(taskInputs.summary, map, ClusterStateTaskConfig.build(priority, timeout), taskInputs.executor);
ClusterService.this.removeListener(this); // replay only once.
}
}
});
long currentVersion = readMetaDataVersion(ConsistencyLevel.LOCAL_QUORUM);
if (currentVersion > previousClusterState.metaData().version())
// trigger a metadat update from metadata table if not yet triggered by a gossip change.
this.discovery.updateMetadata("refresh-metadata", currentVersion);
return;
}
}
} catch (Exception e) {
// Unexpected issue => ack with failure.
ackListener.onNodeAck(this.localNode(), e);
TimeValue executionTime = TimeValue.timeValueMillis(Math.max(0, TimeValue.nsecToMSec(System.nanoTime() - startTimeNS)));
if (logger.isTraceEnabled()) {
StringBuilder sb = new StringBuilder("failed to execute cluster state update in ").append(executionTime)
.append(", state:\nversion [")
.append(previousClusterState.version()).
append("], source [").append(taskInputs.summary).append("]\n");
logger.warn(sb.toString(), e);
// TODO resubmit task on next cluster state change
} else {
logger.error("Cassandra issue:", e);
}
if (metaDataVersionAckListerner != null)
metaDataVersionAckListerner.abort();
return;
}
try {
if (logger.isTraceEnabled()) {
StringBuilder sb = new StringBuilder("cluster state updated, source [").append(taskInputs.summary).append("]\n");
sb.append(newClusterState.toString());
logger.trace(sb.toString());
} else if (logger.isDebugEnabled()) {
logger.debug("cluster state updated, version [{}], source [{}]", newClusterState.version(), taskInputs.summary);
}
// update routing table.
newClusterState = ClusterState.builder(newClusterState).routingTable(RoutingTable.build(this, newClusterState)).build();
ClusterChangedEvent clusterChangedEvent = new ClusterChangedEvent(taskInputs.summary, newClusterState, previousClusterState);
// new cluster state, notify all listeners
final DiscoveryNodes.Delta nodesDelta = clusterChangedEvent.nodesDelta();
if (nodesDelta.hasChanges() && logger.isInfoEnabled()) {
String summary = nodesDelta.shortSummary();
if (summary.length() > 0) {
logger.info("{}, reason: {}", summary, taskInputs.summary);
}
}
nodeConnectionsService.connectToNodes(newClusterState.nodes());
logger.debug("applying cluster state version {}", newClusterState.version());
try {
// nothing to do until we actually recover from the gateway or any other block indicates we need to disable persistency
if (clusterChangedEvent.state().blocks().disableStatePersistence() == false && clusterChangedEvent.metaDataChanged()) {
final Settings incomingSettings = clusterChangedEvent.state().metaData().settings();
clusterSettings.applySettings(incomingSettings);
}
} catch (Exception ex) {
logger.warn("failed to apply cluster settings", ex);
}
nodeConnectionsService.disconnectFromNodesExcept(newClusterState.nodes());
// notify highPriorityStateAppliers, including IndicesClusterStateService to start shards and update mapperServices.
if (logger.isTraceEnabled())
logger.trace("notfiy highPriorityStateAppliers={}",highPriorityStateAppliers);
for (ClusterStateApplier applier : this.highPriorityStateAppliers) {
try {
applier.applyClusterState(clusterChangedEvent);
} catch (Exception ex) {
logger.warn("failed to notify ClusterStateListener", ex);
}
}
// update the current cluster state
final ClusterState newClusterState2 = newClusterState;
updateState(css -> newClusterState2);
if (logger.isTraceEnabled())
logger.trace("set local clusterState version={} metadata.version={}", newClusterState.version(), newClusterState.metaData().version());
// notifiy listener, including ElasticSecondaryIndex instances.
Stream.concat(clusterStateListeners.stream(), timeoutClusterStateListeners.stream()).forEach(listener -> {
try {
logger.trace("calling [{}] with change to version [{}] metadata.version=[{}]", listener, newClusterState2.version(), newClusterState2.metaData().version());
listener.clusterChanged(clusterChangedEvent);
} catch (Exception ex) {
logger.warn("failed to notify ClusterStateListener", ex);
}
});
// update cluster state routing table
// TODO: update the routing table only for updated indices.
newClusterState = ClusterState.builder(newClusterState).routingTable(RoutingTable.build(this, newClusterState)).build();
final ClusterState newClusterState3 = newClusterState;
updateState(css -> newClusterState3);
// coordinator node
if (presistedMetadata && metaDataVersionAckListerner != null && newClusterState.nodes().getSize() > 1) {
try {
if (logger.isInfoEnabled())
logger.debug("Waiting MetaData.version = {} for all other alive nodes", newClusterState.metaData().version() );
if (!metaDataVersionAckListerner.await(30L, TimeUnit.SECONDS)) {
logger.warn("Timeout waiting MetaData.version={}", newClusterState.metaData().version());
} else {
logger.debug("Metadata.version={} applied by all alive nodes", newClusterState.metaData().version());
}
} catch (Throwable e) {
final long version = newClusterState.metaData().version();
logger.error((Supplier<?>) () -> new ParameterizedMessage("Interruped while waiting MetaData.version = {}", version), e);
}
}
// notify normalPriorityStateAppliers with the new cluster state,
// including CassandraSecondaryIndicesApplier to create new C* 2i instances when newClusterState is applied by all nodes.
if (logger.isTraceEnabled())
logger.trace("notifiy normalPriorityStateAppliers={} before acknowlegdging listeners",normalPriorityStateAppliers);
for (ClusterStateApplier applier : normalPriorityStateAppliers) {
try {
applier.applyClusterState(clusterChangedEvent);
} catch (Exception ex) {
logger.warn("failed to notify ClusterStateListener", ex);
}
}
// non-coordinator node
if (!presistedMetadata && newClusterState.metaData().version() > previousClusterState.metaData().version()) {
// For non-coordinator nodes, publish in gossip state the applied metadata.uuid and version.
// after mapping change have been applied to secondary index in normalPriorityStateAppliers
publishX2(newClusterState);
}
//manual ack only from the master at the end of the publish
if (newClusterState.nodes().isLocalNodeElectedMaster()) {
try {
ackListener.onNodeAck(newClusterState.nodes().getLocalNode(), null);
} catch (Exception e) {
final DiscoveryNode localNode = newClusterState.nodes().getLocalNode();
logger.debug(
(Supplier<?>) () -> new ParameterizedMessage("error while processing ack for master node [{}]", localNode),
e);
}
}
if (logger.isTraceEnabled())
logger.trace("notify lowPriorityStateAppliers={} after acknowlegdging listeners", lowPriorityStateAppliers);
for (ClusterStateApplier applier : lowPriorityStateAppliers) {
try {
applier.applyClusterState(clusterChangedEvent);
} catch (Exception ex) {
logger.warn("failed to notify ClusterStateListener", ex);
}
}
// notify processed listeners
taskOutputs.processedDifferentClusterState(previousClusterState, newClusterState);
if (newClusterState.nodes().isLocalNodeElectedMaster()) {
try {
taskOutputs.clusterStatePublished(clusterChangedEvent);
} catch (Exception e) {
logger.error(
(Supplier<?>) () -> new ParameterizedMessage(
"exception thrown while notifying executor of new cluster state publication [{}]",
taskInputs.summary),
e);
}
}
if (this.shardStartedBarrier != null) {
shardStartedBarrier.isReadyToIndex(newClusterState);
}
TimeValue executionTime = TimeValue.timeValueMillis(Math.max(0, TimeValue.nsecToMSec(System.nanoTime() - startTimeNS)));
logger.debug("processed [{}]: took {} done applying updated cluster_state (version: {}, uuid: {}, metadata.version: {})", taskInputs.summary, executionTime, newClusterState.version(), newClusterState.stateUUID(), newClusterState.metaData().version());
warnAboutSlowTaskIfNeeded(executionTime, taskInputs.summary);
} catch (Throwable t) {
TimeValue executionTime = TimeValue.timeValueMillis(Math.max(0, TimeValue.nsecToMSec(System.nanoTime() - startTimeNS)));
StringBuilder sb = new StringBuilder("failed to apply updated cluster state in ").append(executionTime).append(":\nversion [").append(newClusterState.version())
.append("], uuid [").append(newClusterState.stateUUID()).append("], source [").append(taskInputs.summary).append("]\n");
sb.append(newClusterState.nodes());
sb.append(newClusterState.routingTable());
sb.append(newClusterState.getRoutingNodes());
logger.warn(sb.toString(), t);
// TODO: do we want to call updateTask.onFailure here?
}
}
public void createSecondaryIndices(final IndexMetaData indexMetaData) throws IOException {
String ksName = indexMetaData.keyspace();
String className = indexMetaData.getSettings().get(IndexMetaData.SETTING_SECONDARY_INDEX_CLASS, this.settings.get(SETTING_CLUSTER_SECONDARY_INDEX_CLASS, defaultSecondaryIndexClass.getName()));
for(ObjectCursor<MappingMetaData> cursor: indexMetaData.getMappings().values()) {
createSecondaryIndex(ksName, cursor.value, className);
}
}
// build secondary indices when shard is started and mapping applied
public void createSecondaryIndex(String ksName, MappingMetaData mapping, String className) throws IOException {
final String cfName = typeToCfName(mapping.type());
final CFMetaData cfm = Schema.instance.getCFMetaData(ksName, cfName);
boolean found = false;
if (cfm != null && cfm.getIndexes() != null) {
for(IndexMetadata indexMetadata : cfm.getIndexes()) {
if (indexMetadata.isCustom() && indexMetadata.options.get(IndexTarget.CUSTOM_INDEX_OPTION_NAME).equals(className)) {
found = true;
break;
}
}
if (!found) {
String indexName = buildIndexName(cfName);
String query = String.format(Locale.ROOT, "CREATE CUSTOM INDEX IF NOT EXISTS \"%s\" ON \"%s\".\"%s\" () USING '%s'",
indexName, ksName, cfName, className);
logger.debug(query);
try {
QueryProcessor.process(query, ConsistencyLevel.LOCAL_ONE);
} catch (Throwable e) {
throw new IOException("Failed to process query=["+query+"]:"+e.getMessage(), e);
}
}
} else {
logger.warn("Cannot create SECONDARY INDEX, [{}.{}] does not exist",ksName, cfName);
}
}
public void dropSecondaryIndices(final IndexMetaData indexMetaData) throws RequestExecutionException {
String ksName = indexMetaData.keyspace();
for(CFMetaData cfMetaData : Schema.instance.getKSMetaData(ksName).tablesAndViews()) {
if (cfMetaData.isCQLTable())
dropSecondaryIndex(cfMetaData);
}
}
public void dropSecondaryIndex(String ksName, String cfName) throws RequestExecutionException {
CFMetaData cfMetaData = Schema.instance.getCFMetaData(ksName, cfName);
if (cfMetaData != null)
dropSecondaryIndex(cfMetaData);
}
public void dropSecondaryIndex(CFMetaData cfMetaData) throws RequestExecutionException {
for(IndexMetadata idx : cfMetaData.getIndexes()) {
if (idx.isCustom()) {
String className = idx.options.get(IndexTarget.CUSTOM_INDEX_OPTION_NAME);
if (className != null && className.endsWith("ElasticSecondaryIndex")) {
logger.debug("DROP INDEX IF EXISTS {}.{}", cfMetaData.ksName, idx.name);
QueryProcessor.process(String.format(Locale.ROOT, "DROP INDEX IF EXISTS \"%s\".\"%s\"",
cfMetaData.ksName, idx.name),
ConsistencyLevel.LOCAL_ONE);
}
}
}
}
public void dropTables(final IndexMetaData indexMetaData) throws RequestExecutionException {
String ksName = indexMetaData.keyspace();
for(ObjectCursor<String> cfName : indexMetaData.getMappings().keys()) {
dropTable(ksName, cfName.value);
}
}
public void dropTable(String ksName, String cfName) throws RequestExecutionException {
CFMetaData cfm = Schema.instance.getCFMetaData(ksName, cfName);
if (cfm != null) {
logger.warn("DROP TABLE IF EXISTS {}.{}", ksName, cfName);
QueryProcessor.process(String.format(Locale.ROOT, "DROP TABLE IF EXISTS \"%s\".\"%s\"", ksName, cfName), ConsistencyLevel.LOCAL_ONE);
}
}
public static String buildIndexName(final String cfName) {
return new StringBuilder("elastic_")
.append(cfName)
.append("_idx").toString();
}
public static String buildIndexName(final String cfName, final String colName) {
return new StringBuilder("elastic_")
.append(cfName).append('_')
.append(colName.replaceAll("\\W+", "_"))
.append("_idx").toString();
}
public static CFMetaData getCFMetaData(final String ksName, final String cfName) throws ActionRequestValidationException {
CFMetaData metadata = Schema.instance.getCFMetaData(ksName, cfName);
if (metadata == null) {
ActionRequestValidationException arve = new ActionRequestValidationException();
arve.addValidationError(ksName+"."+cfName+" table does not exists");;
throw arve;
}
return metadata;
}
public Map<String, GetField> flattenGetField(final String[] fieldFilter, final String path, final Object node, Map<String, GetField> flatFields) {
if ((node instanceof List) || (node instanceof Set)) {
for(Object o : ((Collection)node)) {
flattenGetField(fieldFilter, path, o, flatFields);
}
} else if (node instanceof Map) {
for (String key : ((Map<String,Object>)node).keySet()) {
String fullname = (path.length() > 0) ? path + '.' + key : key;
flattenGetField(fieldFilter, fullname, ((Map<String,Object>)node).get(key), flatFields);
}
} else {
if (fieldFilter != null) {
for (String f : fieldFilter) {
if (path.equals(f)) {
GetField gf = flatFields.get(path);
if (gf == null) {
gf = new GetField(path, ImmutableList.builder().add(node).build());
} else {
gf = new GetField(path, ImmutableList.builder().addAll(gf.getValues()).add(node).build());
}
flatFields.put(path, gf);
break;
}
}
}
}
return flatFields;
}
public Map<String, List<Object>> flattenTree(final Set<String> neededFiedls, final String path, final Object node, Map<String, List<Object>> flatMap) {
if ((node instanceof List) || (node instanceof Set)) {
for(Object o : ((Collection)node)) {
flattenTree(neededFiedls, path, o, flatMap);
}
} else if (node instanceof Map) {
for (String key : ((Map<String,Object>)node).keySet()) {
String fullname = (path.length() > 0) ? path + '.' + key : key;
flattenTree(neededFiedls, fullname, ((Map<String,Object>)node).get(key), flatMap);
}
} else {
if ((neededFiedls == null) || (neededFiedls.contains(path))) {
List<Object> values = (List<Object>) flatMap.get(path);
if (values == null) {
values = new ArrayList<Object>();
flatMap.put(path, values);
}
values.add(node);
}
}
return flatMap;
}
public boolean rowExists(final IndexService indexService, final String type, final String id)
throws InvalidRequestException, RequestExecutionException, RequestValidationException, IOException {
DocPrimaryKey docPk = parseElasticId(indexService, type, id);
return process(ConsistencyLevel.LOCAL_ONE, buildExistsQuery(indexService.mapperService().documentMapper(type), indexService.keyspace(), typeToCfName(type), id), docPk.values).size() > 0;
}
public UntypedResultSet fetchRow(final IndexService indexService, final String type, final String id, final String[] columns, Map<String,ColumnDefinition> columnDefs) throws InvalidRequestException, RequestExecutionException,
RequestValidationException, IOException {
return fetchRow(indexService, type, id, columns, ConsistencyLevel.LOCAL_ONE, columnDefs);
}
/**
* Fetch from the coordinator node.
*/
public UntypedResultSet fetchRow(final IndexService indexService, final String type, final String id, final String[] columns, final ConsistencyLevel cl, Map<String,ColumnDefinition> columnDefs) throws InvalidRequestException,
RequestExecutionException, RequestValidationException, IOException {
DocPrimaryKey docPk = parseElasticId(indexService, type, id);
return fetchRow(indexService, type, docPk, columns, cl, columnDefs);
}
/**
* Fetch from the coordinator node.
*/
public UntypedResultSet fetchRow(final IndexService indexService, final String type, final DocPrimaryKey docPk, final String[] columns, final ConsistencyLevel cl, Map<String,ColumnDefinition> columnDefs) throws InvalidRequestException,
RequestExecutionException, RequestValidationException, IOException {
return process(cl, buildFetchQuery(indexService, type, columns, docPk.isStaticDocument, columnDefs), docPk. values);
}
public Engine.GetResult fetchSourceInternal(final IndexService indexService, String type, String id, Map<String,ColumnDefinition> columnDefs, LongConsumer onRefresh) throws IOException {
long time = System.nanoTime();
DocPrimaryKey docPk = parseElasticId(indexService, type, id);
UntypedResultSet result = fetchRowInternal(indexService, type, docPk, columnDefs.keySet().toArray(new String[columnDefs.size()]), columnDefs);
onRefresh.accept(System.nanoTime() - time);
if (!result.isEmpty()) {
Map<String, Object> sourceMap = rowAsMap(indexService, type, result.one());
BytesReference source = XContentFactory.contentBuilder(XContentType.JSON).map(sourceMap).bytes();
Long timestamp = 0L;
if (sourceMap.get(TimestampFieldMapper.NAME) != null) {
timestamp = (Long) sourceMap.get(TimestampFieldMapper.NAME);
}
Long ttl = 0L;
if (sourceMap.get(TTLFieldMapper.NAME) != null) {
ttl = (Long) sourceMap.get(TTLFieldMapper.NAME);
}
// build termVector form the Cassandra doc.
return new Engine.GetResult(true, 1L, null, null);
}
return Engine.GetResult.NOT_EXISTS;
}
public UntypedResultSet fetchRowInternal(final IndexService indexService, final String cfName, final String id, final String[] columns, Map<String,ColumnDefinition> columnDefs) throws ConfigurationException, IOException {
DocPrimaryKey docPk = parseElasticId(indexService, cfName, id);
return fetchRowInternal(indexService, cfName, columns, docPk.values, docPk.isStaticDocument, columnDefs);
}
public UntypedResultSet fetchRowInternal(final IndexService indexService, final String cfName, final DocPrimaryKey docPk, final String[] columns, Map<String,ColumnDefinition> columnDefs) throws ConfigurationException, IOException {
return fetchRowInternal(indexService, cfName, columns, docPk.values, docPk.isStaticDocument, columnDefs);
}
public UntypedResultSet fetchRowInternal(final IndexService indexService, final String cfName, final String[] columns, final Object[] pkColumns, boolean forStaticDocument, Map<String,ColumnDefinition> columnDefs) throws ConfigurationException, IOException, IndexNotFoundException {
return QueryProcessor.executeInternal(buildFetchQuery(indexService, cfName, columns, forStaticDocument, columnDefs), pkColumns);
}
private String regularColumn(final IndexService indexService, final String type) throws IOException {
if (indexService != null) {
DocumentMapper docMapper = indexService.mapperService().documentMapper(type);
if (docMapper != null) {
for(FieldMapper fieldMapper : docMapper.mappers()) {
if (fieldMapper instanceof MetadataFieldMapper)
continue;
if (fieldMapper.cqlPrimaryKeyOrder() == -1 && !fieldMapper.cqlStaticColumn() && fieldMapper.cqlCollection() == Mapper.CqlCollection.SINGLETON) {
return fieldMapper.name();
}
}
}
}
if (logger.isDebugEnabled())
logger.debug("no regular columns for index=[{}] type=[{}]", indexService.index().getName(), type);
return null;
}
public String buildFetchQuery(final IndexService indexService, final String type, String cqlProjection, boolean forStaticDocument)
throws IndexNotFoundException, IOException
{
DocumentMapper docMapper = indexService.mapperService().documentMapper(type);
String cfName = typeToCfName(type);
DocumentMapper.CqlFragments cqlFragment = docMapper.getCqlFragments();
StringBuilder query = new StringBuilder();
final String SELECT_ = "SELECT ";
query.append("SELECT ")
.append(cqlProjection)
.append(" FROM \"").append(indexService.keyspace()).append("\".\"").append(cfName)
.append("\" WHERE ").append((forStaticDocument) ? cqlFragment.ptWhere : cqlFragment.pkWhere )
.append(" LIMIT 1");
return query.toString();
}
public String buildFetchQuery(final IndexService indexService, final String type, final String[] requiredColumns, boolean forStaticDocument, Map<String, ColumnDefinition> columnDefs)
throws IndexNotFoundException, IOException
{
DocumentMapper docMapper = indexService.mapperService().documentMapper(type);
String cfName = typeToCfName(type);
CFMetaData metadata = getCFMetaData(indexService.keyspace(), cfName);
DocumentMapper.CqlFragments cqlFragment = docMapper.getCqlFragments();
String regularColumn = null;
StringBuilder query = new StringBuilder();
final String SELECT_ = "SELECT ";
query.append(SELECT_);
for (String c : requiredColumns) {
switch(c){
case TokenFieldMapper.NAME:
query.append(query.length() > 7 ? ',':' ')
.append("token(")
.append(cqlFragment.ptCols)
.append(") as \"_token\"");
break;
case RoutingFieldMapper.NAME:
query.append(query.length() > 7 ? ',':' ')
.append( (metadata.partitionKeyColumns().size() > 1) ? "toJsonArray(" : "toString(" )
.append(cqlFragment.ptCols)
.append(") as \"_routing\"");
break;
case TTLFieldMapper.NAME:
if (regularColumn == null)
regularColumn = regularColumn(indexService, cfName);
if (regularColumn != null)
query.append(query.length() > 7 ? ',':' ').append("TTL(").append(regularColumn).append(") as \"_ttl\"");
break;
case TimestampFieldMapper.NAME:
if (regularColumn == null)
regularColumn = regularColumn(indexService, cfName);
if (regularColumn != null)
query.append(query.length() > 7 ? ',':' ').append("WRITETIME(").append(regularColumn).append(") as \"_timestamp\"");
break;
case ParentFieldMapper.NAME:
ParentFieldMapper parentMapper = docMapper.parentFieldMapper();
if (parentMapper.active()) {
query.append(query.length() > 7 ? ',':' ');
if (parentMapper.pkColumns() == null) {
// default column name for _parent should be string.
query.append("\"_parent\"");
} else {
query.append( (parentMapper.pkColumns().indexOf(',') > 0) ? "toJsonArray(" : "toString(")
.append(parentMapper.pkColumns())
.append(") as \"_parent\"");
}
}
break;
case NodeFieldMapper.NAME:
// nothing to add.
break;
default:
ColumnDefinition cd = columnDefs.get(c);
if (cd != null && (cd.isPartitionKey() || cd.isStatic() || !forStaticDocument)) {
query.append(query.length() > SELECT_.length() ? ',':' ').append("\"").append(c).append("\"");
}
}
}
if (query.length() == SELECT_.length()) {
// no column match or requiredColumn is empty, add _id to avoid CQL syntax error...
query.append("\"_id\"");
}
query.append(" FROM \"").append(indexService.keyspace()).append("\".\"").append(cfName)
.append("\" WHERE ").append((forStaticDocument) ? cqlFragment.ptWhere : cqlFragment.pkWhere )
.append(" LIMIT 1");
return query.toString();
}
public static String buildDeleteQuery(final DocumentMapper docMapper, final String ksName, final String cfName, final String id) {
return "DELETE FROM \""+ksName+"\".\""+cfName+"\" WHERE "+ docMapper.getCqlFragments().pkWhere;
}
public static String buildExistsQuery(final DocumentMapper docMapper, final String ksName, final String cfName, final String id) {
return "SELECT "+docMapper.getCqlFragments().pkCols+" FROM \""+ksName+"\".\""+cfName+"\" WHERE "+ docMapper.getCqlFragments().pkWhere;
}
public void deleteRow(final IndexService indexService, final String type, final String id, final ConsistencyLevel cl) throws InvalidRequestException, RequestExecutionException, RequestValidationException,
IOException {
String cfName = typeToCfName(type);
DocumentMapper docMapper = indexService.mapperService().documentMapper(type);
process(cl, buildDeleteQuery(docMapper, indexService.keyspace(), cfName, id), parseElasticId(indexService, type, id).values);
}
public Map<String, Object> rowAsMap(final IndexService indexService, final String type, UntypedResultSet.Row row) throws IOException {
Map<String, Object> mapObject = new HashMap<String, Object>();
rowAsMap(indexService, type, row, mapObject);
return mapObject;
}
public int rowAsMap(final IndexService indexService, final String type, UntypedResultSet.Row row, Map<String, Object> mapObject) throws IOException {
Object[] values = rowAsArray(indexService, type, row);
int i=0;
int j=0;
for(ColumnSpecification colSpec: row.getColumns()) {
if (values[i] != null && !IdFieldMapper.NAME.equals(colSpec.name.toString())) {
mapObject.put(colSpec.name.toString(), values[i]);
j++;
}
i++;
}
return j;
}
public Object[] rowAsArray(final IndexService indexService, final String type, UntypedResultSet.Row row) throws IOException {
return rowAsArray(indexService, type, row, false);
}
private Object value(FieldMapper fieldMapper, Object rowValue, boolean valueForSearch) {
if (fieldMapper != null) {
final MappedFieldType fieldType = fieldMapper.fieldType();
return (valueForSearch) ? fieldType.valueForDisplay( rowValue ) : fieldType.cqlValue( rowValue );
} else {
return rowValue;
}
}
// TODO: return raw values if no mapper found.
public Object[] rowAsArray(final IndexService indexService, final String type, UntypedResultSet.Row row, boolean valueForSearch) throws IOException {
final Object values[] = new Object[row.getColumns().size()];
final DocumentMapper documentMapper = indexService.mapperService().documentMapper(type);
final DocumentFieldMappers docFieldMappers = documentMapper.mappers();
int i = 0;
for (ColumnSpecification colSpec : row.getColumns()) {
String columnName = colSpec.name.toString();
CQL3Type cql3Type = colSpec.type.asCQL3Type();
if (!row.has(columnName) || ByteBufferUtil.EMPTY_BYTE_BUFFER.equals(row.getBlob(columnName)) ) {
values[i++] = null;
continue;
}
if (cql3Type instanceof CQL3Type.Native) {
final FieldMapper fieldMapper = docFieldMappers.smartNameFieldMapper(columnName);
switch ((CQL3Type.Native) cql3Type) {
case ASCII:
case TEXT:
case VARCHAR:
values[i] = row.getString(columnName);
if (values[i] != null && fieldMapper == null) {
ObjectMapper objectMapper = documentMapper.objectMappers().get(columnName);
if (objectMapper != null && !objectMapper.isEnabled()) {
// parse text as JSON Map (not enabled object)
values[i] = FBUtilities.fromJsonMap(row.getString(columnName));
}
}
break;
case TIMEUUID:
if (fieldMapper instanceof DateFieldMapper) {
// Timeuuid can be mapped to date rather than keyword.
values[i] = UUIDGen.unixTimestamp(row.getUUID(columnName));
break;
}
values[i] = row.getUUID(columnName).toString();
break;
case UUID:
values[i] = row.getUUID(columnName).toString();
break;
case TIMESTAMP:
values[i] = value(fieldMapper, row.getTimestamp(columnName).getTime(), valueForSearch);
break;
case DATE:
values[i] = value(fieldMapper, row.getInt(columnName)*86400L*1000L, valueForSearch);
break;
case TIME:
values[i] = value(fieldMapper, row.getLong(columnName), valueForSearch);
break;
case INT:
values[i] = value(fieldMapper, row.getInt(columnName), valueForSearch);
break;
case SMALLINT:
values[i] = value(fieldMapper, row.getShort(columnName), valueForSearch);
break;
case TINYINT:
values[i] = value(fieldMapper, row.getByte(columnName), valueForSearch);
break;
case BIGINT:
values[i] = value(fieldMapper, row.getLong(columnName), valueForSearch);
break;
case DOUBLE:
values[i] = value(fieldMapper, row.getDouble(columnName), valueForSearch);
break;
case FLOAT:
values[i] = value(fieldMapper, row.getFloat(columnName), valueForSearch);
break;
case BLOB:
values[i] = value(fieldMapper,
row.getBlob(columnName),
valueForSearch);
break;
case BOOLEAN:
values[i] = value(fieldMapper, row.getBoolean(columnName), valueForSearch);
break;
case COUNTER:
logger.warn("Ignoring unsupported counter {} for column {}", cql3Type, columnName);
break;
case INET:
values[i] = value(fieldMapper, row.getInetAddress(columnName), valueForSearch);
break;
default:
logger.error("Ignoring unsupported type {} for column {}", cql3Type, columnName);
}
} else if (cql3Type.isCollection()) {
AbstractType<?> elementType;
switch (((CollectionType<?>) colSpec.type).kind) {
case LIST:
List list;
elementType = ((ListType<?>) colSpec.type).getElementsType();
if (elementType instanceof UserType) {
final ObjectMapper objectMapper = documentMapper.objectMappers().get(columnName);
final List<ByteBuffer> lbb = row.getList(columnName, BytesType.instance);
list = new ArrayList(lbb.size());
for (ByteBuffer bb : lbb) {
list.add(deserialize(elementType, bb, objectMapper));
}
} else {
final FieldMapper fieldMapper = docFieldMappers.smartNameFieldMapper(columnName);
final List list2 = row.getList(colSpec.name.toString(), elementType);
list = new ArrayList(list2.size());
for(Object v : list2) {
list.add(value(fieldMapper, v, valueForSearch));
}
}
values[i] = (list.size() == 1) ? list.get(0) : list;
break;
case SET :
Set set;
elementType = ((SetType<?>) colSpec.type).getElementsType();
if (elementType instanceof UserType) {
final ObjectMapper objectMapper = documentMapper.objectMappers().get(columnName);
final Set<ByteBuffer> lbb = row.getSet(columnName, BytesType.instance);
set = new HashSet(lbb.size());
for (ByteBuffer bb : lbb) {
set.add(deserialize(elementType, bb, objectMapper));
}
} else {
final FieldMapper fieldMapper = docFieldMappers.smartNameFieldMapper(columnName);
final Set set2 = row.getSet(columnName, elementType);
set = new HashSet(set2.size());
for(Object v : set2) {
set.add( value(fieldMapper, v, valueForSearch) );
}
}
values[i] = (set.size() == 1) ? set.iterator().next() : set;
break;
case MAP :
Map map;
if (((MapType<?,?>) colSpec.type).getKeysType().asCQL3Type() != CQL3Type.Native.TEXT) {
throw new IOException("Only support map<text,?>, bad type for column "+columnName);
}
UTF8Type keyType = (UTF8Type) ((MapType<?,?>) colSpec.type).getKeysType();
elementType = ((MapType<?,?>) colSpec.type).getValuesType();
final ObjectMapper objectMapper = documentMapper.objectMappers().get(columnName);
if (elementType instanceof UserType) {
final Map<String, ByteBuffer> lbb = row.getMap(columnName, keyType, BytesType.instance);
map = new HashMap<String , Map<String, Object>>(lbb.size());
for(String key : lbb.keySet()) {
map.put(key, deserialize(elementType, lbb.get(key), objectMapper.getMapper(key)));
}
} else {
Map<String,Object> map2 = (Map<String,Object>) row.getMap(columnName, keyType, elementType);
map = new HashMap<String, Object>(map2.size());
for(String key : map2.keySet()) {
FieldMapper subMapper = (FieldMapper)objectMapper.getMapper(key);
map.put(key, value(subMapper, map2.get(key), valueForSearch) );
}
}
values[i] = map;
break;
}
} else if (colSpec.type instanceof UserType) {
ByteBuffer bb = row.getBytes(columnName);
values[i] = deserialize(colSpec.type, bb, documentMapper.objectMappers().get(columnName));
} else if (cql3Type instanceof CQL3Type.Custom) {
logger.warn("CQL3.Custum type not supported for column "+columnName);
}
i++;
}
return values;
}
public static class BlockingActionListener implements ActionListener<ClusterStateUpdateResponse> {
private final CountDownLatch latch = new CountDownLatch(1);
private volatile Throwable error = null;
public void waitForUpdate(TimeValue timeValue) throws Exception {
if (timeValue != null && timeValue.millis() > 0) {
if (!latch.await(timeValue.millis(), TimeUnit.MILLISECONDS)) {
throw new ElasticsearchTimeoutException("blocking update timeout");
}
} else {
latch.await();
}
if (error != null)
throw new RuntimeException(error);
}
@Override
public void onResponse(ClusterStateUpdateResponse response) {
latch.countDown();
}
@Override
public void onFailure(Exception e) {
error = e;
latch.countDown();
}
}
/**
* CQL schema update must be asynchronous when triggered by a new dynamic field (see #91)
* @param indexService
* @param type
* @param source
* @throws Exception
*/
public void blockingMappingUpdate(IndexService indexService, String type, String source) throws Exception {
TimeValue timeout = settings.getAsTime(SETTING_CLUSTER_MAPPING_UPDATE_TIMEOUT, TimeValue.timeValueSeconds(Integer.getInteger(SETTING_SYSTEM_MAPPING_UPDATE_TIMEOUT, 30)));
BlockingActionListener mappingUpdateListener = new BlockingActionListener();
MetaDataMappingService metaDataMappingService = ElassandraDaemon.injector().getInstance(MetaDataMappingService.class);
PutMappingClusterStateUpdateRequest putRequest = new PutMappingClusterStateUpdateRequest()
.indices(new org.elasticsearch.index.Index[] {indexService.index()})
.type(type)
.source(source)
.ackTimeout(timeout);
metaDataMappingService.putMapping(putRequest, mappingUpdateListener);
mappingUpdateListener.waitForUpdate(timeout);
}
public void updateDocument(final IndicesService indicesService, final IndexRequest request, final IndexMetaData indexMetaData) throws Exception {
upsertDocument(indicesService, request, indexMetaData, true);
}
public void insertDocument(final IndicesService indicesService, final IndexRequest request, final IndexMetaData indexMetaData) throws Exception {
upsertDocument(indicesService, request, indexMetaData, false);
}
private void upsertDocument(final IndicesService indicesService, final IndexRequest request, final IndexMetaData indexMetaData, boolean updateOperation) throws Exception {
final IndexService indexService = indicesService.indexService(indexMetaData.getIndex());
final IndexShard indexShard = indexService.getShard(0);
final SourceToParse sourceToParse = SourceToParse.source(SourceToParse.Origin.PRIMARY, request.index(), request.type(), request.id(), request.source(), XContentType.JSON);
if (request.routing() != null)
sourceToParse.routing(request.routing());
if (request.parent() != null)
sourceToParse.parent(request.parent());
if (request.timestamp() != null)
sourceToParse.timestamp(request.timestamp());
if (request.ttl() != null)
sourceToParse.ttl(request.ttl());
final String keyspaceName = indexMetaData.keyspace();
final String cfName = typeToCfName(request.type());
final Engine.Index operation = indexShard.prepareIndexOnPrimary(sourceToParse, request.version(), request.versionType(), request.getAutoGeneratedTimestamp(), false);
final Mapping update = operation.parsedDoc().dynamicMappingsUpdate();
final boolean dynamicMappingEnable = indexService.mapperService().dynamic();
if (update != null && dynamicMappingEnable) {
if (logger.isDebugEnabled())
logger.debug("Document source={} require a blocking mapping update of [{}]", request.sourceAsMap(), indexService.index().getName());
// blocking Elasticsearch mapping update (required to update cassandra schema before inserting a row, this is the cost of dynamic mapping)
blockingMappingUpdate(indexService, request.type(), update.toString());
}
// get the docMapper after a potential mapping update
final DocumentMapper docMapper = indexShard.mapperService().documentMapperWithAutoCreate(request.type()).getDocumentMapper();
// insert document into cassandra keyspace=index, table = type
final Map<String, Object> sourceMap = request.sourceAsMap();
final Map<String, ObjectMapper> objectMappers = docMapper.objectMappers();
final DocumentFieldMappers fieldMappers = docMapper.mappers();
Long timestamp = null;
if (docMapper.timestampFieldMapper().enabled() && request.timestamp() != null) {
timestamp = docMapper.timestampFieldMapper().fieldType().cqlValue(request.timestamp());
}
if (logger.isTraceEnabled())
logger.trace("Insert metadata.version={} index=[{}] table=[{}] id=[{}] source={} consistency={} ttl={}",
state().metaData().version(),
indexService.index().getName(), cfName, request.id(), sourceMap,
request.waitForActiveShards().toCassandraConsistencyLevel(), request.ttl());
final CFMetaData metadata = getCFMetaData(keyspaceName, cfName);
String id = request.id();
Map<String, ByteBuffer> map = new HashMap<String, ByteBuffer>();
if (request.parent() != null)
sourceMap.put(ParentFieldMapper.NAME, request.parent());
// normalize the _id and may find some column value in _id.
// if the provided columns does not contains all the primary key columns, parse the _id to populate the columns in map.
parseElasticId(indexService, cfName, request.id(), sourceMap);
// workaround because ParentFieldMapper.value() and UidFieldMapper.value() create an Uid.
if (sourceMap.get(ParentFieldMapper.NAME) != null && ((String)sourceMap.get(ParentFieldMapper.NAME)).indexOf(Uid.DELIMITER) < 0) {
sourceMap.put(ParentFieldMapper.NAME, request.type() + Uid.DELIMITER + sourceMap.get(ParentFieldMapper.NAME));
}
if (docMapper.sourceMapper().enabled()) {
sourceMap.put(SourceFieldMapper.NAME, request.source());
}
for (String field : sourceMap.keySet()) {
FieldMapper fieldMapper = field.startsWith(ParentFieldMapper.NAME) ? // workaround for _parent#<join_type>
docMapper.parentFieldMapper() : fieldMappers.getMapper( field );
Mapper mapper = (fieldMapper != null) ? fieldMapper : objectMappers.get(field);
ByteBuffer colName;
if (mapper == null) {
if (dynamicMappingEnable)
throw new MapperException("Unmapped field ["+field+"]");
colName = ByteBufferUtil.bytes(field);
} else {
colName = mapper.cqlName(); // cached ByteBuffer column name.
}
final ColumnDefinition cd = metadata.getColumnDefinition(colName);
if (cd != null) {
// we got a CQL column.
Object fieldValue = sourceMap.get(field);
try {
if (fieldValue == null) {
if (cd.type.isCollection()) {
switch (((CollectionType<?>)cd.type).kind) {
case LIST :
case SET :
map.put(field, CollectionSerializer.pack(Collections.emptyList(), 0, ProtocolVersion.CURRENT));
break;
case MAP :
break;
}
} else {
map.put(field, null);
}
continue;
}
if (mapper != null && mapper.cqlCollection().equals(CqlCollection.SINGLETON) && (fieldValue instanceof Collection)) {
throw new MapperParsingException("field " + fieldMapper.name() + " should be a single value");
}
// hack to store percolate query as a string while mapper is an object mapper.
if (metadata.cfName.equals("_percolator") && field.equals("query")) {
if (cd.type.isCollection()) {
switch (((CollectionType<?>)cd.type).kind) {
case LIST :
if ( ((ListType)cd.type).getElementsType().asCQL3Type().equals(CQL3Type.Native.TEXT) && !(fieldValue instanceof String)) {
// opaque list of objects serialized to JSON text
fieldValue = Collections.singletonList( stringify(fieldValue) );
}
break;
case SET :
if ( ((SetType)cd.type).getElementsType().asCQL3Type().equals(CQL3Type.Native.TEXT) && !(fieldValue instanceof String)) {
// opaque set of objects serialized to JSON text
fieldValue = Collections.singleton( stringify(fieldValue) );
}
break;
}
} else {
if (cd.type.asCQL3Type().equals(CQL3Type.Native.TEXT) && !(fieldValue instanceof String)) {
// opaque singleton object serialized to JSON text
fieldValue = stringify(fieldValue);
}
}
}
map.put(field, serialize(request.index(), cfName, cd.type, field, fieldValue, mapper));
} catch (Exception e) {
logger.error("[{}].[{}] failed to parse field {}={}", e, request.index(), cfName, field, fieldValue );
throw e;
}
}
}
String query;
ByteBuffer[] values;
if (request.opType() == DocWriteRequest.OpType.CREATE) {
values = new ByteBuffer[map.size()];
query = buildInsertQuery(keyspaceName, cfName, map, id,
true,
(request.ttl() != null) ? request.ttl().getSeconds() : null, // ttl
timestamp,
values, 0);
final boolean applied = processWriteConditional(request.waitForActiveShards().toCassandraConsistencyLevel(), ConsistencyLevel.LOCAL_SERIAL, query, (Object[])values);
if (!applied)
throw new VersionConflictEngineException(indexShard.shardId(), cfName, request.id(), "PAXOS insert failed, document already exists");
} else {
// set empty top-level fields to null to overwrite existing columns.
for(FieldMapper m : fieldMappers) {
String fullname = m.name();
if (map.get(fullname) == null && !fullname.startsWith("_") && fullname.indexOf('.') == -1 && metadata.getColumnDefinition(m.cqlName()) != null)
map.put(fullname, null);
}
for(String m : objectMappers.keySet()) {
if (map.get(m) == null && m.indexOf('.') == -1 && metadata.getColumnDefinition(objectMappers.get(m).cqlName()) != null)
map.put(m, null);
}
values = new ByteBuffer[map.size()];
query = buildInsertQuery(keyspaceName, cfName, map, id,
false,
(request.ttl() != null) ? request.ttl().getSeconds() : null,
timestamp,
values, 0);
process(request.waitForActiveShards().toCassandraConsistencyLevel(), query, (Object[])values);
}
}
public String buildInsertQuery(final String ksName, final String cfName, Map<String, ByteBuffer> map, String id, final boolean ifNotExists, final Long ttl,
final Long writetime, ByteBuffer[] values, int valuesOffset) throws Exception {
final StringBuilder questionsMarks = new StringBuilder();
final StringBuilder columnNames = new StringBuilder();
int i=0;
for (Entry<String,ByteBuffer> entry : map.entrySet()) {
if (entry.getKey().equals(TokenFieldMapper.NAME))
continue;
if (columnNames.length() > 0) {
columnNames.append(',');
questionsMarks.append(',');
}
columnNames.append("\"").append(entry.getKey()).append("\"");
questionsMarks.append('?');
values[valuesOffset + i] = entry.getValue();
i++;
}
final StringBuilder query = new StringBuilder();
query.append("INSERT INTO \"").append(ksName).append("\".\"").append(cfName)
.append("\" (").append(columnNames.toString()).append(") VALUES (").append(questionsMarks.toString()).append(") ");
if (ifNotExists) query.append("IF NOT EXISTS ");
if (ttl != null && ttl > 0 || writetime != null) query.append("USING ");
if (ttl != null && ttl > 0) query.append("TTL ").append(Long.toString(ttl));
if (ttl != null &&ttl > 0 && writetime != null) query.append(" AND ");
if (writetime != null) query.append("TIMESTAMP ").append(Long.toString(writetime*1000));
return query.toString();
}
public BytesReference source(IndexService indexService, DocumentMapper docMapper, Map sourceAsMap, Uid uid) throws JsonParseException, JsonMappingException, IOException {
if (docMapper.sourceMapper().enabled()) {
// retreive from _source columns stored as blob in cassandra if available.
ByteBuffer bb = (ByteBuffer) sourceAsMap.get(SourceFieldMapper.NAME);
if (bb != null)
return new BytesArray(bb.array(), bb.position(), bb.limit() - bb.position());
}
// rebuild _source from all cassandra columns.
XContentBuilder builder = buildDocument(docMapper, sourceAsMap, true, isStaticDocument(indexService, uid));
builder.humanReadable(true);
return builder.bytes();
}
public BytesReference source(IndexService indexService, DocumentMapper docMapper, Map sourceAsMap, String id) throws JsonParseException, JsonMappingException, IOException {
return source( indexService, docMapper, sourceAsMap, new Uid(docMapper.type(), id));
}
public DocPrimaryKey parseElasticId(final IndexService indexService, final String type, final String id) throws IOException {
return parseElasticId(indexService, type, id, null);
}
/**
* Parse elastic _id (a value or a JSON array) to build a DocPrimaryKey or populate map.
*/
public DocPrimaryKey parseElasticId(final IndexService indexService, final String type, final String id, Map<String, Object> map) throws JsonParseException, JsonMappingException, IOException {
String ksName = indexService.keyspace();
String cfName = typeToCfName(type);
CFMetaData metadata = getCFMetaData(ksName, cfName);
List<ColumnDefinition> partitionColumns = metadata.partitionKeyColumns();
List<ColumnDefinition> clusteringColumns = metadata.clusteringColumns();
int ptLen = partitionColumns.size();
if (id.startsWith("[") && id.endsWith("]")) {
// _id is JSON array of values.
org.codehaus.jackson.map.ObjectMapper jsonMapper = new org.codehaus.jackson.map.ObjectMapper();
Object[] elements = jsonMapper.readValue(id, Object[].class);
Object[] values = (map != null) ? null : new Object[elements.length];
String[] names = (map != null) ? null : new String[elements.length];
if (elements.length > ptLen + clusteringColumns.size())
throw new JsonMappingException("_id="+id+" longer than the primary key size="+(ptLen+clusteringColumns.size()) );
for(int i=0; i < elements.length; i++) {
ColumnDefinition cd = (i < ptLen) ? partitionColumns.get(i) : clusteringColumns.get(i - ptLen);
AbstractType<?> atype = cd.type;
if (map == null) {
names[i] = cd.name.toString();
values[i] = atype.compose( fromString(atype, elements[i].toString()) );
} else {
map.put(cd.name.toString(), atype.compose( fromString(atype, elements[i].toString()) ) );
}
}
return (map != null) ? null : new DocPrimaryKey(names, values, (clusteringColumns.size() > 0 && elements.length == partitionColumns.size()) ) ;
} else {
// _id is a single columns, parse its value.
AbstractType<?> atype = partitionColumns.get(0).type;
if (map == null) {
return new DocPrimaryKey( new String[] { partitionColumns.get(0).name.toString() } , new Object[] { atype.compose(fromString(atype, id)) }, clusteringColumns.size() != 0);
} else {
map.put(partitionColumns.get(0).name.toString(), atype.compose( fromString(atype, id) ) );
return null;
}
}
}
public DocPrimaryKey parseElasticRouting(final IndexService indexService, final String type, final String routing) throws JsonParseException, JsonMappingException, IOException {
String ksName = indexService.keyspace();
String cfName = typeToCfName(type);
CFMetaData metadata = getCFMetaData(ksName, cfName);
List<ColumnDefinition> partitionColumns = metadata.partitionKeyColumns();
int ptLen = partitionColumns.size();
if (routing.startsWith("[") && routing.endsWith("]")) {
// _routing is JSON array of values.
org.codehaus.jackson.map.ObjectMapper jsonMapper = new org.codehaus.jackson.map.ObjectMapper();
Object[] elements = jsonMapper.readValue(routing, Object[].class);
Object[] values = new Object[elements.length];
String[] names = new String[elements.length];
if (elements.length != ptLen)
throw new JsonMappingException("_routing="+routing+" does not match the partition key size="+ptLen);
for(int i=0; i < elements.length; i++) {
ColumnDefinition cd = partitionColumns.get(i);
AbstractType<?> atype = cd.type;
names[i] = cd.name.toString();
values[i] = atype.compose( fromString(atype, elements[i].toString()) );
i++;
}
return new DocPrimaryKey(names, values) ;
} else {
// _id is a single columns, parse its value.
AbstractType<?> atype = partitionColumns.get(0).type;
return new DocPrimaryKey( new String[] { partitionColumns.get(0).name.toString() } , new Object[] { atype.compose( fromString(atype, routing) ) });
}
}
public Token getToken(final IndexService indexService, final String type, final String routing) throws JsonParseException, JsonMappingException, IOException {
DocPrimaryKey pk = parseElasticRouting(indexService, type, routing);
CFMetaData cfm = getCFMetaData(indexService.keyspace(), type);
CBuilder builder = CBuilder.create(cfm.getKeyValidatorAsClusteringComparator());
for (int i = 0; i < cfm.partitionKeyColumns().size(); i++)
builder.add(pk.values[i]);
return cfm.partitioner.getToken(CFMetaData.serializePartitionKey(builder.build()));
}
public Set<Token> getTokens(final IndexService indexService, final String[] types, final String routing) throws JsonParseException, JsonMappingException, IOException {
Set<Token> tokens = new HashSet<Token>();
if (types != null && types.length > 0) {
for(String type : types)
tokens.add(getToken(indexService, type, routing));
}
return tokens;
}
public boolean isStaticDocument(final IndexService indexService, Uid uid) throws JsonParseException, JsonMappingException, IOException {
CFMetaData metadata = getCFMetaData(indexService.keyspace(), typeToCfName(uid.type()));
String id = uid.id();
if (id.startsWith("[") && id.endsWith("]")) {
org.codehaus.jackson.map.ObjectMapper jsonMapper = new org.codehaus.jackson.map.ObjectMapper();
Object[] elements = jsonMapper.readValue(id, Object[].class);
return metadata.clusteringColumns().size() > 0 && elements.length == metadata.partitionKeyColumns().size();
} else {
return metadata.clusteringColumns().size() != 0;
}
}
@SuppressForbidden(reason = "toUpperCase() for consistency level")
public static ConsistencyLevel consistencyLevelFromString(String value) {
switch(value.toUpperCase(Locale.ROOT)) {
case "ANY": return ConsistencyLevel.ANY;
case "ONE": return ConsistencyLevel.ONE;
case "TWO": return ConsistencyLevel.TWO;
case "THREE": return ConsistencyLevel.THREE;
case "QUORUM": return ConsistencyLevel.QUORUM;
case "ALL": return ConsistencyLevel.ALL;
case "LOCAL_QUORUM": return ConsistencyLevel.LOCAL_QUORUM;
case "EACH_QUORUM": return ConsistencyLevel.EACH_QUORUM;
case "SERIAL": return ConsistencyLevel.SERIAL;
case "LOCAL_SERIAL": return ConsistencyLevel.LOCAL_SERIAL;
case "LOCAL_ONE": return ConsistencyLevel.LOCAL_ONE;
default :
throw new IllegalArgumentException("No write consistency match [" + value + "]");
}
}
public boolean isDatacenterGroupMember(InetAddress endpoint) {
String endpointDc = DatabaseDescriptor.getEndpointSnitch().getDatacenter(endpoint);
KeyspaceMetadata elasticAdminMetadata = Schema.instance.getKSMetaData(this.elasticAdminKeyspaceName);
if (elasticAdminMetadata != null) {
ReplicationParams replicationParams = elasticAdminMetadata.params.replication;
if (replicationParams.klass == NetworkTopologyStrategy.class && replicationParams.options.get(endpointDc) != null) {
return true;
}
}
return false;
}
public class MetadataSchemaUpdate {
long version;
long timestamp;
String metaDataString;
MetadataSchemaUpdate(String metaDataString, long version) {
this.metaDataString = metaDataString;
this.version = version;
this.timestamp = FBUtilities.timestampMicros();
}
}
public void writeMetaDataAsComment(MetaData metaData) throws ConfigurationException, IOException {
writeMetaDataAsComment( MetaData.Builder.toXContent(metaData, MetaData.CASSANDRA_FORMAT_PARAMS), metaData.version());
}
public void writeMetaDataAsComment(String metaDataString, long version) throws ConfigurationException, IOException {
// Issue #91, update C* schema asynchronously to avoid inter-locking with map column as nested object.
logger.trace("Submit asynchronous CQL schema update for metadata={}", metaDataString);
this.lastMetadataToSave.set(new MetadataSchemaUpdate(metaDataString, version));
this.metadataToSaveSemaphore.release();
}
/**
* Should only be used after a SCHEMA change.
*/
public MetaData readMetaDataAsComment() throws NoPersistedMetaDataException {
try {
String query = String.format(Locale.ROOT, "SELECT comment FROM system_schema.tables WHERE keyspace_name='%s' AND table_name='%s'",
this.elasticAdminKeyspaceName, ELASTIC_ADMIN_METADATA_TABLE);
UntypedResultSet result = QueryProcessor.executeInternal(query);
if (result.isEmpty())
throw new NoPersistedMetaDataException("Failed to read comment from "+elasticAdminKeyspaceName+"+"+ELASTIC_ADMIN_METADATA_TABLE);
String metadataString = result.one().getString("comment");
logger.debug("Recover metadata from {}.{} = {}", elasticAdminKeyspaceName, ELASTIC_ADMIN_METADATA_TABLE, metadataString);
return parseMetaDataString( metadataString );
} catch (RequestValidationException | RequestExecutionException e) {
throw new NoPersistedMetaDataException("Failed to read comment from "+elasticAdminKeyspaceName+"+"+ELASTIC_ADMIN_METADATA_TABLE, e);
}
}
private MetaData parseMetaDataString(String metadataString) throws NoPersistedMetaDataException {
if (metadataString != null && metadataString.length() > 0) {
MetaData metaData;
try {
metaData = metaStateService.loadGlobalState(metadataString);
} catch (Exception e) {
logger.error("Failed to parse metadata={}", e, metadataString);
throw new NoPersistedMetaDataException("Failed to parse metadata="+metadataString, e);
}
return metaData;
}
throw new NoPersistedMetaDataException("metadata null or empty");
}
/**
* Try to read fresher metadata from cassandra.
*/
public MetaData checkForNewMetaData(Long expectedVersion) throws NoPersistedMetaDataException {
MetaData localMetaData = readMetaDataAsRow(ConsistencyLevel.ONE);
if (localMetaData != null && localMetaData.version() >= expectedVersion) {
return localMetaData;
}
if (localMetaData == null) {
throw new NoPersistedMetaDataException("No cluster metadata in "+this.elasticAdminKeyspaceName);
}
MetaData quorumMetaData = readMetaDataAsRow(this.metadataReadCL);
if (quorumMetaData.version() >= expectedVersion) {
return quorumMetaData;
}
return null;
}
public MetaData readInternalMetaDataAsRow() throws NoPersistedMetaDataException {
try {
UntypedResultSet rs = QueryProcessor.executeInternal(selectMetadataQuery, DatabaseDescriptor.getClusterName());
if (rs != null && !rs.isEmpty()) {
Row row = rs.one();
if (row.has("metadata"))
return parseMetaDataString(row.getString("metadata"));
}
} catch (Exception e) {
logger.warn("Cannot read metadata locally",e);
}
return null;
}
public MetaData readMetaDataAsRow(ConsistencyLevel cl) throws NoPersistedMetaDataException {
try {
UntypedResultSet rs = process(cl, ClientState.forInternalCalls(), selectMetadataQuery, DatabaseDescriptor.getClusterName());
if (rs != null && !rs.isEmpty()) {
Row row = rs.one();
if (row.has("metadata"))
return parseMetaDataString(row.getString("metadata"));
}
} catch (UnavailableException e) {
logger.warn("Cannot read metadata with consistency="+cl,e);
return null;
} catch (KeyspaceNotDefinedException e) {
logger.warn("Keyspace {} not yet defined", ELASTIC_ADMIN_KEYSPACE);
return null;
} catch (Exception e) {
throw new NoPersistedMetaDataException("Unexpected error",e);
}
throw new NoPersistedMetaDataException("Unexpected error");
}
public Long readMetaDataVersion(ConsistencyLevel cl) throws NoPersistedMetaDataException {
try {
UntypedResultSet rs = process(cl, ClientState.forInternalCalls(), selectVersionMetadataQuery, DatabaseDescriptor.getClusterName());
if (rs != null && !rs.isEmpty()) {
Row row = rs.one();
if (row.has("version"))
return row.getLong("version");
}
} catch (Exception e) {
logger.warn("unexpected error", e);
}
return -1L;
}
public static String getElasticsearchClusterName(Settings settings) {
String clusterName = DatabaseDescriptor.getClusterName();
String datacenterGroup = settings.get(ClusterService.SETTING_CLUSTER_DATACENTER_GROUP);
if (datacenterGroup != null) {
clusterName = DatabaseDescriptor.getClusterName() + "@" + datacenterGroup.trim();
}
return clusterName;
}
public int getLocalDataCenterSize() {
int count = 1;
for (UntypedResultSet.Row row : executeInternal("SELECT data_center, rpc_address FROM system." + SystemKeyspace.PEERS))
if (row.has("rpc_address") && DatabaseDescriptor.getLocalDataCenter().equals(row.getString("data_center")))
count++;
logger.info(" datacenter=[{}] size={} from peers", DatabaseDescriptor.getLocalDataCenter(), count);
return count;
}
Void createElasticAdminKeyspace() {
try {
Map<String, String> replication = new HashMap<String, String>();
replication.put("class", NetworkTopologyStrategy.class.getName());
replication.put(DatabaseDescriptor.getLocalDataCenter(), Integer.toString(getLocalDataCenterSize()));
String createKeyspace = String.format(Locale.ROOT, "CREATE KEYSPACE IF NOT EXISTS \"%s\" WITH replication = %s;",
elasticAdminKeyspaceName, FBUtilities.json(replication).replaceAll("\"", "'"));
logger.info(createKeyspace);
process(ConsistencyLevel.LOCAL_ONE, ClientState.forInternalCalls(), createKeyspace);
} catch (Exception e) {
logger.error((Supplier<?>) () -> new ParameterizedMessage("Failed to initialize keyspace {}", elasticAdminKeyspaceName), e);
throw e;
}
return null;
}
// Modify keyspace replication
public void alterKeyspaceReplicationFactor(String keyspaceName, int rf) {
ReplicationParams replication = Schema.instance.getKSMetaData(keyspaceName).params.replication;
if (!NetworkTopologyStrategy.class.getName().equals(replication.klass))
throw new ConfigurationException("Keyspace ["+keyspaceName+"] should use "+NetworkTopologyStrategy.class.getName()+" replication strategy");
Map<String, String> repMap = replication.asMap();
if (!repMap.containsKey(DatabaseDescriptor.getLocalDataCenter()) || !Integer.toString(rf).equals(repMap.get(DatabaseDescriptor.getLocalDataCenter()))) {
repMap.put(DatabaseDescriptor.getLocalDataCenter(), Integer.toString(rf));
logger.debug("Updating keyspace={} replication={}", keyspaceName, repMap);
try {
String query = String.format(Locale.ROOT, "ALTER KEYSPACE \"%s\" WITH replication = %s",
keyspaceName, FBUtilities.json(repMap).replaceAll("\"", "'"));
logger.info(query);
process(ConsistencyLevel.LOCAL_ONE, ClientState.forInternalCalls(), query);
} catch (Throwable e) {
logger.error((Supplier<?>) () -> new ParameterizedMessage("Failed to alter keyspace [{}]",keyspaceName), e);
throw e;
}
} else {
logger.info("Keep unchanged keyspace={} datacenter={} RF={}", keyspaceName, DatabaseDescriptor.getLocalDataCenter(), rf);
}
}
// Create The meta Data Table if needed
Void createElasticAdminMetaTable(final String metaDataString) {
try {
String createTable = String.format(Locale.ROOT, "CREATE TABLE IF NOT EXISTS \"%s\".%s ( cluster_name text PRIMARY KEY, owner uuid, version bigint, metadata text) WITH comment='%s';",
elasticAdminKeyspaceName, ELASTIC_ADMIN_METADATA_TABLE, metaDataString);
logger.info(createTable);
process(ConsistencyLevel.LOCAL_ONE, ClientState.forInternalCalls(), createTable);
} catch (Exception e) {
logger.error((Supplier<?>) () -> new ParameterizedMessage("Failed to initialize table {}.{}", elasticAdminKeyspaceName, ELASTIC_ADMIN_METADATA_TABLE), e);
throw e;
}
return null;
}
// initialize a first row if needed
Void insertFirstMetaRow(final MetaData metadata, final String metaDataString) {
try {
logger.info(insertMetadataQuery);
process(ConsistencyLevel.LOCAL_ONE, ClientState.forInternalCalls(), insertMetadataQuery,
DatabaseDescriptor.getClusterName(), UUID.fromString(StorageService.instance.getLocalHostId()), metadata.version(), metaDataString);
} catch (Exception e) {
logger.error((Supplier<?>) () -> new ParameterizedMessage("Failed insert first row into table {}.{}", elasticAdminKeyspaceName, ELASTIC_ADMIN_METADATA_TABLE), e);
throw e;
}
return null;
}
void retry (final Supplier<Void> function, final String label) {
for (int i = 0; ; ++i) {
try {
function.get();
break;
} catch (final Exception e) {
if (i >= CREATE_ELASTIC_ADMIN_RETRY_ATTEMPTS) {
logger.error("Failed to {} after {} attempts", label, CREATE_ELASTIC_ADMIN_RETRY_ATTEMPTS);
throw new NoPersistedMetaDataException("Failed to " + label + " after " + CREATE_ELASTIC_ADMIN_RETRY_ATTEMPTS + " attempts", e);
} else
logger.info("Retrying: {}", label);
}
}
}
/**
* Create or update elastic_admin keyspace.
*/
public void createOrUpdateElasticAdminKeyspace() {
UntypedResultSet result = QueryProcessor.executeOnceInternal(String.format(Locale.ROOT, "SELECT replication FROM system_schema.keyspaces WHERE keyspace_name='%s'", elasticAdminKeyspaceName));
if (result.isEmpty()) {
MetaData metadata = state().metaData();
try {
final String metaDataString;
try {
metaDataString = MetaData.Builder.toXContent(metadata);
} catch (IOException e) {
logger.error("Failed to build metadata", e);
throw new NoPersistedMetaDataException("Failed to build metadata", e);
}
// create elastic_admin if not exists after joining the ring and before allowing metadata update.
retry(() -> createElasticAdminKeyspace(), "create elastic admin keyspace");
retry(() -> createElasticAdminMetaTable(metaDataString), "create elastic admin metadata table");
retry(() -> insertFirstMetaRow(metadata, metaDataString), "write first row to metadata table");
logger.info("Succefully initialize {}.{} = {}", elasticAdminKeyspaceName, ELASTIC_ADMIN_METADATA_TABLE, metaDataString);
try {
writeMetaDataAsComment(metaDataString, metadata.version());
} catch (IOException e) {
logger.error("Failed to write metadata as comment", e);
}
} catch (Throwable e) {
logger.error((Supplier<?>) () -> new ParameterizedMessage("Failed to initialize table {}.{}", elasticAdminKeyspaceName, ELASTIC_ADMIN_METADATA_TABLE),e);
}
} else {
Map<String,String> replication = result.one().getFrozenTextMap("replication");
logger.debug("keyspace={} replication={}", elasticAdminKeyspaceName, replication);
if (!NetworkTopologyStrategy.class.getName().equals(replication.get("class")))
throw new ConfigurationException("Keyspace ["+this.elasticAdminKeyspaceName+"] should use "+NetworkTopologyStrategy.class.getName()+" replication strategy");
int currentRF = -1;
if (replication.get(DatabaseDescriptor.getLocalDataCenter()) != null) {
currentRF = Integer.valueOf(replication.get(DatabaseDescriptor.getLocalDataCenter()).toString());
}
int targetRF = getLocalDataCenterSize();
if (targetRF != currentRF) {
replication.put(DatabaseDescriptor.getLocalDataCenter(), Integer.toString(targetRF));
try {
String query = String.format(Locale.ROOT, "ALTER KEYSPACE \"%s\" WITH replication = %s",
elasticAdminKeyspaceName, FBUtilities.json(replication).replaceAll("\"", "'"));
logger.info(query);
process(ConsistencyLevel.LOCAL_ONE, ClientState.forInternalCalls(), query);
} catch (Throwable e) {
logger.error((Supplier<?>) () -> new ParameterizedMessage("Failed to alter keyspace [{}]", elasticAdminKeyspaceName),e);
throw e;
}
} else {
logger.info("Keep unchanged keyspace={} datacenter={} RF={}", elasticAdminKeyspaceName, DatabaseDescriptor.getLocalDataCenter(), targetRF);
}
}
}
public ShardInfo shardInfo(String index, ConsistencyLevel cl) {
Keyspace keyspace = Schema.instance.getKeyspaceInstance(state().metaData().index(index).keyspace());
AbstractReplicationStrategy replicationStrategy = keyspace.getReplicationStrategy();
int rf = replicationStrategy.getReplicationFactor();
if (replicationStrategy instanceof NetworkTopologyStrategy)
rf = ((NetworkTopologyStrategy)replicationStrategy).getReplicationFactor(DatabaseDescriptor.getLocalDataCenter());
return new ShardInfo(rf, cl.blockFor(keyspace));
}
public void persistMetaData(MetaData oldMetaData, MetaData newMetaData, String source) throws IOException, InvalidRequestException, RequestExecutionException, RequestValidationException {
if (!newMetaData.clusterUUID().equals(localNode().getId())) {
logger.error("should not push metadata updated from another node {}/{}", newMetaData.clusterUUID(), newMetaData.version());
return;
}
if (newMetaData.clusterUUID().equals(state().metaData().clusterUUID()) && newMetaData.version() < state().metaData().version()) {
logger.warn("don't push obsolete metadata uuid={} version {} < {}", newMetaData.clusterUUID(), newMetaData.version(), state().metaData().version());
return;
}
String metaDataString = MetaData.Builder.toXContent(newMetaData, MetaData.CASSANDRA_FORMAT_PARAMS);
UUID owner = UUID.fromString(localNode().getId());
boolean applied = processWriteConditional(
this.metadataWriteCL,
this.metadataSerialCL,
ClientState.forInternalCalls(),
updateMetaDataQuery,
new Object[] { owner, newMetaData.version(), metaDataString, DatabaseDescriptor.getClusterName(), newMetaData.version() });
if (applied) {
logger.debug("PAXOS Succefully update metadata source={} newMetaData={} in cluster {}", source, metaDataString, DatabaseDescriptor.getClusterName());
writeMetaDataAsComment(metaDataString, newMetaData.version());
return;
} else {
logger.warn("PAXOS Failed to update metadata oldMetadata={}/{} currentMetaData={}/{} in cluster {}",
oldMetaData.clusterUUID(), oldMetaData.version(), localNode().getId(), newMetaData.version(), DatabaseDescriptor.getClusterName());
throw new ConcurrentMetaDataUpdateException(owner, newMetaData.version());
}
}
public static Collection flattenCollection(Collection c) {
List l = new ArrayList(c.size());
for(Object o : c) {
if (o instanceof Collection) {
l.addAll( flattenCollection((Collection)o) );
} else {
l.add(o);
}
}
return l;
}
/**
* Duplicate code from org.apache.cassandra.service.StorageService.setLoggingLevel, allowing to set log level without StorageService.instance for tests.
* @param classQualifier
* @param rawLevel
*/
public static void setLoggingLevel(String classQualifier, String rawLevel)
{
ch.qos.logback.classic.Logger logBackLogger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(classQualifier);
// if both classQualifer and rawLevel are empty, reload from configuration
if (StringUtils.isBlank(classQualifier) && StringUtils.isBlank(rawLevel) )
{
try {
JMXConfiguratorMBean jmxConfiguratorMBean = JMX.newMBeanProxy(ManagementFactory.getPlatformMBeanServer(),
new ObjectName("ch.qos.logback.classic:Name=default,Type=ch.qos.logback.classic.jmx.JMXConfigurator"),
JMXConfiguratorMBean.class);
jmxConfiguratorMBean.reloadDefaultConfiguration();
return;
} catch (MalformedObjectNameException | JoranException e) {
throw new RuntimeException(e);
}
}
// classQualifer is set, but blank level given
else if (StringUtils.isNotBlank(classQualifier) && StringUtils.isBlank(rawLevel) )
{
if (logBackLogger.getLevel() != null || hasAppenders(logBackLogger))
logBackLogger.setLevel(null);
return;
}
ch.qos.logback.classic.Level level = ch.qos.logback.classic.Level.toLevel(rawLevel);
logBackLogger.setLevel(level);
//logger.info("set log level to {} for classes under '{}' (if the level doesn't look like '{}' then the logger couldn't parse '{}')", level, classQualifier, rawLevel, rawLevel);
}
private static boolean hasAppenders(ch.qos.logback.classic.Logger logger)
{
Iterator<Appender<ILoggingEvent>> it = logger.iteratorForAppenders();
return it.hasNext();
}
/**
* Serialize a cassandra typed object.
*/
public static ByteBuffer serialize(final String ksName, final String cfName, final AbstractType type, final String name, final Object value, final Mapper mapper)
throws SyntaxException, ConfigurationException, JsonGenerationException, JsonMappingException, IOException {
if (value == null) {
return null;
}
if (type instanceof UserType) {
UserType udt = (UserType) type;
ByteBuffer[] components = new ByteBuffer[udt.size()];
int i=0;
if (GEO_POINT_TYPE.equals(ByteBufferUtil.string(udt.name))) {
GeoPoint geoPoint = new GeoPoint();
if (value instanceof String) {
// parse from string lat,lon (ex: "41.12,-71.34") or geohash (ex:"drm3btev3e86")
geoPoint.resetFromString((String)value);
} else {
// parse from lat, lon fields as map
Map<String, Object> mapValue = (Map<String, Object>) value;
geoPoint.reset((Double)mapValue.get(GeoPointFieldMapper.Names.LAT), (Double)mapValue.get(GeoPointFieldMapper.Names.LON));
}
components[i++]=serialize(ksName, cfName, udt.fieldType(0), GeoPointFieldMapper.Names.LAT, geoPoint.lat(), null);
components[i++]=serialize(ksName, cfName, udt.fieldType(1), GeoPointFieldMapper.Names.LON, geoPoint.lon(), null);
} else if (COMPLETION_TYPE.equals(ByteBufferUtil.string(udt.name))) {
// input list<text>, output text, weight int, payload text
Map<String, Object> mapValue = (Map<String, Object>) value;
components[i++]=(mapValue.get(CompletionFieldMapper.Fields.CONTENT_FIELD_NAME_INPUT) == null) ? null : serialize(ksName, cfName, udt.fieldType(0), CompletionFieldMapper.Fields.CONTENT_FIELD_NAME_INPUT, mapValue.get(CompletionFieldMapper.Fields.CONTENT_FIELD_NAME_INPUT), null);
components[i++]=(mapValue.get(CompletionFieldMapper.Fields.CONTENT_FIELD_NAME_WEIGHT) == null) ? null : serialize(ksName, cfName, udt.fieldType(2), CompletionFieldMapper.Fields.CONTENT_FIELD_NAME_WEIGHT, new Long((Integer) mapValue.get(CompletionFieldMapper.Fields.CONTENT_FIELD_NAME_WEIGHT)), null);
components[i++]=(mapValue.get(CompletionFieldMapper.Fields.CONTENT_FIELD_NAME_CONTEXTS) == null) ? null : serialize(ksName, cfName, udt.fieldType(3), CompletionFieldMapper.Fields.CONTENT_FIELD_NAME_CONTEXTS, stringify(mapValue.get(CompletionFieldMapper.Fields.CONTENT_FIELD_NAME_CONTEXTS)), null);
} else {
Map<String, Object> mapValue = (Map<String, Object>) value;
for (int j = 0; j < udt.size(); j++) {
String subName = UTF8Type.instance.compose(udt.fieldName(j).bytes);
AbstractType<?> subType = udt.fieldType(j);
Object subValue = mapValue.get(subName);
Mapper subMapper = (mapper instanceof ObjectMapper) ? ((ObjectMapper) mapper).getMapper(subName) : null;
components[i++]=serialize(ksName, cfName, subType, subName, subValue, subMapper);
}
}
return TupleType.buildValue(components);
} else if (type instanceof MapType) {
MapType mapType = ClusterService.getMapType(ksName, cfName, name);
MapSerializer serializer = mapType.getSerializer();
Map map = (Map)value;
List<ByteBuffer> buffers = serializer.serializeValues((Map)value);
return CollectionSerializer.pack(buffers, map.size(), ProtocolVersion.CURRENT);
} else if (type instanceof CollectionType) {
AbstractType elementType = (type instanceof ListType) ? ((ListType)type).getElementsType() : ((SetType)type).getElementsType();
if (elementType instanceof UserType && ClusterService.GEO_POINT_TYPE.equals(ByteBufferUtil.string(((UserType)elementType).name)) && value instanceof List && ((List)value).get(0) instanceof Double) {
// geo_point as array of double lon,lat like [1.2, 1.3]
UserType udt = (UserType)elementType;
List<Double> values = (List<Double>)value;
ByteBuffer[] elements = new ByteBuffer[] {
serialize(ksName, cfName, udt.fieldType(0), GeoPointFieldMapper.Names.LAT, values.get(1), null),
serialize(ksName, cfName, udt.fieldType(1), GeoPointFieldMapper.Names.LON, values.get(0), null)
};
ByteBuffer geo_point = TupleType.buildValue(elements);
return CollectionSerializer.pack(ImmutableList.of(geo_point), 1, ProtocolVersion.CURRENT);
}
if (value instanceof Collection) {
// list of elementType
List<ByteBuffer> elements = new ArrayList<ByteBuffer>();
for(Object v : flattenCollection((Collection) value)) {
ByteBuffer bb = serialize(ksName, cfName, elementType, name, v, mapper);
elements.add(bb);
}
return CollectionSerializer.pack(elements, elements.size(), ProtocolVersion.CURRENT);
} else {
// singleton list
ByteBuffer bb = serialize(ksName, cfName, elementType, name, value, mapper);
return CollectionSerializer.pack(ImmutableList.of(bb), 1, ProtocolVersion.CURRENT);
}
} else {
// Native cassandra type, encoded with mapper if available.
if (mapper != null) {
if (mapper instanceof FieldMapper) {
return type.decompose( ((FieldMapper) mapper).fieldType().cqlValue(value, type) );
} else if (mapper instanceof ObjectMapper && !((ObjectMapper)mapper).isEnabled()) {
// enabled=false => store field as json text
if (value instanceof Map) {
XContentBuilder builder = XContentFactory.jsonBuilder();
builder.map( (Map) value);
return type.decompose( builder.string() );
}
return type.decompose( value );
}
}
return type.decompose( value );
}
}
public static Object deserialize(AbstractType<?> type, ByteBuffer bb) throws CharacterCodingException {
return deserialize(type, bb, null);
}
public static Object deserialize(AbstractType<?> type, ByteBuffer bb, Mapper mapper) throws CharacterCodingException {
if (type instanceof UserType) {
UserType udt = (UserType) type;
Map<String, Object> mapValue = new HashMap<String, Object>();
ByteBuffer[] components = udt.split(bb);
if (GEO_POINT_TYPE.equals(ByteBufferUtil.string(udt.name))) {
if (components[0] != null)
mapValue.put(GeoPointFieldMapper.Names.LAT, deserialize(udt.type(0), components[0], null));
if (components[1] != null)
mapValue.put(GeoPointFieldMapper.Names.LON, deserialize(udt.type(1), components[1], null));
} else {
for (int i = 0; i < components.length; i++) {
String fieldName = UTF8Type.instance.compose(udt.fieldName(i).bytes);
AbstractType<?> ctype = udt.type(i);
Mapper subMapper = null;
if (mapper != null && mapper instanceof ObjectMapper)
subMapper = ((ObjectMapper)mapper).getMapper(fieldName);
Object value = (components[i] == null) ? null : deserialize(ctype, components[i], subMapper);
mapValue.put(fieldName, value);
}
}
return mapValue;
} else if (type instanceof ListType) {
ListType<?> ltype = (ListType<?>)type;
ByteBuffer input = bb.duplicate();
int size = CollectionSerializer.readCollectionSize(input, ProtocolVersion.CURRENT);
List list = new ArrayList(size);
for (int i = 0; i < size; i++) {
list.add( deserialize(ltype.getElementsType(), CollectionSerializer.readValue(input, ProtocolVersion.CURRENT), mapper));
}
if (input.hasRemaining())
throw new MarshalException("Unexpected extraneous bytes after map value");
return list;
} else if (type instanceof SetType) {
SetType<?> ltype = (SetType<?>)type;
ByteBuffer input = bb.duplicate();
int size = CollectionSerializer.readCollectionSize(input, ProtocolVersion.CURRENT);
Set set = new HashSet(size);
for (int i = 0; i < size; i++) {
set.add( deserialize(ltype.getElementsType(), CollectionSerializer.readValue(input, ProtocolVersion.CURRENT), mapper));
}
if (input.hasRemaining())
throw new MarshalException("Unexpected extraneous bytes after map value");
return set;
} else if (type instanceof MapType) {
MapType<?,?> ltype = (MapType<?,?>)type;
ByteBuffer input = bb.duplicate();
int size = CollectionSerializer.readCollectionSize(input, ProtocolVersion.CURRENT);
Map map = new LinkedHashMap(size);
for (int i = 0; i < size; i++) {
ByteBuffer kbb = CollectionSerializer.readValue(input, ProtocolVersion.CURRENT);
ByteBuffer vbb = CollectionSerializer.readValue(input, ProtocolVersion.CURRENT);
String key = (String) ltype.getKeysType().compose(kbb);
Mapper subMapper = null;
if (mapper != null) {
assert mapper instanceof ObjectMapper : "Expecting an object mapper for MapType";
subMapper = ((ObjectMapper)mapper).getMapper(key);
}
map.put(key, deserialize(ltype.getValuesType(), vbb, subMapper));
}
if (input.hasRemaining())
throw new MarshalException("Unexpected extraneous bytes after map value");
return map;
} else {
Object value = type.compose(bb);
if (mapper != null && mapper instanceof FieldMapper) {
return ((FieldMapper)mapper).fieldType().valueForDisplay(value);
}
return value;
}
}
public IndexService indexServiceSafe(org.elasticsearch.index.Index index) {
return this.indicesService.indexServiceSafe(index);
}
/**
* Return a set of started shards according t the gossip state map and the local shard state.
*/
public ShardRoutingState getShardRoutingStates(org.elasticsearch.index.Index index, UUID nodeUuid) {
if (nodeUuid.equals(this.localNode().uuid())) {
if (this.discovery.isSearchEnabled()) {
try {
IndexShard localIndexShard = indexServiceSafe(index).getShardOrNull(0);
if (localIndexShard != null && localIndexShard.routingEntry() != null)
return localIndexShard.routingEntry().state();
} catch (IndexNotFoundException e) {
}
}
return ShardRoutingState.UNASSIGNED;
}
// read-only map.
Map<String, ShardRoutingState> shards = (this.discovery).getShardRoutingState(nodeUuid);
if (shards == null) {
if (logger.isDebugEnabled() && state().nodes().get(nodeUuid.toString()).status().equals(DiscoveryNodeStatus.ALIVE))
logger.debug("No ShardRoutingState for alive node=[{}]",nodeUuid.toString());
return ShardRoutingState.UNASSIGNED;
}
return shards.get(index.getName());
}
/**
* Set index shard state in the gossip endpoint map (must be synchronized).
*/
public void publishShardRoutingState(final String index, final ShardRoutingState shardRoutingState) throws JsonGenerationException, JsonMappingException, IOException {
if (this.discovery != null)
this.discovery.publishShardRoutingState(index, shardRoutingState);
}
/**
* Publish cluster metadata uuid and version in gossip state.
*/
public void publishX2(final ClusterState clusterState) {
if (this.discovery != null)
this.discovery.publishX2(clusterState);
}
/**
* publish gossip states when setup completed.
*/
public void publishGossipStates() {
if (this.discovery != null) {
this.discovery.publishX2(state());
try {
this.discovery.publishX1();
} catch (IOException e) {
logger.error("Unexpected error", e);
}
}
}
}
| Refactor unused code
| core/src/main/java/org/elasticsearch/cluster/service/ClusterService.java | Refactor unused code | <ide><path>ore/src/main/java/org/elasticsearch/cluster/service/ClusterService.java
<ide> }
<ide>
<ide> public UntypedResultSet process(final ConsistencyLevel cl, final ConsistencyLevel serialConsistencyLevel, final String query, Long writetime, final Object... values) {
<del> ClientState clientState = this.threadPool.getThreadContext().getTransient("_client_state");
<del> if (clientState == null)
<del> clientState = ClientState.forInternalCalls();
<del> return process(cl, serialConsistencyLevel, clientState, query, writetime, values);
<add> return process(cl, serialConsistencyLevel, ClientState.forInternalCalls(), query, writetime, values);
<ide> }
<ide>
<ide> public UntypedResultSet process(final ConsistencyLevel cl, final ConsistencyLevel serialConsistencyLevel, ClientState clientState, final String query, Long writetime, final Object... values)
<ide> }
<ide>
<ide> public boolean processWriteConditional(final ConsistencyLevel cl, final ConsistencyLevel serialCl, final String query, Object... values) {
<del> ClientState clientState = this.threadPool.getThreadContext().getTransient("_client_state");
<del> if (clientState == null)
<del> clientState = ClientState.forInternalCalls();
<del> return processWriteConditional(cl, serialCl, clientState, query, values);
<add> return processWriteConditional(cl, serialCl, ClientState.forInternalCalls(), query, values);
<ide> }
<ide>
<ide> public boolean processWriteConditional(final ConsistencyLevel cl, final ConsistencyLevel serialCl, ClientState clientState, final String query, Object... values) |
|
Java | mit | e46bb1ca931b49c3f2eb1e8ebfae4ac00e8f42ee | 0 | Um-Mitternacht/Wiccan_Arts,backuporg/Witchworks,Um-Mitternacht/Witchworks | package com.wiccanarts.common.item;
import com.wiccanarts.common.lib.LibItemName;
import com.wiccanarts.common.lib.LibMod;
import net.minecraft.init.SoundEvents;
import net.minecraft.item.Item;
import net.minecraft.item.ItemArmor;
import net.minecraftforge.common.util.EnumHelper;
/**
* This class was created by Arekkuusu on 04/04/2017.
* It's distributed as part of Wiccan Arts under
* the MIT license.
*/
public final class ModMaterials {
public static final Item.ToolMaterial TOOL_SILVER = EnumHelper.addToolMaterial(LibItemName.SILVER, 1, 250, 3.0F, 2.0F, 22);
public static final ItemArmor.ArmorMaterial ARMOR_SILVER = EnumHelper.addArmorMaterial(LibItemName.SILVER, LibMod.MOD_ID+":"+LibItemName.SILVER, 18, new int[] {2, 9, 4, 2}, 22, SoundEvents.ITEM_ARMOR_EQUIP_GENERIC, 1.5F);
private ModMaterials() {
}
}
| src/main/java/com/wiccanarts/common/item/ModMaterials.java | package com.wiccanarts.common.item;
import com.wiccanarts.common.lib.LibItemName;
import com.wiccanarts.common.lib.LibMod;
import net.minecraft.init.SoundEvents;
import net.minecraft.item.Item;
import net.minecraft.item.ItemArmor;
import net.minecraftforge.common.util.EnumHelper;
/**
* This class was created by Arekkuusu on 04/04/2017.
* It's distributed as part of Wiccan Arts under
* the MIT license.
*/
public final class ModMaterials {
public static final Item.ToolMaterial TOOL_SILVER = EnumHelper.addToolMaterial(LibItemName.SILVER, 2, 222, 3.5F, 2.5F, 18);
public static final ItemArmor.ArmorMaterial ARMOR_SILVER = EnumHelper.addArmorMaterial(LibItemName.SILVER, LibMod.MOD_ID+":"+LibItemName.SILVER, 18, new int[] {2, 9, 4, 2}, 22, SoundEvents.ITEM_ARMOR_EQUIP_GENERIC, 1.5F);
private ModMaterials() {
}
}
| how are these values, berci?
| src/main/java/com/wiccanarts/common/item/ModMaterials.java | how are these values, berci? | <ide><path>rc/main/java/com/wiccanarts/common/item/ModMaterials.java
<ide> */
<ide> public final class ModMaterials {
<ide>
<del> public static final Item.ToolMaterial TOOL_SILVER = EnumHelper.addToolMaterial(LibItemName.SILVER, 2, 222, 3.5F, 2.5F, 18);
<add> public static final Item.ToolMaterial TOOL_SILVER = EnumHelper.addToolMaterial(LibItemName.SILVER, 1, 250, 3.0F, 2.0F, 22);
<ide> public static final ItemArmor.ArmorMaterial ARMOR_SILVER = EnumHelper.addArmorMaterial(LibItemName.SILVER, LibMod.MOD_ID+":"+LibItemName.SILVER, 18, new int[] {2, 9, 4, 2}, 22, SoundEvents.ITEM_ARMOR_EQUIP_GENERIC, 1.5F);
<ide>
<ide> private ModMaterials() { |
|
Java | apache-2.0 | 7140bda0a1bc3221e4912b637075f2da82aad3c7 | 0 | fishercoder1534/Leetcode,fishercoder1534/Leetcode,fishercoder1534/Leetcode,fishercoder1534/Leetcode,fishercoder1534/Leetcode | package com.fishercoder.solutions;
public class _304 {
public static class Solution1 {
public class NumMatrix {
public NumMatrix(int[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return;
}
/**The dimensions of this tot matrix is actually 1 bigger than the given matrix, cool!*/
tot = new int[matrix.length + 1][matrix[0].length + 1];
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
tot[i + 1][j + 1] =
matrix[i][j] + tot[i + 1][j] + tot[i][j + 1] - tot[i][j];
}
}
}
public int sumRegion(int row1, int col1, int row2, int col2) {
return tot[row2 + 1][col2 + 1] - tot[row2 + 1][col1] - tot[row1][col2 + 1]
+ tot[row1][col1];
}
int[][] tot;
}
}
/**
* Your NumMatrix object will be instantiated and called as such:
* NumMatrix obj = new NumMatrix(matrix);
* int param_1 = obj.sumRegion(row1,col1,row2,col2);
*/
}
| src/main/java/com/fishercoder/solutions/_304.java | package com.fishercoder.solutions;
/**
* 304. Range Sum Query 2D - Immutable
*
* Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2).
Range Sum Query 2D
The above rectangle (with the red border) is defined by (row1, col1) = (2, 1) and (row2, col2) = (4, 3), which contains sum = 8.
Example:
Given matrix = [
[3, 0, 1, 4, 2],
[5, 6, 3, 2, 1],
[1, 2, 0, 1, 5],
[4, 1, 0, 1, 7],
[1, 0, 3, 0, 5]
]
sumRegion(2, 1, 4, 3) -> 8
sumRegion(1, 1, 2, 2) -> 11
sumRegion(1, 2, 2, 4) -> 12
Note:
You may assume that the matrix does not change.
There are many calls to sumRegion function.
You may assume that row1 ≤ row2 and col1 ≤ col2.
*/
public class _304 {
public static class Solution1 {
public class NumMatrix {
public NumMatrix(int[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return;
}
/**The dimensions of this tot matrix is actually 1 bigger than the given matrix, cool!*/
tot = new int[matrix.length + 1][matrix[0].length + 1];
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
tot[i + 1][j + 1] =
matrix[i][j] + tot[i + 1][j] + tot[i][j + 1] - tot[i][j];
}
}
}
public int sumRegion(int row1, int col1, int row2, int col2) {
return tot[row2 + 1][col2 + 1] - tot[row2 + 1][col1] - tot[row1][col2 + 1]
+ tot[row1][col1];
}
int[][] tot;
}
}
/**
* Your NumMatrix object will be instantiated and called as such:
* NumMatrix obj = new NumMatrix(matrix);
* int param_1 = obj.sumRegion(row1,col1,row2,col2);
*/
}
| refactor 304
| src/main/java/com/fishercoder/solutions/_304.java | refactor 304 | <ide><path>rc/main/java/com/fishercoder/solutions/_304.java
<ide> package com.fishercoder.solutions;
<ide>
<del>/**
<del> * 304. Range Sum Query 2D - Immutable
<del> *
<del> * Given a 2D matrix matrix, find the sum of the elements inside the rectangle defined by its upper left corner (row1, col1) and lower right corner (row2, col2).
<del>
<del> Range Sum Query 2D
<del> The above rectangle (with the red border) is defined by (row1, col1) = (2, 1) and (row2, col2) = (4, 3), which contains sum = 8.
<del>
<del> Example:
<del> Given matrix = [
<del> [3, 0, 1, 4, 2],
<del> [5, 6, 3, 2, 1],
<del> [1, 2, 0, 1, 5],
<del> [4, 1, 0, 1, 7],
<del> [1, 0, 3, 0, 5]
<del> ]
<del>
<del> sumRegion(2, 1, 4, 3) -> 8
<del> sumRegion(1, 1, 2, 2) -> 11
<del> sumRegion(1, 2, 2, 4) -> 12
<del> Note:
<del> You may assume that the matrix does not change.
<del> There are many calls to sumRegion function.
<del> You may assume that row1 ≤ row2 and col1 ≤ col2.
<del> */
<ide> public class _304 {
<ide>
<ide> public static class Solution1 {
<ide> for (int i = 0; i < matrix.length; i++) {
<ide> for (int j = 0; j < matrix[0].length; j++) {
<ide> tot[i + 1][j + 1] =
<del> matrix[i][j] + tot[i + 1][j] + tot[i][j + 1] - tot[i][j];
<add> matrix[i][j] + tot[i + 1][j] + tot[i][j + 1] - tot[i][j];
<ide> }
<ide> }
<ide> }
<ide>
<ide> public int sumRegion(int row1, int col1, int row2, int col2) {
<ide> return tot[row2 + 1][col2 + 1] - tot[row2 + 1][col1] - tot[row1][col2 + 1]
<del> + tot[row1][col1];
<add> + tot[row1][col1];
<ide> }
<ide>
<ide> int[][] tot; |
|
Java | apache-2.0 | 73560f767fed1ebb954321ea1042a0edd3f73aad | 0 | facebook/litho,facebook/litho,facebook/litho,facebook/litho,facebook/litho,facebook/litho | /**
* Copyright (c) 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
package com.facebook.litho;
import javax.annotation.CheckReturnValue;
import javax.annotation.concurrent.GuardedBy;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import android.content.Context;
import android.content.ContextWrapper;
import android.graphics.Rect;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.os.Process;
import android.support.annotation.IntDef;
import android.support.annotation.Keep;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.VisibleForTesting;
import android.view.View;
import android.view.ViewParent;
import com.facebook.infer.annotation.ReturnsOwnership;
import static com.facebook.litho.ComponentLifecycle.StateUpdate;
import static com.facebook.litho.ComponentsLogger.ACTION_SUCCESS;
import static com.facebook.litho.ComponentsLogger.EVENT_LAYOUT_CALCULATE;
import static com.facebook.litho.ComponentsLogger.EVENT_PRE_ALLOCATE_MOUNT_CONTENT;
import static com.facebook.litho.ComponentsLogger.PARAM_IS_BACKGROUND_LAYOUT;
import static com.facebook.litho.ComponentsLogger.PARAM_LOG_TAG;
import static com.facebook.litho.ComponentsLogger.PARAM_TREE_DIFF_ENABLED;
import static com.facebook.litho.ThreadUtils.assertHoldsLock;
import static com.facebook.litho.ThreadUtils.assertMainThread;
import static com.facebook.litho.ThreadUtils.isMainThread;
/**
* Represents a tree of components and controls their life cycle. ComponentTree takes in a single
* root component and recursively invokes its OnCreateLayout to create a tree of components.
* ComponentTree is responsible for refreshing the mounted state of a component with new props.
*
* The usual use case for {@link ComponentTree} is:
* <code>
* ComponentTree component = ComponentTree.create(context, MyComponent.create());
* myHostView.setRoot(component);
* <code/>
*/
public class ComponentTree {
private static final String TAG = ComponentTree.class.getSimpleName();
private static final int SIZE_UNINITIALIZED = -1;
// MainThread Looper messages:
private static final int MESSAGE_WHAT_BACKGROUND_LAYOUT_STATE_UPDATED = 1;
private static final String DEFAULT_LAYOUT_THREAD_NAME = "ComponentLayoutThread";
private static final int DEFAULT_LAYOUT_THREAD_PRIORITY = Process.THREAD_PRIORITY_BACKGROUND;
private static final int SCHEDULE_NONE = 0;
private static final int SCHEDULE_LAYOUT_ASYNC = 1;
private static final int SCHEDULE_LAYOUT_SYNC = 2;
private ComponentsStethoManager mStethoManager;
@IntDef({SCHEDULE_NONE, SCHEDULE_LAYOUT_ASYNC, SCHEDULE_LAYOUT_SYNC})
@Retention(RetentionPolicy.SOURCE)
private @interface PendingLayoutCalculation {}
private static final AtomicInteger sIdGenerator = new AtomicInteger(0);
private static final Handler sMainThreadHandler = new ComponentMainThreadHandler();
// Do not access sDefaultLayoutThreadLooper directly, use getDefaultLayoutThreadLooper().
@GuardedBy("ComponentTree.class")
private static volatile Looper sDefaultLayoutThreadLooper;
// Helpers to track view visibility when we are incrementally
// mounting and partially invalidating
private static final int[] sCurrentLocation = new int[2];
private static final int[] sParentLocation = new int[2];
private static final Rect sParentBounds = new Rect();
private final Runnable mCalculateLayoutRunnable = new Runnable() {
@Override
public void run() {
calculateLayout(null);
}
};
private final ComponentContext mContext;
// These variables are only accessed from the main thread.
private boolean mIsMounting;
private boolean mIncrementalMountEnabled;
private boolean mIsLayoutDiffingEnabled;
private boolean mIsAttached;
private boolean mIsAsyncUpdateStateEnabled;
private ComponentView mComponentView;
private LayoutHandler mLayoutThreadHandler;
@GuardedBy("this")
private boolean mHasViewMeasureSpec;
// TODO(6606683): Enable recycling of mComponent.
// We will need to ensure there are no background threads referencing mComponent. We'll need
// to keep a reference count or something. :-/
@GuardedBy("this")
private Component<?> mRoot;
@GuardedBy("this")
private int mWidthSpec = SIZE_UNINITIALIZED;
@GuardedBy("this")
private int mHeightSpec = SIZE_UNINITIALIZED;
// This is written to only by the main thread with the lock held, read from the main thread with
// no lock held, or read from any other thread with the lock held.
private LayoutState mMainThreadLayoutState;
// The semantics here are tricky. Whenever you transfer mBackgroundLayoutState to a local that
// will be accessed outside of the lock, you must set mBackgroundLayoutState to null to ensure
// that the current thread alone has access to the LayoutState, which is single-threaded.
@GuardedBy("this")
private LayoutState mBackgroundLayoutState;
@GuardedBy("this")
private StateHandler mStateHandler;
private Object mLayoutLock;
protected final int mId = sIdGenerator.getAndIncrement();
@GuardedBy("this")
private boolean mIsMeasuring;
@GuardedBy("this")
private @PendingLayoutCalculation int mScheduleLayoutAfterMeasure;
public static Builder create(ComponentContext context, Component.Builder<?> root) {
return create(context, root.build());
}
public static Builder create(ComponentContext context, Component<?> root) {
return ComponentsPools.acquireComponentTreeBuilder(context, root);
}
protected ComponentTree(Builder builder) {
mContext = ComponentContext.withComponentTree(builder.context, this);
mRoot = builder.root;
mIncrementalMountEnabled = builder.incrementalMountEnabled;
mIsLayoutDiffingEnabled = builder.isLayoutDiffingEnabled;
mLayoutThreadHandler = builder.layoutThreadHandler;
mLayoutLock = builder.layoutLock;
mIsAsyncUpdateStateEnabled = builder.asyncStateUpdates;
if (mLayoutThreadHandler == null) {
mLayoutThreadHandler = new DefaultLayoutHandler(getDefaultLayoutThreadLooper());
}
final StateHandler builderStateHandler = builder.stateHandler;
mStateHandler = builderStateHandler == null
? StateHandler.acquireNewInstance(null)
: builderStateHandler;
}
LayoutState getMainThreadLayoutState() {
return mMainThreadLayoutState;
}
@VisibleForTesting
protected LayoutState getBackgroundLayoutState() {
return mBackgroundLayoutState;
}
/**
* Picks the best LayoutState and sets it in mMainThreadLayoutState. The return value
* is a LayoutState that must be released (after the lock is released). This
* awkward contract is necessary to ensure thread-safety.
*/
@CheckReturnValue
@ReturnsOwnership
private LayoutState setBestMainThreadLayoutAndReturnOldLayout() {
assertHoldsLock(this);
// If everything matches perfectly then we prefer mMainThreadLayoutState
// because that means we don't need to remount.
boolean isMainThreadLayoutBest;
if (isCompatibleComponentAndSpec(mMainThreadLayoutState)) {
isMainThreadLayoutBest = true;
} else if (isCompatibleSpec(mBackgroundLayoutState, mWidthSpec, mHeightSpec)
|| !isCompatibleSpec(mMainThreadLayoutState, mWidthSpec, mHeightSpec)) {
// If mMainThreadLayoutState isn't a perfect match, we'll prefer
// mBackgroundLayoutState since it will have the more recent create.
isMainThreadLayoutBest = false;
} else {
// If the main thread layout is still compatible size-wise, and the
// background one is not, then we'll do nothing. We want to keep the same
// main thread layout so that we don't force main thread re-layout.
isMainThreadLayoutBest = true;
}
if (isMainThreadLayoutBest) {
// We don't want to hold onto mBackgroundLayoutState since it's unlikely
// to ever be used again. We return mBackgroundLayoutState to indicate it
// should be released after exiting the lock.
LayoutState toRelease = mBackgroundLayoutState;
mBackgroundLayoutState = null;
return toRelease;
} else {
// Since we are changing layout states we'll need to remount.
if (mComponentView != null) {
mComponentView.setMountStateDirty();
}
LayoutState toRelease = mMainThreadLayoutState;
mMainThreadLayoutState = mBackgroundLayoutState;
mBackgroundLayoutState = null;
return toRelease;
}
}
private void backgroundLayoutStateUpdated() {
assertMainThread();
// If we aren't attached, then we have nothing to do. We'll handle
// everything in onAttach.
if (!mIsAttached) {
return;
}
LayoutState toRelease;
boolean layoutStateUpdated;
int componentRootId;
synchronized (this) {
if (mRoot == null) {
// We have been released. Abort.
return;
}
LayoutState oldMainThreadLayoutState = mMainThreadLayoutState;
toRelease = setBestMainThreadLayoutAndReturnOldLayout();
layoutStateUpdated = (mMainThreadLayoutState != oldMainThreadLayoutState);
componentRootId = mRoot.getId();
}
if (toRelease != null) {
toRelease.releaseRef();
toRelease = null;
}
if (!layoutStateUpdated) {
return;
}
// We defer until measure if we don't yet have a width/height
int viewWidth = mComponentView.getMeasuredWidth();
int viewHeight = mComponentView.getMeasuredHeight();
if (viewWidth == 0 && viewHeight == 0) {
// The host view has not been measured yet.
return;
}
final boolean needsAndroidLayout =
!isCompatibleComponentAndSize(
mMainThreadLayoutState,
componentRootId,
viewWidth,
viewHeight);
if (needsAndroidLayout) {
mComponentView.requestLayout();
} else {
mountComponentIfDirty();
}
}
void attach() {
assertMainThread();
if (mComponentView == null) {
throw new IllegalStateException("Trying to attach a ComponentTree without a set View");
}
LayoutState toRelease;
int componentRootId;
synchronized (this) {
// We need to track that we are attached regardless...
mIsAttached = true;
// ... and then we do state transfer
toRelease = setBestMainThreadLayoutAndReturnOldLayout();
componentRootId = mRoot.getId();
}
if (toRelease != null) {
toRelease.releaseRef();
toRelease = null;
}
// We defer until measure if we don't yet have a width/height
int viewWidth = mComponentView.getMeasuredWidth();
int viewHeight = mComponentView.getMeasuredHeight();
if (viewWidth == 0 && viewHeight == 0) {
// The host view has not been measured yet.
return;
}
final boolean needsAndroidLayout =
!isCompatibleComponentAndSize(
mMainThreadLayoutState,
componentRootId,
viewWidth,
viewHeight);
if (needsAndroidLayout || mComponentView.isMountStateDirty()) {
mComponentView.requestLayout();
} else {
mComponentView.rebind();
}
}
private static boolean hasSameBaseContext(Context context1, Context context2) {
return getBaseContext(context1) == getBaseContext(context2);
}
private static Context getBaseContext(Context context) {
Context baseContext = context;
while (baseContext instanceof ContextWrapper) {
baseContext = ((ContextWrapper) baseContext).getBaseContext();
}
return baseContext;
}
boolean isMounting() {
return mIsMounting;
}
private boolean mountComponentIfDirty() {
if (mComponentView.isMountStateDirty()) {
if (mIncrementalMountEnabled) {
incrementalMountComponent();
} else {
mountComponent(null);
}
return true;
}
return false;
}
void incrementalMountComponent() {
assertMainThread();
if (!mIncrementalMountEnabled) {
throw new IllegalStateException("Calling incrementalMountComponent() but incremental mount" +
" is not enabled");
}
// Per ComponentTree visible area. Because ComponentViews can be nested and mounted
// not in "depth order", this variable cannot be static.
final Rect currentVisibleArea = ComponentsPools.acquireRect();
if (getVisibleRect(currentVisibleArea)) {
mountComponent(currentVisibleArea);
}
// if false: no-op, doesn't have visible area, is not ready or not attached
ComponentsPools.release(currentVisibleArea);
}
private boolean getVisibleRect(Rect visibleBounds) {
assertMainThread();
getLocationAndBoundsOnScreen(mComponentView, sCurrentLocation, visibleBounds);
final ViewParent viewParent = mComponentView.getParent();
if (viewParent instanceof View) {
View parent = (View) viewParent;
getLocationAndBoundsOnScreen(parent, sParentLocation, sParentBounds);
if (!visibleBounds.setIntersect(visibleBounds, sParentBounds)) {
return false;
}
}
visibleBounds.offset(-sCurrentLocation[0], -sCurrentLocation[1]);
return true;
}
private static void getLocationAndBoundsOnScreen(View view, int[] location, Rect bounds) {
assertMainThread();
view.getLocationOnScreen(location);
bounds.set(
location[0],
location[1],
location[0] + view.getWidth(),
location[1] + view.getHeight());
}
void mountComponent(Rect currentVisibleArea) {
assertMainThread();
mIsMounting = true;
// currentVisibleArea null or empty => mount all
mComponentView.mount(mMainThreadLayoutState, currentVisibleArea);
mIsMounting = false;
}
void detach() {
assertMainThread();
synchronized (this) {
mIsAttached = false;
mHasViewMeasureSpec = false;
}
}
/**
* Set a new ComponentView to this ComponentTree checking that they have the same context and
* clear the ComponentTree reference from the previous ComponentView if any.
* Be sure this ComponentTree is detach first.
*/
void setComponentView(@NonNull ComponentView view) {
assertMainThread();
// It's possible that the view associated with this ComponentTree was recycled but was
// never detached. In all cases we have to make sure that the old references between
// componentView and componentTree are reset.
if (mIsAttached) {
if (mComponentView != null) {
mComponentView.setComponent(null);
} else {
detach();
}
} else if (mComponentView != null) {
// Remove the ComponentTree reference from a previous view if any.
mComponentView.clearComponentTree();
}
if (!hasSameBaseContext(view.getContext(), mContext)) {
// This would indicate bad things happening, like leaking a context.
throw new IllegalArgumentException(
"Base view context differs, view context is: " + view.getContext() +
", ComponentTree context is: " + mContext);
}
mComponentView = view;
}
void clearComponentView() {
assertMainThread();
// Crash if the ComponentTree is mounted to a view.
if (mIsAttached) {
throw new IllegalStateException(
"Clearing the ComponentView while the ComponentTree is attached");
}
mComponentView = null;
}
void measure(int widthSpec, int heightSpec, int[] measureOutput, boolean forceLayout) {
assertMainThread();
Component component = null;
LayoutState toRelease;
synchronized (this) {
mIsMeasuring = true;
// This widthSpec/heightSpec is fixed until the view gets detached.
mWidthSpec = widthSpec;
mHeightSpec = heightSpec;
mHasViewMeasureSpec = true;
toRelease = setBestMainThreadLayoutAndReturnOldLayout();
if (forceLayout || !isCompatibleComponentAndSpec(mMainThreadLayoutState)) {
// Neither layout was compatible and we have to perform a layout.
// Since outputs get set on the same object during the lifecycle calls,
// we need to copy it in order to use it concurrently.
component = mRoot.makeShallowCopy();
}
}
if (toRelease != null) {
toRelease.releaseRef();
toRelease = null;
}
if (component != null) {
// TODO: We should re-use the existing CSSNodeDEPRECATED tree instead of re-creating it.
if (mMainThreadLayoutState != null) {
// It's beneficial to delete the old layout state before we start creating a new one since
// we'll be able to re-use some of the layout nodes.
LayoutState localLayoutState;
synchronized (this) {
localLayoutState = mMainThreadLayoutState;
mMainThreadLayoutState = null;
}
localLayoutState.releaseRef();
}
// We have no layout that matches the given spec, so we need to compute it on the main thread.
LayoutState localLayoutState = calculateLayoutState(
mLayoutLock,
mContext,
component,
widthSpec,
heightSpec,
mIsLayoutDiffingEnabled,
null);
final StateHandler layoutStateStateHandler =
localLayoutState.consumeStateHandler();
synchronized (this) {
if (layoutStateStateHandler != null) {
mStateHandler.commit(layoutStateStateHandler);
ComponentsPools.release(layoutStateStateHandler);
}
mMainThreadLayoutState = localLayoutState;
localLayoutState = null;
}
// We need to force remount on layout
mComponentView.setMountStateDirty();
}
measureOutput[0] = mMainThreadLayoutState.getWidth();
measureOutput[1] = mMainThreadLayoutState.getHeight();
int layoutScheduleType = SCHEDULE_NONE;
Component root = null;
synchronized (this) {
mIsMeasuring = false;
if (mScheduleLayoutAfterMeasure != SCHEDULE_NONE) {
layoutScheduleType = mScheduleLayoutAfterMeasure;
mScheduleLayoutAfterMeasure = SCHEDULE_NONE;
root = mRoot.makeShallowCopy();
}
}
if (layoutScheduleType != SCHEDULE_NONE) {
setRootAndSizeSpecInternal(
root,
SIZE_UNINITIALIZED,
SIZE_UNINITIALIZED,
layoutScheduleType == SCHEDULE_LAYOUT_ASYNC,
null /*output */);
}
}
/**
* Returns {@code true} if the layout call mounted the component.
*/
boolean layout() {
assertMainThread();
return mountComponentIfDirty();
}
/**
* Returns whether incremental mount is enabled or not in this component.
*/
public boolean isIncrementalMountEnabled() {
return mIncrementalMountEnabled;
}
synchronized Component getRoot() {
return mRoot;
}
/**
* Update the root component. This can happen in both attached and detached states. In each case
* we will run a layout and then proxy a message to the main thread to cause a
* relayout/invalidate.
*/
public void setRoot(Component<?> rootComponent) {
if (rootComponent == null) {
throw new IllegalArgumentException("Root component can't be null");
}
setRootAndSizeSpecInternal(
rootComponent,
SIZE_UNINITIALIZED,
SIZE_UNINITIALIZED,
false /* isAsync */,
null /* output */);
}
public void preAllocateMountContent() {
assertMainThread();
final LayoutState toPrePopulate;
if (mMainThreadLayoutState != null) {
toPrePopulate = mMainThreadLayoutState.acquireRef();
} else {
synchronized (this) {
toPrePopulate = mBackgroundLayoutState;
if (toPrePopulate == null) {
return;
}
toPrePopulate.acquireRef();
}
}
logPreAllocationStart();
toPrePopulate.preAllocateMountContent();
logPreAllocationFinish();
toPrePopulate.releaseRef();
}
public void setRootAsync(Component<?> rootComponent) {
if (rootComponent == null) {
throw new IllegalArgumentException("Root component can't be null");
}
setRootAndSizeSpecInternal(
rootComponent,
SIZE_UNINITIALIZED,
SIZE_UNINITIALIZED,
true /* isAsync */,
null /* output */);
}
synchronized void updateStateLazy(String componentKey, StateUpdate stateUpdate) {
if (mRoot == null) {
return;
}
mStateHandler.queueStateUpdate(componentKey, stateUpdate);
}
void updateState(String componentKey, StateUpdate stateUpdate) {
updateStateInternal(componentKey, stateUpdate, false);
}
void updateStateAsync(String componentKey, StateUpdate stateUpdate) {
if (!mIsAsyncUpdateStateEnabled) {
throw new RuntimeException("Triggering async state updates on this component tree is " +
"disabled, use sync state updates.");
}
updateStateInternal(componentKey, stateUpdate, true);
}
void updateStateInternal(String key, StateUpdate stateUpdate, boolean isAsync) {
final Component<?> root;
synchronized (this) {
if (mRoot == null) {
return;
}
mStateHandler.queueStateUpdate(key, stateUpdate);
if (mIsMeasuring) {
// If the layout calculation was already scheduled to happen synchronously let's just go
// with a sync layout calculation.
if (mScheduleLayoutAfterMeasure == SCHEDULE_LAYOUT_SYNC) {
return;
}
mScheduleLayoutAfterMeasure = isAsync ? SCHEDULE_LAYOUT_ASYNC : SCHEDULE_LAYOUT_SYNC;
return;
}
root = mRoot.makeShallowCopy();
}
setRootAndSizeSpecInternal(
root,
SIZE_UNINITIALIZED,
SIZE_UNINITIALIZED,
isAsync,
null /*output */);
}
/**
* Update the width/height spec. This is useful if you are currently detached and are responding
* to a configuration change. If you are currently attached then the HostView is the source of
* truth for width/height, so this call will be ignored.
*/
public void setSizeSpec(int widthSpec, int heightSpec) {
setSizeSpec(widthSpec, heightSpec, null);
}
/**
* Same as {@link #setSizeSpec(int, int)} but fetches the resulting width/height
* in the given {@link Size}.
*/
public void setSizeSpec(int widthSpec, int heightSpec, Size output) {
setRootAndSizeSpecInternal(
null,
widthSpec,
heightSpec,
false /* isAsync */,
output /* output */);
}
public void setSizeSpecAsync(int widthSpec, int heightSpec) {
setRootAndSizeSpecInternal(
null,
widthSpec,
heightSpec,
true /* isAsync */,
null /* output */);
}
/**
* Compute asynchronously a new layout with the given component root and sizes
*/
public void setRootAndSizeSpecAsync(Component<?> root, int widthSpec, int heightSpec) {
if (root == null) {
throw new IllegalArgumentException("Root component can't be null");
}
setRootAndSizeSpecInternal(
root,
widthSpec,
heightSpec,
true /* isAsync */,
null /* output */);
}
/**
* Compute a new layout with the given component root and sizes
*/
public void setRootAndSizeSpec(Component<?> root, int widthSpec, int heightSpec) {
if (root == null) {
throw new IllegalArgumentException("Root component can't be null");
}
setRootAndSizeSpecInternal(
root,
widthSpec,
heightSpec,
false /* isAsync */,
null /* output */);
}
public void setRootAndSizeSpec(Component<?> root, int widthSpec, int heightSpec, Size output) {
if (root == null) {
throw new IllegalArgumentException("Root component can't be null");
}
setRootAndSizeSpecInternal(
root,
widthSpec,
heightSpec,
false /* isAsync */,
output);
}
/**
* @return the {@link ComponentView} associated with this ComponentTree if any.
*/
@Keep
@Nullable
public ComponentView getComponentView() {
assertMainThread();
return mComponentView;
}
/**
* Provides a new instance from the StateHandler pool that is initialized with the information
* from the StateHandler currently held by the ComponentTree. Once the state updates have been
* applied and we are back in the main thread the state handler gets released to the pool.
* @return a copy of the state handler instance held by ComponentTree.
*/
public synchronized StateHandler getStateHandler() {
return StateHandler.acquireNewInstance(mStateHandler);
}
private void setRootAndSizeSpecInternal(
Component<?> root,
int widthSpec,
int heightSpec,
boolean isAsync,
Size output) {
synchronized (this) {
final Map<String, List<StateUpdate>> pendingStateUpdates =
mStateHandler.getPendingStateUpdates();
if (pendingStateUpdates != null && pendingStateUpdates.size() > 0 && root != null) {
root = root.makeShallowCopyWithNewId();
}
final boolean rootInitialized = root != null;
final boolean widthSpecInitialized = widthSpec != SIZE_UNINITIALIZED;
final boolean heightSpecInitialized = heightSpec != SIZE_UNINITIALIZED;
if (mHasViewMeasureSpec && !rootInitialized) {
// It doesn't make sense to specify the width/height while the HostView is attached and it
// has been measured. We do not throw an Exception only because there can be race conditions
// that can cause this to happen. In such race conditions, ignoring the setSizeSpec call is
// the right thing to do.
return;
}
final boolean widthSpecDidntChange = !widthSpecInitialized || widthSpec == mWidthSpec;
final boolean heightSpecDidntChange = !heightSpecInitialized || heightSpec == mHeightSpec;
final boolean sizeSpecDidntChange = widthSpecDidntChange && heightSpecDidntChange;
final LayoutState mostRecentLayoutState =
mBackgroundLayoutState != null ? mBackgroundLayoutState : mMainThreadLayoutState;
final boolean allSpecsWereInitialized =
widthSpecInitialized &&
heightSpecInitialized &&
mWidthSpec != SIZE_UNINITIALIZED &&
mHeightSpec != SIZE_UNINITIALIZED;
final boolean sizeSpecsAreCompatible =
sizeSpecDidntChange ||
(allSpecsWereInitialized &&
mostRecentLayoutState != null &&
LayoutState.hasCompatibleSizeSpec(
mWidthSpec,
mHeightSpec,
widthSpec,
heightSpec,
mostRecentLayoutState.getWidth(),
mostRecentLayoutState.getHeight()));
final boolean rootDidntChange = !rootInitialized || root.getId() == mRoot.getId();
if (rootDidntChange && sizeSpecsAreCompatible) {
// The spec and the root haven't changed. Either we have a layout already, or we're
// currently computing one on another thread.
if (output != null) {
output.height = mostRecentLayoutState.getHeight();
output.width = mostRecentLayoutState.getWidth();
}
return;
}
if (widthSpecInitialized) {
mWidthSpec = widthSpec;
}
if (heightSpecInitialized) {
mHeightSpec = heightSpec;
}
if (rootInitialized) {
mRoot = root;
}
}
if (isAsync && output != null) {
throw new IllegalArgumentException("The layout can't be calculated asynchronously if" +
" we need the Size back");
} else if (isAsync) {
mLayoutThreadHandler.removeCallbacks(mCalculateLayoutRunnable);
mLayoutThreadHandler.post(mCalculateLayoutRunnable);
} else {
calculateLayout(output);
}
}
/**
* Calculates the layout.
* @param output a destination where the size information should be saved
*/
private void calculateLayout(Size output) {
int widthSpec;
int heightSpec;
Component<?> root;
LayoutState previousLayoutState = null;
// Cancel any scheduled requests we might have in the background queue since we are starting
// a new layout computation.
mLayoutThreadHandler.removeCallbacksAndMessages(null);
synchronized (this) {
// Can't compute a layout if specs or root are missing
if (!hasSizeSpec() || mRoot == null) {
return;
}
// Check if we already have a compatible layout.
if (hasCompatibleComponentAndSpec()) {
if (output != null) {
final LayoutState mostRecentLayoutState =
mBackgroundLayoutState != null ? mBackgroundLayoutState : mMainThreadLayoutState;
output.width = mostRecentLayoutState.getWidth();
output.height = mostRecentLayoutState.getHeight();
}
return;
}
widthSpec = mWidthSpec;
heightSpec = mHeightSpec;
root = mRoot.makeShallowCopy();
if (mMainThreadLayoutState != null) {
previousLayoutState = mMainThreadLayoutState.acquireRef();
}
}
logLayoutCalculationStart(root);
LayoutState localLayoutState = calculateLayoutState(
mLayoutLock,
mContext,
root,
widthSpec,
heightSpec,
mIsLayoutDiffingEnabled,
previousLayoutState != null ? previousLayoutState.getDiffTree() : null);
if (output != null) {
output.width = localLayoutState.getWidth();
output.height = localLayoutState.getHeight();
}
if (previousLayoutState != null) {
previousLayoutState.releaseRef();
previousLayoutState = null;
}
boolean layoutStateUpdated = false;
synchronized (this) {
// Make sure some other thread hasn't computed a compatible layout in the meantime.
if (!hasCompatibleComponentAndSpec()
&& isCompatibleSpec(localLayoutState, mWidthSpec, mHeightSpec)) {
if (localLayoutState != null) {
final StateHandler layoutStateStateHandler =
localLayoutState.consumeStateHandler();
if (layoutStateStateHandler != null) {
if (mStateHandler != null) { // we could have been released
mStateHandler.commit(layoutStateStateHandler);
}
ComponentsPools.release(layoutStateStateHandler);
}
}
// Set the new layout state, and remember the old layout state so we
// can release it.
LayoutState tmp = mBackgroundLayoutState;
mBackgroundLayoutState = localLayoutState;
localLayoutState = tmp;
layoutStateUpdated = true;
}
}
if (localLayoutState != null) {
localLayoutState.releaseRef();
localLayoutState = null;
}
if (layoutStateUpdated) {
postBackgroundLayoutStateUpdated();
}
logLayoutCalculationFinish(root);
}
private void logPreAllocationStart() {
final ComponentsLogger logger = mContext.getLogger();
if (logger != null) {
logger.eventStart(
EVENT_PRE_ALLOCATE_MOUNT_CONTENT,
this,
PARAM_LOG_TAG,
mContext.getLogTag());
}
}
private void logPreAllocationFinish() {
final ComponentsLogger logger = mContext.getLogger();
if (logger != null) {
logger.eventEnd(EVENT_PRE_ALLOCATE_MOUNT_CONTENT, this, ACTION_SUCCESS);
}
}
private void logLayoutCalculationStart(Component<?> root) {
final ComponentsLogger logger = mContext.getLogger();
if (logger == null) {
return;
}
logger.eventStart(EVENT_LAYOUT_CALCULATE, root, PARAM_LOG_TAG, mContext.getLogTag());
logger.eventAddParam(
EVENT_LAYOUT_CALCULATE,
root,
PARAM_TREE_DIFF_ENABLED,
String.valueOf(mIsLayoutDiffingEnabled));
logger.eventAddParam(
EVENT_LAYOUT_CALCULATE,
root,
PARAM_IS_BACKGROUND_LAYOUT,
String.valueOf(!ThreadUtils.isMainThread()));
}
private void logLayoutCalculationFinish(Component<?> root) {
final ComponentsLogger logger = mContext.getLogger();
if (logger != null) {
logger.eventEnd(EVENT_LAYOUT_CALCULATE, root, ACTION_SUCCESS);
}
}
/**
* Transfer mBackgroundLayoutState to mMainThreadLayoutState. This will proxy
* to the main thread if necessary. If the component/size-spec changes in the
* meantime, then the transfer will be aborted.
*/
private void postBackgroundLayoutStateUpdated() {
if (isMainThread()) {
// We need to possibly update mMainThreadLayoutState. This call will
// cause the host view to be invalidated and re-laid out, if necessary.
backgroundLayoutStateUpdated();
} else {
// If we aren't on the main thread, we send a message to the main thread
// to invoke backgroundLayoutStateUpdated.
sMainThreadHandler.obtainMessage(MESSAGE_WHAT_BACKGROUND_LAYOUT_STATE_UPDATED, this)
.sendToTarget();
}
}
/**
* The contract is that in order to release a ComponentTree, you must do so from the main
* thread, or guarantee that it will never be accessed from the main thread again. Usually
* HostView will handle releasing, but if you never attach to a host view, then you should call
* release yourself.
*/
public void release() {
LayoutState mainThreadLayoutState;
LayoutState backgroundLayoutState;
synchronized (this) {
if (mComponentView != null) {
mComponentView.setComponent(null);
}
mRoot = null;
mainThreadLayoutState = mMainThreadLayoutState;
mMainThreadLayoutState = null;
backgroundLayoutState = mBackgroundLayoutState;
mBackgroundLayoutState = null;
// TODO t15532529
mStateHandler = null;
}
if (mainThreadLayoutState != null) {
mainThreadLayoutState.releaseRef();
mainThreadLayoutState = null;
}
if (backgroundLayoutState != null) {
backgroundLayoutState.releaseRef();
backgroundLayoutState = null;
}
}
private boolean isCompatibleComponentAndSpec(LayoutState layoutState) {
assertHoldsLock(this);
return mRoot != null && isCompatibleComponentAndSpec(
layoutState, mRoot.getId(), mWidthSpec, mHeightSpec);
}
// Either the MainThreadLayout or the BackgroundThreadLayout is compatible with the current state.
private boolean hasCompatibleComponentAndSpec() {
assertHoldsLock(this);
return isCompatibleComponentAndSpec(mMainThreadLayoutState)
|| isCompatibleComponentAndSpec(mBackgroundLayoutState);
}
private boolean hasSizeSpec() {
assertHoldsLock(this);
return mWidthSpec != SIZE_UNINITIALIZED
&& mHeightSpec != SIZE_UNINITIALIZED;
}
private static synchronized Looper getDefaultLayoutThreadLooper() {
if (sDefaultLayoutThreadLooper == null) {
HandlerThread defaultThread =
new HandlerThread(DEFAULT_LAYOUT_THREAD_NAME, DEFAULT_LAYOUT_THREAD_PRIORITY);
defaultThread.start();
sDefaultLayoutThreadLooper = defaultThread.getLooper();
}
return sDefaultLayoutThreadLooper;
}
private static boolean isCompatibleSpec(
LayoutState layoutState, int widthSpec, int heightSpec) {
return layoutState != null
&& layoutState.isCompatibleSpec(widthSpec, heightSpec)
&& layoutState.isCompatibleAccessibility();
}
private static boolean isCompatibleComponentAndSpec(
LayoutState layoutState, int componentId, int widthSpec, int heightSpec) {
return layoutState != null
&& layoutState.isCompatibleComponentAndSpec(componentId, widthSpec, heightSpec)
&& layoutState.isCompatibleAccessibility();
}
private static boolean isCompatibleComponentAndSize(
LayoutState layoutState, int componentId, int width, int height) {
return layoutState != null
&& layoutState.isComponentId(componentId)
&& layoutState.isCompatibleSize(width, height)
&& layoutState.isCompatibleAccessibility();
}
public ComponentContext getContext() {
return mContext;
}
private static class ComponentMainThreadHandler extends Handler {
private ComponentMainThreadHandler() {
super(Looper.getMainLooper());
}
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_WHAT_BACKGROUND_LAYOUT_STATE_UPDATED:
ComponentTree that = (ComponentTree) msg.obj;
that.backgroundLayoutStateUpdated();
break;
default:
throw new IllegalArgumentException();
}
}
}
protected LayoutState calculateLayoutState(
@Nullable Object lock,
ComponentContext context,
Component<?> root,
int widthSpec,
int heightSpec,
boolean diffingEnabled,
@Nullable DiffNode diffNode) {
final ComponentContext contextWithStateHandler;
synchronized (this) {
contextWithStateHandler =
new ComponentContext(context, StateHandler.acquireNewInstance(mStateHandler));
}
if (lock != null) {
synchronized (lock) {
return LayoutState.calculate(
contextWithStateHandler,
root,
mId,
widthSpec,
heightSpec,
diffingEnabled,
diffNode);
}
} else {
return LayoutState.calculate(
contextWithStateHandler,
root,
mId,
widthSpec,
heightSpec,
diffingEnabled,
diffNode);
}
}
ComponentsStethoManager getStethoManager() {
return mStethoManager;
}
void setStethoManager(ComponentsStethoManager stethoManager) {
mStethoManager = stethoManager;
}
/**
* A default {@link LayoutHandler} that will use a {@link Handler} with a {@link Thread}'s
* {@link Looper}.
*/
private static class DefaultLayoutHandler extends Handler implements LayoutHandler {
private DefaultLayoutHandler(Looper threadLooper) {
super(threadLooper);
}
}
/**
* A builder class that can be used to create a {@link ComponentTree}.
*/
public static class Builder {
// required
private ComponentContext context;
private Component<?> root;
// optional
private boolean incrementalMountEnabled = true;
private boolean isLayoutDiffingEnabled;
private LayoutHandler layoutThreadHandler;
private Object layoutLock;
private StateHandler stateHandler;
private boolean asyncStateUpdates = true;
protected Builder() {
}
protected Builder(ComponentContext context, Component<?> root) {
init(context, root);
}
protected void init(ComponentContext context, Component<?> root) {
| src/main/java/com/facebook/components/ComponentTree.java | /**
* Copyright (c) 2014-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
package com.facebook.litho;
import javax.annotation.CheckReturnValue;
import javax.annotation.concurrent.GuardedBy;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import android.content.Context;
import android.content.ContextWrapper;
import android.graphics.Rect;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.os.Process;
import android.support.annotation.IntDef;
import android.support.annotation.Keep;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.VisibleForTesting;
import android.view.View;
import android.view.ViewParent;
import com.facebook.infer.annotation.ReturnsOwnership;
import static com.facebook.litho.ComponentLifecycle.StateUpdate;
import static com.facebook.litho.ComponentsLogger.ACTION_SUCCESS;
import static com.facebook.litho.ComponentsLogger.EVENT_LAYOUT_CALCULATE;
import static com.facebook.litho.ComponentsLogger.EVENT_PRE_ALLOCATE_MOUNT_CONTENT;
import static com.facebook.litho.ComponentsLogger.PARAM_IS_BACKGROUND_LAYOUT;
import static com.facebook.litho.ComponentsLogger.PARAM_LOG_TAG;
import static com.facebook.litho.ComponentsLogger.PARAM_TREE_DIFF_ENABLED;
import static com.facebook.litho.ThreadUtils.assertHoldsLock;
import static com.facebook.litho.ThreadUtils.assertMainThread;
import static com.facebook.litho.ThreadUtils.isMainThread;
/**
* Represents a tree of components and controls their life cycle. ComponentTree takes in a single
* root component and recursively invokes its OnCreateLayout to create a tree of components.
* ComponentTree is responsible for refreshing the mounted state of a component with new props.
*
* The usual use case for {@link ComponentTree} is:
* <code>
* ComponentTree component = ComponentTree.create(context, MyComponent.create());
* myHostView.setRoot(component);
* <code/>
*/
public class ComponentTree {
private static final String TAG = ComponentTree.class.getSimpleName();
private static final int SIZE_UNINITIALIZED = -1;
// MainThread Looper messages:
private static final int MESSAGE_WHAT_BACKGROUND_LAYOUT_STATE_UPDATED = 1;
private static final String DEFAULT_LAYOUT_THREAD_NAME = "ComponentLayoutThread";
private static final int DEFAULT_LAYOUT_THREAD_PRIORITY = Process.THREAD_PRIORITY_BACKGROUND;
private static final int SCHEDULE_NONE = 0;
private static final int SCHEDULE_LAYOUT_ASYNC = 1;
private static final int SCHEDULE_LAYOUT_SYNC = 2;
private ComponentsStethoManager mStethoManager;
@IntDef({SCHEDULE_NONE, SCHEDULE_LAYOUT_ASYNC, SCHEDULE_LAYOUT_SYNC})
@Retention(RetentionPolicy.SOURCE)
private @interface PendingLayoutCalculation {}
private static final AtomicInteger sIdGenerator = new AtomicInteger(0);
private static final Handler sMainThreadHandler = new ComponentMainThreadHandler();
// Do not access sDefaultLayoutThreadLooper directly, use getDefaultLayoutThreadLooper().
@GuardedBy("ComponentTree.class")
private static volatile Looper sDefaultLayoutThreadLooper;
// Helpers to track view visibility when we are incrementally
// mounting and partially invalidating
private static final int[] sCurrentLocation = new int[2];
private static final int[] sParentLocation = new int[2];
private static final Rect sParentBounds = new Rect();
private final Runnable mCalculateLayoutRunnable = new Runnable() {
@Override
public void run() {
calculateLayout(null);
}
};
private final ComponentContext mContext;
// These variables are only accessed from the main thread.
private boolean mIsMounting;
private boolean mIncrementalMountEnabled;
private boolean mIsLayoutDiffingEnabled;
private boolean mIsAttached;
private boolean mIsAsyncUpdateStateEnabled;
private ComponentView mComponentView;
private LayoutHandler mLayoutThreadHandler;
@GuardedBy("this")
private boolean mHasViewMeasureSpec;
// TODO(6606683): Enable recycling of mComponent.
// We will need to ensure there are no background threads referencing mComponent. We'll need
// to keep a reference count or something. :-/
@GuardedBy("this")
private Component<?> mRoot;
@GuardedBy("this")
private int mWidthSpec = SIZE_UNINITIALIZED;
@GuardedBy("this")
private int mHeightSpec = SIZE_UNINITIALIZED;
// This is written to only by the main thread with the lock held, read from the main thread with
// no lock held, or read from any other thread with the lock held.
private LayoutState mMainThreadLayoutState;
// The semantics here are tricky. Whenever you transfer mBackgroundLayoutState to a local that
// will be accessed outside of the lock, you must set mBackgroundLayoutState to null to ensure
// that the current thread alone has access to the LayoutState, which is single-threaded.
@GuardedBy("this")
private LayoutState mBackgroundLayoutState;
@GuardedBy("this")
private StateHandler mStateHandler;
private Object mLayoutLock;
protected final int mId = sIdGenerator.getAndIncrement();
@GuardedBy("this")
private boolean mIsMeasuring;
@GuardedBy("this")
private @PendingLayoutCalculation int mScheduleLayoutAfterMeasure;
public static Builder create(ComponentContext context, Component.Builder<?> root) {
return create(context, root.build());
}
public static Builder create(ComponentContext context, Component<?> root) {
return ComponentsPools.acquireComponentTreeBuilder(context, root);
}
protected ComponentTree(Builder builder) {
mContext = ComponentContext.withComponentTree(builder.context, this);
mRoot = builder.root;
mIncrementalMountEnabled = builder.incrementalMountEnabled;
mIsLayoutDiffingEnabled = builder.isLayoutDiffingEnabled;
mLayoutThreadHandler = builder.layoutThreadHandler;
mLayoutLock = builder.layoutLock;
mIsAsyncUpdateStateEnabled = builder.asyncStateUpdates;
if (mLayoutThreadHandler == null) {
mLayoutThreadHandler = new DefaultLayoutHandler(getDefaultLayoutThreadLooper());
}
final StateHandler builderStateHandler = builder.stateHandler;
mStateHandler = builderStateHandler == null
? StateHandler.acquireNewInstance(null)
: builderStateHandler;
}
LayoutState getMainThreadLayoutState() {
return mMainThreadLayoutState;
}
@VisibleForTesting
protected LayoutState getBackgroundLayoutState() {
return mBackgroundLayoutState;
}
/**
* Picks the best LayoutState and sets it in mMainThreadLayoutState. The return value
* is a LayoutState that must be released (after the lock is released). This
* awkward contract is necessary to ensure thread-safety.
*/
@CheckReturnValue
@ReturnsOwnership
private LayoutState setBestMainThreadLayoutAndReturnOldLayout() {
assertHoldsLock(this);
// If everything matches perfectly then we prefer mMainThreadLayoutState
// because that means we don't need to remount.
boolean isMainThreadLayoutBest;
if (isCompatibleComponentAndSpec(mMainThreadLayoutState)) {
isMainThreadLayoutBest = true;
} else if (isCompatibleSpec(mBackgroundLayoutState, mWidthSpec, mHeightSpec)
|| !isCompatibleSpec(mMainThreadLayoutState, mWidthSpec, mHeightSpec)) {
// If mMainThreadLayoutState isn't a perfect match, we'll prefer
// mBackgroundLayoutState since it will have the more recent create.
isMainThreadLayoutBest = false;
} else {
// If the main thread layout is still compatible size-wise, and the
// background one is not, then we'll do nothing. We want to keep the same
// main thread layout so that we don't force main thread re-layout.
isMainThreadLayoutBest = true;
}
if (isMainThreadLayoutBest) {
// We don't want to hold onto mBackgroundLayoutState since it's unlikely
// to ever be used again. We return mBackgroundLayoutState to indicate it
// should be released after exiting the lock.
LayoutState toRelease = mBackgroundLayoutState;
mBackgroundLayoutState = null;
return toRelease;
} else {
// Since we are changing layout states we'll need to remount.
if (mComponentView != null) {
mComponentView.setMountStateDirty();
}
LayoutState toRelease = mMainThreadLayoutState;
mMainThreadLayoutState = mBackgroundLayoutState;
mBackgroundLayoutState = null;
return toRelease;
}
}
private void backgroundLayoutStateUpdated() {
assertMainThread();
// If we aren't attached, then we have nothing to do. We'll handle
// everything in onAttach.
if (!mIsAttached) {
return;
}
LayoutState toRelease;
boolean layoutStateUpdated;
int componentRootId;
synchronized (this) {
if (mRoot == null) {
// We have been released. Abort.
return;
}
LayoutState oldMainThreadLayoutState = mMainThreadLayoutState;
toRelease = setBestMainThreadLayoutAndReturnOldLayout();
layoutStateUpdated = (mMainThreadLayoutState != oldMainThreadLayoutState);
componentRootId = mRoot.getId();
}
if (toRelease != null) {
toRelease.releaseRef();
toRelease = null;
}
if (!layoutStateUpdated) {
return;
}
// We defer until measure if we don't yet have a width/height
int viewWidth = mComponentView.getMeasuredWidth();
int viewHeight = mComponentView.getMeasuredHeight();
if (viewWidth == 0 && viewHeight == 0) {
// The host view has not been measured yet.
return;
}
final boolean needsAndroidLayout =
!isCompatibleComponentAndSize(
mMainThreadLayoutState,
componentRootId,
viewWidth,
viewHeight);
if (needsAndroidLayout) {
mComponentView.requestLayout();
} else {
mountComponentIfDirty();
}
}
void attach() {
assertMainThread();
if (mComponentView == null) {
throw new IllegalStateException("Trying to attach a ComponentTree without a set View");
}
LayoutState toRelease;
int componentRootId;
synchronized (this) {
// We need to track that we are attached regardless...
mIsAttached = true;
// ... and then we do state transfer
toRelease = setBestMainThreadLayoutAndReturnOldLayout();
componentRootId = mRoot.getId();
}
if (toRelease != null) {
toRelease.releaseRef();
toRelease = null;
}
// We defer until measure if we don't yet have a width/height
int viewWidth = mComponentView.getMeasuredWidth();
int viewHeight = mComponentView.getMeasuredHeight();
if (viewWidth == 0 && viewHeight == 0) {
// The host view has not been measured yet.
return;
}
final boolean needsAndroidLayout =
!isCompatibleComponentAndSize(
mMainThreadLayoutState,
componentRootId,
viewWidth,
viewHeight);
if (needsAndroidLayout || mComponentView.isMountStateDirty()) {
mComponentView.requestLayout();
} else {
mComponentView.rebind();
}
}
private static boolean hasSameBaseContext(Context context1, Context context2) {
return getBaseContext(context1) == getBaseContext(context2);
}
private static Context getBaseContext(Context context) {
Context baseContext = context;
while (baseContext instanceof ContextWrapper) {
baseContext = ((ContextWrapper) baseContext).getBaseContext();
}
return baseContext;
}
boolean isMounting() {
return mIsMounting;
}
private boolean mountComponentIfDirty() {
if (mComponentView.isMountStateDirty()) {
if (mIncrementalMountEnabled) {
incrementalMountComponent();
} else {
mountComponent(null);
}
return true;
}
return false;
}
void incrementalMountComponent() {
assertMainThread();
if (!mIncrementalMountEnabled) {
throw new IllegalStateException("Calling incrementalMountComponent() but incremental mount" +
" is not enabled");
}
// Per ComponentTree visible area. Because ComponentViews can be nested and mounted
// not in "depth order", this variable cannot be static.
final Rect currentVisibleArea = ComponentsPools.acquireRect();
if (getVisibleRect(currentVisibleArea)) {
mountComponent(currentVisibleArea);
}
// if false: no-op, doesn't have visible area, is not ready or not attached
ComponentsPools.release(currentVisibleArea);
}
private boolean getVisibleRect(Rect visibleBounds) {
assertMainThread();
getLocationAndBoundsOnScreen(mComponentView, sCurrentLocation, visibleBounds);
final ViewParent viewParent = mComponentView.getParent();
if (viewParent instanceof View) {
View parent = (View) viewParent;
getLocationAndBoundsOnScreen(parent, sParentLocation, sParentBounds);
if (!visibleBounds.setIntersect(visibleBounds, sParentBounds)) {
return false;
}
}
visibleBounds.offset(-sCurrentLocation[0], -sCurrentLocation[1]);
return true;
}
private static void getLocationAndBoundsOnScreen(View view, int[] location, Rect bounds) {
assertMainThread();
view.getLocationOnScreen(location);
bounds.set(
location[0],
location[1],
location[0] + view.getWidth(),
location[1] + view.getHeight());
}
void mountComponent(Rect currentVisibleArea) {
assertMainThread();
mIsMounting = true;
// currentVisibleArea null or empty => mount all
mComponentView.mount(mMainThreadLayoutState, currentVisibleArea);
mIsMounting = false;
}
void detach() {
assertMainThread();
synchronized (this) {
mIsAttached = false;
mHasViewMeasureSpec = false;
}
}
/**
* Set a new ComponentView to this ComponentTree checking that they have the same context and
* clear the ComponentTree reference from the previous ComponentView if any.
* Be sure this ComponentTree is detach first.
*/
void setComponentView(@NonNull ComponentView view) {
assertMainThread();
// It's possible that the view associated with this ComponentTree was recycled but was
// never detached. In all cases we have to make sure that the old references between
// componentView and componentTree are reset.
if (mIsAttached) {
if (mComponentView != null) {
mComponentView.setComponent(null);
} else {
detach();
}
} else if (mComponentView != null) {
// Remove the ComponentTree reference from a previous view if any.
mComponentView.clearComponentTree();
}
if (!hasSameBaseContext(view.getContext(), mContext)) {
// This would indicate bad things happening, like leaking a context.
throw new IllegalArgumentException(
"Base view context differs, view context is: " + view.getContext() +
", ComponentTree context is: " + mContext);
}
mComponentView = view;
}
void clearComponentView() {
assertMainThread();
// Crash if the ComponentTree is mounted to a view.
if (mIsAttached) {
throw new IllegalStateException(
"Clearing the ComponentView while the ComponentTree is attached");
}
mComponentView = null;
}
void measure(int widthSpec, int heightSpec, int[] measureOutput, boolean forceLayout) {
assertMainThread();
Component component = null;
LayoutState toRelease;
synchronized (this) {
mIsMeasuring = true;
// This widthSpec/heightSpec is fixed until the view gets detached.
mWidthSpec = widthSpec;
mHeightSpec = heightSpec;
mHasViewMeasureSpec = true;
toRelease = setBestMainThreadLayoutAndReturnOldLayout();
if (forceLayout || !isCompatibleComponentAndSpec(mMainThreadLayoutState)) {
// Neither layout was compatible and we have to perform a layout.
// Since outputs get set on the same object during the lifecycle calls,
// we need to copy it in order to use it concurrently.
component = mRoot.makeShallowCopy();
}
}
if (toRelease != null) {
toRelease.releaseRef();
toRelease = null;
}
if (component != null) {
// TODO: We should re-use the existing CSSNodeDEPRECATED tree instead of re-creating it.
if (mMainThreadLayoutState != null) {
// It's beneficial to delete the old layout state before we start creating a new one since
// we'll be able to re-use some of the layout nodes.
LayoutState localLayoutState;
synchronized (this) {
localLayoutState = mMainThreadLayoutState;
mMainThreadLayoutState = null;
}
localLayoutState.releaseRef();
}
// We have no layout that matches the given spec, so we need to compute it on the main thread.
LayoutState localLayoutState = calculateLayoutState(
mLayoutLock,
mContext,
component,
widthSpec,
heightSpec,
mIsLayoutDiffingEnabled,
null);
final StateHandler layoutStateStateHandler =
localLayoutState.consumeStateHandler();
synchronized (this) {
if (layoutStateStateHandler != null) {
mStateHandler.commit(layoutStateStateHandler);
ComponentsPools.release(layoutStateStateHandler);
}
mMainThreadLayoutState = localLayoutState;
localLayoutState = null;
}
// We need to force remount on layout
mComponentView.setMountStateDirty();
}
measureOutput[0] = mMainThreadLayoutState.getWidth();
measureOutput[1] = mMainThreadLayoutState.getHeight();
int layoutScheduleType = SCHEDULE_NONE;
Component root = null;
synchronized (this) {
mIsMeasuring = false;
if (mScheduleLayoutAfterMeasure != SCHEDULE_NONE) {
layoutScheduleType = mScheduleLayoutAfterMeasure;
mScheduleLayoutAfterMeasure = SCHEDULE_NONE;
root = mRoot.makeShallowCopy();
}
}
if (layoutScheduleType != SCHEDULE_NONE) {
setRootAndSizeSpecInternal(
root,
SIZE_UNINITIALIZED,
SIZE_UNINITIALIZED,
layoutScheduleType == SCHEDULE_LAYOUT_ASYNC,
null /*output */);
}
}
/**
* Returns {@code true} if the layout call mounted the component.
*/
boolean layout() {
assertMainThread();
return mountComponentIfDirty();
}
/**
* Returns whether incremental mount is enabled or not in this component.
*/
public boolean isIncrementalMountEnabled() {
return mIncrementalMountEnabled;
}
synchronized Component getRoot() {
return mRoot;
}
/**
* Update the root component. This can happen in both attached and detached states. In each case
* we will run a layout and then proxy a message to the main thread to cause a
* relayout/invalidate.
*/
public void setRoot(Component<?> rootComponent) {
if (rootComponent == null) {
throw new IllegalArgumentException("Root component can't be null");
}
setRootAndSizeSpecInternal(
rootComponent,
SIZE_UNINITIALIZED,
SIZE_UNINITIALIZED,
false /* isAsync */,
null /* output */);
}
public void preAllocateMountContent() {
assertMainThread();
final LayoutState toPrePopulate;
if (mMainThreadLayoutState != null) {
toPrePopulate = mMainThreadLayoutState.acquireRef();
} else {
synchronized (this) {
toPrePopulate = mBackgroundLayoutState;
if (toPrePopulate == null) {
return;
}
toPrePopulate.acquireRef();
}
}
logPreAllocationStart();
toPrePopulate.preAllocateMountContent();
logPreAllocationFinish();
toPrePopulate.releaseRef();
}
public void setRootAsync(Component<?> rootComponent) {
if (rootComponent == null) {
throw new IllegalArgumentException("Root component can't be null");
}
setRootAndSizeSpecInternal(
rootComponent,
SIZE_UNINITIALIZED,
SIZE_UNINITIALIZED,
true /* isAsync */,
null /* output */);
}
synchronized void updateStateLazy(String componentKey, StateUpdate stateUpdate) {
if (mRoot == null) {
return;
}
mStateHandler.queueStateUpdate(componentKey, stateUpdate);
}
void updateState(String componentKey, StateUpdate stateUpdate) {
updateStateInternal(componentKey, stateUpdate, false);
}
void updateStateAsync(String componentKey, StateUpdate stateUpdate) {
if (!mIsAsyncUpdateStateEnabled) {
throw new RuntimeException("Triggering async state updates on this component tree is " +
"disabled, use sync state updates.");
}
updateStateInternal(componentKey, stateUpdate, true);
}
void updateStateInternal(String key, StateUpdate stateUpdate, boolean isAsync) {
final Component<?> root;
synchronized (this) {
if (mRoot == null) {
return;
}
mStateHandler.queueStateUpdate(key, stateUpdate);
if (mIsMeasuring) {
// If the layout calculation was already scheduled to happen synchronously let's just go
// with a sync layout calculation.
if (mScheduleLayoutAfterMeasure == SCHEDULE_LAYOUT_SYNC) {
return;
}
mScheduleLayoutAfterMeasure = isAsync ? SCHEDULE_LAYOUT_ASYNC : SCHEDULE_LAYOUT_SYNC;
return;
}
root = mRoot.makeShallowCopy();
}
setRootAndSizeSpecInternal(
root,
SIZE_UNINITIALIZED,
SIZE_UNINITIALIZED,
isAsync,
null /*output */);
}
/**
* Update the width/height spec. This is useful if you are currently detached and are responding
* to a configuration change. If you are currently attached then the HostView is the source of
* truth for width/height, so this call will be ignored.
*/
public void setSizeSpec(int widthSpec, int heightSpec) {
setSizeSpec(widthSpec, heightSpec, null);
}
/**
* Same as {@link #setSizeSpec(int, int)} but fetches the resulting width/height
* in the given {@link Size}.
*/
public void setSizeSpec(int widthSpec, int heightSpec, Size output) {
setRootAndSizeSpecInternal(
null,
widthSpec,
heightSpec,
false /* isAsync */,
output /* output */);
}
public void setSizeSpecAsync(int widthSpec, int heightSpec) {
setRootAndSizeSpecInternal(
null,
widthSpec,
heightSpec,
true /* isAsync */,
null /* output */);
}
/**
* Compute asynchronously a new layout with the given component root and sizes
*/
public void setRootAndSizeSpecAsync(Component<?> root, int widthSpec, int heightSpec) {
if (root == null) {
throw new IllegalArgumentException("Root component can't be null");
}
setRootAndSizeSpecInternal(
root,
widthSpec,
heightSpec,
true /* isAsync */,
null /* output */);
}
/**
* Compute a new layout with the given component root and sizes
*/
public void setRootAndSizeSpec(Component<?> root, int widthSpec, int heightSpec) {
if (root == null) {
throw new IllegalArgumentException("Root component can't be null");
}
setRootAndSizeSpecInternal(
root,
widthSpec,
heightSpec,
false /* isAsync */,
null /* output */);
}
public void setRootAndSizeSpec(Component<?> root, int widthSpec, int heightSpec, Size output) {
if (root == null) {
throw new IllegalArgumentException("Root component can't be null");
}
setRootAndSizeSpecInternal(
root,
widthSpec,
heightSpec,
false /* isAsync */,
output);
}
/**
* @return the {@link ComponentView} associated with this ComponentTree if any.
*/
@Keep
@Nullable
public ComponentView getComponentView() {
assertMainThread();
return mComponentView;
}
/**
* Provides a new instance from the StateHandler pool that is initialized with the information
* from the StateHandler currently held by the ComponentTree. Once the state updates have been
* applied and we are back in the main thread the state handler gets released to the pool.
* @return a copy of the state handler instance held by ComponentTree.
*/
public synchronized StateHandler getStateHandler() {
return StateHandler.acquireNewInstance(mStateHandler);
}
private void setRootAndSizeSpecInternal(
Component<?> root,
int widthSpec,
int heightSpec,
boolean isAsync,
Size output) {
synchronized (this) {
final Map<String, List<StateUpdate>> pendingStateUpdates =
mStateHandler.getPendingStateUpdates();
if (pendingStateUpdates != null && pendingStateUpdates.size() > 0 && root != null) {
root = root.makeShallowCopyWithNewId();
}
final boolean rootInitialized = root != null;
final boolean widthSpecInitialized = widthSpec != SIZE_UNINITIALIZED;
final boolean heightSpecInitialized = heightSpec != SIZE_UNINITIALIZED;
if (mHasViewMeasureSpec && !rootInitialized) {
// It doesn't make sense to specify the width/height while the HostView is attached and it
// has been measured. We do not throw an Exception only because there can be race conditions
// that can cause this to happen. In such race conditions, ignoring the setSizeSpec call is
// the right thing to do.
return;
}
final boolean widthSpecDidntChange = !widthSpecInitialized || widthSpec == mWidthSpec;
final boolean heightSpecDidntChange = !heightSpecInitialized || heightSpec == mHeightSpec;
final boolean sizeSpecDidntChange = widthSpecDidntChange && heightSpecDidntChange;
final LayoutState mostRecentLayoutState =
mBackgroundLayoutState != null ? mBackgroundLayoutState : mMainThreadLayoutState;
final boolean allSpecsWereInitialized =
widthSpecInitialized &&
heightSpecInitialized &&
mWidthSpec != SIZE_UNINITIALIZED &&
mHeightSpec != SIZE_UNINITIALIZED;
final boolean sizeSpecsAreCompatible =
sizeSpecDidntChange ||
(allSpecsWereInitialized &&
mostRecentLayoutState != null &&
LayoutState.hasCompatibleSizeSpec(
mWidthSpec,
mHeightSpec,
widthSpec,
heightSpec,
mostRecentLayoutState.getWidth(),
mostRecentLayoutState.getHeight()));
final boolean rootDidntChange = !rootInitialized || root.getId() == mRoot.getId();
if (rootDidntChange && sizeSpecsAreCompatible) {
// The spec and the root haven't changed. Either we have a layout already, or we're
// currently computing one on another thread.
if (output != null) {
output.height = mostRecentLayoutState.getHeight();
output.width = mostRecentLayoutState.getWidth();
}
return;
}
if (widthSpecInitialized) {
mWidthSpec = widthSpec;
}
if (heightSpecInitialized) {
mHeightSpec = heightSpec;
}
if (rootInitialized) {
mRoot = root;
}
}
if (isAsync && output != null) {
throw new IllegalArgumentException("The layout can't be calculated asynchronously if" +
" we need the Size back");
} else if (isAsync) {
mLayoutThreadHandler.removeCallbacks(mCalculateLayoutRunnable);
mLayoutThreadHandler.post(mCalculateLayoutRunnable);
} else {
calculateLayout(output);
}
}
/**
* Calculates the layout.
* @param output a destination where the size information should be saved
*/
private void calculateLayout(Size output) {
int widthSpec;
int heightSpec;
Component<?> root;
LayoutState previousLayoutState = null;
// Cancel any scheduled requests we might have in the background queue since we are starting
// a new layout computation.
mLayoutThreadHandler.removeCallbacksAndMessages(null);
synchronized (this) {
// Can't compute a layout if specs or root are missing
if (!hasSizeSpec() || mRoot == null) {
return;
}
// Check if we already have a compatible layout.
if (hasCompatibleComponentAndSpec()) {
if (output != null) {
final LayoutState mostRecentLayoutState =
mBackgroundLayoutState != null ? mBackgroundLayoutState : mMainThreadLayoutState;
output.width = mostRecentLayoutState.getWidth();
output.height = mostRecentLayoutState.getHeight();
}
return;
}
widthSpec = mWidthSpec;
heightSpec = mHeightSpec;
root = mRoot.makeShallowCopy();
if (mMainThreadLayoutState != null) {
previousLayoutState = mMainThreadLayoutState.acquireRef();
}
}
logLayoutCalculationStart(root);
LayoutState localLayoutState = calculateLayoutState(
mLayoutLock,
mContext,
root,
widthSpec,
heightSpec,
mIsLayoutDiffingEnabled,
previousLayoutState != null ? previousLayoutState.getDiffTree() : null);
if (output != null) {
output.width = localLayoutState.getWidth();
output.height = localLayoutState.getHeight();
}
if (previousLayoutState != null) {
previousLayoutState.releaseRef();
previousLayoutState = null;
}
boolean layoutStateUpdated = false;
synchronized (this) {
// Make sure some other thread hasn't computed a compatible layout in the meantime.
if (!hasCompatibleComponentAndSpec()
&& isCompatibleSpec(localLayoutState, mWidthSpec, mHeightSpec)) {
if (localLayoutState != null) {
final StateHandler layoutStateStateHandler =
localLayoutState.consumeStateHandler();
if (layoutStateStateHandler != null) {
if (mStateHandler != null) { // we could have been released
mStateHandler.commit(layoutStateStateHandler);
}
ComponentsPools.release(layoutStateStateHandler);
}
}
// Set the new layout state, and remember the old layout state so we
// can release it.
LayoutState tmp = mBackgroundLayoutState;
mBackgroundLayoutState = localLayoutState;
localLayoutState = tmp;
layoutStateUpdated = true;
}
}
if (localLayoutState != null) {
localLayoutState.releaseRef();
localLayoutState = null;
}
if (layoutStateUpdated) {
postBackgroundLayoutStateUpdated();
}
logLayoutCalculationFinish(root);
}
private void logPreAllocationStart() {
final ComponentsLogger logger = mContext.getLogger();
if (logger != null) {
logger.eventStart(
EVENT_PRE_ALLOCATE_MOUNT_CONTENT,
this,
PARAM_LOG_TAG,
mContext.getLogTag());
}
}
private void logPreAllocationFinish() {
final ComponentsLogger logger = mContext.getLogger();
if (logger != null) {
logger.eventEnd(EVENT_PRE_ALLOCATE_MOUNT_CONTENT, this, ACTION_SUCCESS);
}
}
private void logLayoutCalculationStart(Component<?> root) {
final ComponentsLogger logger = mContext.getLogger();
if (logger == null) {
return;
}
logger.eventStart(EVENT_LAYOUT_CALCULATE, root, PARAM_LOG_TAG, mContext.getLogTag());
logger.eventAddParam(
EVENT_LAYOUT_CALCULATE,
root,
PARAM_TREE_DIFF_ENABLED,
String.valueOf(mIsLayoutDiffingEnabled));
logger.eventAddParam(
EVENT_LAYOUT_CALCULATE,
root,
PARAM_IS_BACKGROUND_LAYOUT,
String.valueOf(!ThreadUtils.isMainThread()));
}
private void logLayoutCalculationFinish(Component<?> root) {
final ComponentsLogger logger = mContext.getLogger();
if (logger != null) {
logger.eventEnd(EVENT_LAYOUT_CALCULATE, root, ACTION_SUCCESS);
}
}
/**
* Transfer mBackgroundLayoutState to mMainThreadLayoutState. This will proxy
* to the main thread if necessary. If the component/size-spec changes in the
* meantime, then the transfer will be aborted.
*/
private void postBackgroundLayoutStateUpdated() {
if (isMainThread()) {
// We need to possibly update mMainThreadLayoutState. This call will
// cause the host view to be invalidated and re-laid out, if necessary.
backgroundLayoutStateUpdated();
} else {
// If we aren't on the main thread, we send a message to the main thread
// to invoke backgroundLayoutStateUpdated.
sMainThreadHandler.obtainMessage(MESSAGE_WHAT_BACKGROUND_LAYOUT_STATE_UPDATED, this)
.sendToTarget();
}
}
/**
* The contract is that in order to release a ComponentTree, you must do so from the main
* thread, or guarantee that it will never be accessed from the main thread again. Usually
* HostView will handle releasing, but if you never attach to a host view, then you should call
* release yourself.
*/
public void release() {
LayoutState mainThreadLayoutState;
LayoutState backgroundLayoutState;
synchronized (this) {
if (mComponentView != null) {
mComponentView.setComponent(null);
}
mRoot = null;
mainThreadLayoutState = mMainThreadLayoutState;
mMainThreadLayoutState = null;
backgroundLayoutState = mBackgroundLayoutState;
mBackgroundLayoutState = null;
// TODO t15532529
mStateHandler = null;
}
if (mainThreadLayoutState != null) {
mainThreadLayoutState.releaseRef();
mainThreadLayoutState = null;
}
if (backgroundLayoutState != null) {
backgroundLayoutState.releaseRef();
backgroundLayoutState = null;
}
}
private boolean isCompatibleComponentAndSpec(LayoutState layoutState) {
assertHoldsLock(this);
return mRoot != null && isCompatibleComponentAndSpec(
layoutState, mRoot.getId(), mWidthSpec, mHeightSpec);
}
// Either the MainThreadLayout or the BackgroundThreadLayout is compatible with the current state.
private boolean hasCompatibleComponentAndSpec() {
assertHoldsLock(this);
return isCompatibleComponentAndSpec(mMainThreadLayoutState)
|| isCompatibleComponentAndSpec(mBackgroundLayoutState);
}
private boolean hasSizeSpec() {
assertHoldsLock(this);
return mWidthSpec != SIZE_UNINITIALIZED
&& mHeightSpec != SIZE_UNINITIALIZED;
}
private static synchronized Looper getDefaultLayoutThreadLooper() {
if (sDefaultLayoutThreadLooper == null) {
HandlerThread defaultThread =
new HandlerThread(DEFAULT_LAYOUT_THREAD_NAME, DEFAULT_LAYOUT_THREAD_PRIORITY);
defaultThread.start();
sDefaultLayoutThreadLooper = defaultThread.getLooper();
}
return sDefaultLayoutThreadLooper;
}
private static boolean isCompatibleSpec(
LayoutState layoutState, int widthSpec, int heightSpec) {
return layoutState != null
&& layoutState.isCompatibleSpec(widthSpec, heightSpec)
&& layoutState.isCompatibleAccessibility();
}
private static boolean isCompatibleComponentAndSpec(
LayoutState layoutState, int componentId, int widthSpec, int heightSpec) {
return layoutState != null
&& layoutState.isCompatibleComponentAndSpec(componentId, widthSpec, heightSpec)
&& layoutState.isCompatibleAccessibility();
}
private static boolean isCompatibleComponentAndSize(
LayoutState layoutState, int componentId, int width, int height) {
return layoutState != null
&& layoutState.isComponentId(componentId)
&& layoutState.isCompatibleSize(width, height)
&& layoutState.isCompatibleAccessibility();
}
public ComponentContext getContext() {
return mContext;
}
private static class ComponentMainThreadHandler extends Handler {
private ComponentMainThreadHandler() {
super(Looper.getMainLooper());
}
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_WHAT_BACKGROUND_LAYOUT_STATE_UPDATED:
ComponentTree that = (ComponentTree) msg.obj;
that.backgroundLayoutStateUpdated();
break;
default:
throw new IllegalArgumentException();
}
}
}
protected LayoutState calculateLayoutState(
@Nullable Object lock,
ComponentContext context,
Component<?> root,
int widthSpec,
int heightSpec,
boolean diffingEnabled,
@Nullable DiffNode diffNode) {
final ComponentContext contextWithStateHandler;
synchronized (this) {
contextWithStateHandler =
new ComponentContext(context, StateHandler.acquireNewInstance(mStateHandler));
}
if (lock != null) {
synchronized (lock) {
return LayoutState.calculate(
contextWithStateHandler,
root,
mId,
widthSpec,
heightSpec,
diffingEnabled,
diffNode);
}
} else {
return LayoutState.calculate(
contextWithStateHandler,
root,
mId,
widthSpec,
heightSpec,
diffingEnabled,
diffNode);
}
}
ComponentsStethoManager getStethoManager() {
return mStethoManager;
}
void setStethoManager(ComponentsStethoManager stethoManager) {
mStethoManager = stethoManager;
}
/**
* A default {@link LayoutHandler} that will use a {@link Handler} with a {@link Thread}'s
* {@link Looper}.
*/
private static class DefaultLayoutHandler extends Handler implements LayoutHandler {
private DefaultLayoutHandler(Looper threadLooper) {
super(threadLooper);
}
}
/**
* A builder class that can be used to create a {@link ComponentTree}.
*/
public static class Builder {
// required
private ComponentContext context;
private Component<?> root;
// optional
private boolean incrementalMountEnabled = true;
private boolean isLayoutDiffingEnabled;
private LayoutHandler layoutThreadHandler;
private Object layoutLock;
private StateHandler stateHandler;
private boolean asyncStateUpdates = true;
protected Builder() {
}
protected Builder(ComponentContext context, Component<?> root) {
init(context, root);
}
| Lines authored by emilsj
This commit forms part of the blame-preserving initial commit suite.
| src/main/java/com/facebook/components/ComponentTree.java | Lines authored by emilsj | <ide><path>rc/main/java/com/facebook/components/ComponentTree.java
<ide> init(context, root);
<ide> }
<ide>
<add> protected void init(ComponentContext context, Component<?> root) { |
|
Java | apache-2.0 | 29c99e8a03d0143a975be7cbd8d2c5d8e1d0620b | 0 | hongsudt/server,HaiJiaoXinHeng/server-1,hongsudt/server,HaiJiaoXinHeng/server-1,hongsudt/server,HaiJiaoXinHeng/server-1 | package org.ohmage.query.impl;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.MappingJsonFactory;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.format.ISODateTimeFormat;
import org.ohmage.domain.DataStream;
import org.ohmage.domain.DataStream.MetaData;
import org.ohmage.domain.Location;
import org.ohmage.domain.Observer;
import org.ohmage.domain.Observer.Stream;
import org.ohmage.exception.DataAccessException;
import org.ohmage.exception.DomainException;
import org.ohmage.query.IObserverQueries;
import org.ohmage.service.ObserverServices.InvalidPoint;
import org.ohmage.util.StringUtils;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.SingleColumnRowMapper;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionException;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
/**
* This class is responsible for creating, reading, updating, and deleting
* probe information.
*
* @author John Jenkins
*/
public class ObserverQueries extends Query implements IObserverQueries {
/**
* Creates this object via dependency injection (reflection).
*
* @param dataSource
* The DataSource to use when querying the database.
*/
private ObserverQueries(DataSource dataSource) {
super(dataSource);
}
/*
* (non-Javadoc)
*
* @see org.ohmage.query.IObserverQueries#createProbe(org.ohmage.domain.Observer)
*/
@Override
public void createObserver(
final String username,
final Observer observer)
throws DataAccessException {
if(username == null) {
throw new DataAccessException("The username is null.");
}
if(observer == null) {
throw new DataAccessException("The observer is null.");
}
// Create the transaction.
DefaultTransactionDefinition def = new DefaultTransactionDefinition();
def.setName("Creating an observer.");
try {
// Begin the transaction.
PlatformTransactionManager transactionManager =
new DataSourceTransactionManager(getDataSource());
TransactionStatus status = transactionManager.getTransaction(def);
// Observer creation SQL.
final String observerSql =
"INSERT INTO observer (" +
"observer_id, " +
"version, " +
"name, " +
"description, " +
"version_string, " +
"user_id) " +
"VALUES (?, ?, ?, ?, ?, " +
"(SELECT id FROM user WHERE username = ?))";
// Observer creation statement with parameters.
PreparedStatementCreator observerCreator =
new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(
final Connection connection)
throws SQLException {
PreparedStatement ps =
connection.prepareStatement(
observerSql,
new String[] { "id" });
ps.setString(1, observer.getId());
ps.setLong(2, observer.getVersion());
ps.setString(3, observer.getName());
ps.setString(4, observer.getDescription());
ps.setString(5, observer.getVersionString());
ps.setString(6, username);
return ps;
}
};
// The auto-generated key for the observer.
KeyHolder observerKeyHolder = new GeneratedKeyHolder();
// Create the observer.
try {
getJdbcTemplate().update(observerCreator, observerKeyHolder);
}
catch(org.springframework.dao.DataAccessException e) {
transactionManager.rollback(status);
throw new DataAccessException(
"Error executing SQL '" +
observerSql +
"' with parameters: " +
observer.getId() + ", " +
observer.getVersion() + ", " +
observer.getName() + ", " +
observer.getDescription() + ", " +
observer.getVersionString(),
e);
}
// Stream creation SQL.
final String streamSql =
"INSERT INTO observer_stream (" +
"stream_id, " +
"version, " +
"name, " +
"description, " +
"with_id, " +
"with_timestamp, " +
"with_location, " +
"stream_schema)" +
"VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
// For each stream, insert it and link it to the observer.
for(final Stream stream : observer.getStreamsMap().values()) {
// This stream's creation statement with its parameters.
PreparedStatementCreator streamCreator =
new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(
final Connection connection)
throws SQLException {
PreparedStatement ps =
connection.prepareStatement(
streamSql,
new String[] { "id" });
ps.setString(1, stream.getId());
ps.setLong(2, stream.getVersion());
ps.setString(3, stream.getName());
ps.setString(4, stream.getDescription());
ps.setObject(5, stream.getWithId());
ps.setObject(6, stream.getWithTimestamp());
ps.setObject(7, stream.getWithLocation());
try {
ps.setString(
8,
stream
.getSchema()
.readValueAsTree()
.toString());
}
catch(JsonParseException e) {
throw new SQLException(
"The schema is not valid JSON.",
e);
}
catch(IOException e) {
throw new SQLException(
"Could not read the schema string.",
e);
}
return ps;
}
};
// This stream's auto-generated key.
KeyHolder streamKeyHolder = new GeneratedKeyHolder();
// Create the stream.
try {
getJdbcTemplate().update(streamCreator, streamKeyHolder);
}
catch(org.springframework.dao.DataAccessException e) {
transactionManager.rollback(status);
throw new DataAccessException(
"Error executing SQL '" +
streamSql +
"' with parameters: " +
stream.getId() + ", " +
stream.getVersion() + ", " +
stream.getName() + ", " +
stream.getDescription() + ", " +
stream.getWithId() + ", " +
stream.getWithTimestamp() + ", " +
stream.getWithLocation() + ", " +
stream.getSchema().toString(),
e);
}
// Link creation SQL.
final String linkSql =
"INSERT INTO observer_stream_link (" +
"observer_id, " +
"observer_stream_id) " +
"VALUES (?, ?)";
// Link the stream to the observer.
try {
getJdbcTemplate().update(
linkSql,
new Object[] {
observerKeyHolder.getKey().longValue(),
streamKeyHolder.getKey().longValue()
}
);
}
catch(org.springframework.dao.DataAccessException e) {
transactionManager.rollback(status);
throw new DataAccessException(
"Error executing SQL '" +
linkSql +
"' with parameters: " +
observerKeyHolder.getKey().longValue() + ", " +
streamKeyHolder.getKey().longValue(),
e);
}
}
// Commit the transaction.
try {
transactionManager.commit(status);
}
catch(TransactionException e) {
transactionManager.rollback(status);
throw new DataAccessException(
"Error while committing the transaction.",
e);
}
}
catch(TransactionException e) {
throw new DataAccessException(
"Error while attempting to rollback the transaction.",
e);
}
}
/*
* (non-Javadoc)
* @see org.ohmage.query.IObserverQueries#doesObserverExist(java.lang.String)
*/
@Override
public boolean doesObserverExist(
final String observerId)
throws DataAccessException {
String sql =
"SELECT EXISTS(SELECT id FROM observer WHERE observer_id = ?)";
try {
return
getJdbcTemplate().queryForObject(
sql,
new Object[] { observerId },
new SingleColumnRowMapper<Long>()) != 0;
}
catch(org.springframework.dao.DataAccessException e) {
throw new DataAccessException(
"Error executing SQL '" +
sql +
"' with parameter: " +
observerId);
}
}
/*
* (non-Javadoc)
* @see org.ohmage.query.IObserverQueries#getOwner(java.lang.String)
*/
@Override
public String getOwner(
final String observerId)
throws DataAccessException {
if(observerId == null) {
return null;
}
String sql =
"SELECT DISTINCT(u.username) " +
"FROM user u, observer o " +
"WHERE u.id = o.user_id " +
"AND o.observer_id = ?";
try {
return
getJdbcTemplate().queryForObject(
sql,
new Object[] { observerId },
String.class);
}
catch(org.springframework.dao.IncorrectResultSizeDataAccessException e) {
if(e.getActualSize() > 1) {
throw new DataAccessException(
"Multiple observers have the same ID: " + observerId,
e);
}
return null;
}
catch(org.springframework.dao.DataAccessException e) {
throw new DataAccessException(
"There was an error executing SQL '" +
sql +
"' with parameter: " +
observerId,
e);
}
}
/*
* (non-Javadoc)
* @see org.ohmage.query.IObserverQueries#getObservers(java.lang.String, java.lang.Long, long, long)
*/
public List<Observer> getObservers(
final String id,
final Long version,
final long numToSkip,
final long numToReturn)
throws DataAccessException {
// Build the SQL that will get all of the observers visible to the
// requesting user.
StringBuilder observerSql =
new StringBuilder(
"SELECT " +
"id, " +
"observer_id, " +
"version, " +
"name, " +
"description, " +
"version_string " +
"FROM observer o");
List<String> whereClauses = new LinkedList<String>();
List<Object> parameters = new LinkedList<Object>();
// Add the ID if it is present.
if(id != null) {
whereClauses.add("o.observer_id = ?");
parameters.add(id);
}
// Add the version if present.
if(version != null) {
whereClauses.add("o.version = ?");
parameters.add(version);
}
// Add the WHERE clauses to the query.
boolean firstPass = true;
for(String whereClause : whereClauses) {
if(firstPass) {
observerSql.append(" WHERE ");
firstPass = false;
}
else {
observerSql.append(" AND ");
}
observerSql.append(whereClause);
}
observerSql.append(" ORDER BY o.observer_id ASC, o.version DESC");
observerSql.append(" LIMIT ?, ?");
parameters.add(numToSkip);
parameters.add(numToReturn);
final Map<Long, Observer.Builder> observerBuilders =
new HashMap<Long, Observer.Builder>();
try {
getJdbcTemplate().query(
observerSql.toString(),
parameters.toArray(),
new RowMapper<Object> () {
/**
* Maps the row of data to a new observer builder.
*/
@Override
public Object mapRow(
final ResultSet rs,
final int rowNum)
throws SQLException {
Observer.Builder observerBuilder =
new Observer.Builder();
observerBuilder
.setId(rs.getString("observer_id"))
.setVersion(rs.getLong("version"))
.setName(rs.getString("name"))
.setDescription(rs.getString("description"))
.setVersionString(
rs.getString("version_string"));
observerBuilders.put(
rs.getLong("id"),
observerBuilder);
return null;
}
}
);
}
catch(org.springframework.dao.DataAccessException e) {
throw new DataAccessException(
"Error executing SQL '" +
observerSql +
"' with parameters: " +
parameters,
e);
}
final String streamSql =
"SELECT " +
"os.stream_id, " +
"os.version, " +
"os.name, " +
"os.description, " +
"os.with_id, " +
"os.with_timestamp, " +
"os.with_location, " +
"os.stream_schema " +
"FROM observer_stream os, observer_stream_link osl " +
"WHERE osl.observer_id = ? " +
"AND osl.observer_stream_id = os.id";
for(Long dbId : observerBuilders.keySet()) {
try {
observerBuilders
.get(dbId)
.addStreams(
getJdbcTemplate().query(
streamSql,
new Object[] { dbId },
new RowMapper<Observer.Stream>() {
/**
* Maps the row of data to a new stream.
*/
@Override
public Stream mapRow(
final ResultSet rs,
final int rowNum)
throws SQLException {
// Because the with_* values are optional and
// may be null, they must be retrieve in this
// special way.
Boolean withId, withTimestamp, withLocation;
withId = rs.getBoolean("with_id");
if(rs.wasNull()) {
withId = null;
}
withTimestamp =
rs.getBoolean("with_timestamp");
if(rs.wasNull()) {
withTimestamp = null;
}
withLocation = rs.getBoolean("with_location");
if(rs.wasNull()) {
withLocation = null;
}
try {
return new Observer.Stream(
rs.getString("stream_id"),
rs.getLong("version"),
rs.getString("name"),
rs.getString("description"),
withId,
withTimestamp,
withLocation,
rs.getString("stream_schema"));
}
catch(DomainException e) {
throw new SQLException(e);
}
}
}
)
);
}
catch(org.springframework.dao.DataAccessException e) {
throw new DataAccessException(
"Error executing SQL '" +
streamSql +
"' with parameter: " +
dbId,
e);
}
}
ArrayList<Observer> result =
new ArrayList<Observer>(observerBuilders.size());
for(Observer.Builder observerBuilder : observerBuilders.values()) {
try {
result.add(observerBuilder.build());
}
catch(DomainException e) {
throw new DataAccessException(
"There was a problem building an observer.",
e);
}
}
return result;
}
/*
* (non-Javadoc)
* @see org.ohmage.query.IObserverQueries#getGreatestObserverVersion(java.lang.String)
*/
@Override
public Long getGreatestObserverVersion(
final String id)
throws DataAccessException {
String sql =
"SELECT MAX(version) AS max_version " +
"FROM observer " +
"WHERE observer_id = ?";
try {
return
getJdbcTemplate().queryForLong(sql, new Object[] { id });
}
catch(org.springframework.dao.DataAccessException e) {
throw new DataAccessException(
"Error executing SQL '" +
sql +
"' with parameter: " +
id,
e);
}
}
/*
* (non-Javadoc)
* @see org.ohmage.query.IObserverQueries#getStreams(java.lang.String, java.lang.Long, java.lang.String, java.lang.Long, long, long)
*/
@Override
public Map<String, Collection<Observer.Stream>> getStreams(
final String username,
final String observerId,
final Long observerVersion,
final String streamId,
final Long streamVersion,
final long numToSkip,
final long numToReturn)
throws DataAccessException {
if(numToReturn == 0) {
return Collections.emptyMap();
}
// Create the default SQL.
StringBuilder sqlBuilder =
new StringBuilder(
"SELECT DISTINCT " +
"o.observer_id, " +
"os.stream_id, " +
"os.version, " +
"os.name, " +
"os.description, " +
"os.with_id, " +
"os.with_timestamp, " +
"os.with_location, " +
"os.stream_schema " +
"FROM " +
"observer o, " +
"observer_stream os, " +
"observer_stream_link osl " +
"WHERE o.id = osl.observer_id " +
"AND os.id = osl.observer_stream_id");
// Create the default set of parameters.
List<Object> parameters = new LinkedList<Object>();
if(username != null) {
sqlBuilder
.append(
" AND EXISTS (" +
"SELECT osd.id " +
"FROM user u, observer_stream_data osd " +
"WHERE u.username = ? " +
"AND u.id = osd.user_id " +
"AND osl.id = osd.observer_stream_link_id" +
")"
);
parameters.add(username);
}
// If querying about the observer's ID, add that WHERE clause and
// add the parameter.
if(observerId != null) {
sqlBuilder.append(" AND o.observer_id = ?");
parameters.add(observerId);
}
// If querying about the observer's version, add that WHERE clause
// and add the parameter.
if(observerVersion != null) {
sqlBuilder.append(" AND o.version = ?");
parameters.add(observerVersion);
}
// If querying about the stream's ID add the WHERE clause and the
// parameter.
if(streamId != null) {
sqlBuilder.append(" AND os.stream_id = ?");
parameters.add(streamId);
}
// If querying about the stream's version add the WHERE clause and the
// parameter.
if(streamVersion != null) {
sqlBuilder.append(" AND os.version = ?");
parameters.add(streamVersion);
}
// Add ordering to facilitate paging.
sqlBuilder
.append(
" ORDER BY o.observer_id, o.version, os.stream_id, os.version");
// Add the limits for paging.
sqlBuilder.append(" LIMIT ?, ?");
parameters.add(numToSkip);
parameters.add(numToReturn);
// Query for the results and add them to the result map.
final Map<String, Collection<Observer.Stream>> result =
new HashMap<String, Collection<Observer.Stream>>();
try {
getJdbcTemplate().query(
sqlBuilder.toString(),
parameters.toArray(),
new RowMapper<Object>() {
/**
* Maps the row of data to a new stream.
*/
@Override
public Object mapRow(
final ResultSet rs,
final int rowNum)
throws SQLException {
// Get the observer's ID.
String observerId = rs.getString("observer_id");
// Get the streams from the result.
Collection<Observer.Stream> streams =
result.get(observerId);
// If no collection exists for that observer ID yet,
// create a new collection and add it.
if(streams == null) {
streams = new LinkedList<Observer.Stream>();
result.put(observerId, streams);
}
// Because the with_* values are optional and
// may be null, they must be retrieve in this
// special way.
Boolean withId, withTimestamp, withLocation;
withId = rs.getBoolean("with_id");
if(rs.wasNull()) {
withId = null;
}
withTimestamp =
rs.getBoolean("with_timestamp");
if(rs.wasNull()) {
withTimestamp = null;
}
withLocation = rs.getBoolean("with_location");
if(rs.wasNull()) {
withLocation = null;
}
// Add the stream to its respective result list.
try {
streams
.add(
new Observer.Stream(
rs.getString("stream_id"),
rs.getLong("version"),
rs.getString("name"),
rs.getString("description"),
withId,
withTimestamp,
withLocation,
rs.getString("stream_schema")));
}
catch(DomainException e) {
throw new SQLException(e);
}
// Return nothing as it will never be used.
return null;
}
}
);
}
catch(org.springframework.dao.DataAccessException e) {
throw new DataAccessException(
"Error executing SQL '" +
sqlBuilder.toString() +
"' with parameters: " +
parameters,
e);
}
// Return the result.
return result;
}
/*
* (non-Javadoc)
* @see org.ohmage.query.IObserverQueries#getGreatestObserverVersion(java.lang.String)
*/
@Override
public Long getGreatestStreamVersion(
final String observerId,
final String streamId)
throws DataAccessException {
String sql =
"SELECT MAX(os.version) AS max_version " +
"FROM observer o, observer_stream os, observer_stream_link osl " +
"WHERE o.observer_id = ? " +
"AND os.stream_id = ? " +
"AND o.id = osl.observer_id " +
"AND osl.observer_stream_id = os.id";
try {
return
getJdbcTemplate().queryForLong(
sql,
new Object[] { observerId, streamId });
}
catch(org.springframework.dao.DataAccessException e) {
throw new DataAccessException(
"Error executing SQL '" +
sql +
"' with parameter: " +
observerId + ", " +
streamId,
e);
}
}
/*
* (non-Javadoc)
* @see org.ohmage.query.IObserverQueries#getDuplicateIds(java.lang.String, java.lang.String, java.util.Collection)
*/
@Override
public Collection<String> getDuplicateIds(
final String username,
final String observerId,
final String streamId,
final Collection<String> idsToCheck)
throws DataAccessException {
int numIds = idsToCheck.size();
if(numIds == 0) {
return Collections.emptyList();
}
StringBuilder sqlBuilder =
new StringBuilder(
"SELECT osd.uid " +
"FROM " +
"user u, " +
"observer o, " +
"observer_stream os, " +
"observer_stream_link osl, " +
"observer_stream_data osd " +
"WHERE u.username = ? " +
"AND o.observer_id = ? " +
"AND o.id = osl.observer_id " +
"AND osl.observer_stream_id = os.id " +
"AND os.stream_id = ? " +
"AND u.id = osd.user_id " +
"AND osl.id = osd.observer_stream_link_id " +
"AND osd.uid IN ");
sqlBuilder.append(StringUtils.generateStatementPList(numIds));
Collection<Object> parameters =
new ArrayList<Object>(idsToCheck.size() + 2);
parameters.add(username);
parameters.add(observerId);
parameters.add(streamId);
parameters.addAll(idsToCheck);
try {
return
getJdbcTemplate().query(
sqlBuilder.toString(),
parameters.toArray(),
new SingleColumnRowMapper<String>());
}
catch(org.springframework.dao.DataAccessException e) {
throw new DataAccessException(
"Error executing SQL '" +
sqlBuilder.toString() +
"' with parameters: " +
parameters,
e);
}
}
/*
* (non-Javadoc)
* @see org.ohmage.query.IObserverQueries#storeData(java.lang.String, java.util.Collection)
*/
@Override
public void storeData(
final String username,
final Observer observer,
final Collection<DataStream> data)
throws DataAccessException {
String sql =
"INSERT INTO observer_stream_data (" +
"user_id, " +
"observer_stream_link_id, " +
"uid, " +
"time, " +
"time_offset, " +
"time_adjusted, " +
"time_zone, " +
"location_timestamp, " +
"location_latitude, " +
"location_longitude, " +
"location_accuracy, " +
"location_provider, " +
"data) " +
"VALUES (" +
"(SELECT id FROM user WHERE username = ?), " +
"(" +
"SELECT osl.id " +
"FROM " +
"observer o, " +
"observer_stream os, " +
"observer_stream_link osl " +
"WHERE o.observer_id = ? " +
"AND o.version = ? " +
"AND os.stream_id = ? " +
"AND os.version = ? " +
"AND o.id = osl.observer_id " +
"AND os.id = osl.observer_stream_id" +
"), " +
"?, " +
"?, " +
"?, " +
"?, " +
"?, " +
"?, " +
"?, " +
"?, " +
"?, " +
"?, " +
"?)";
List<Object[]> args = new ArrayList<Object[]>(data.size());
for(DataStream currData : data) {
MetaData metaData = currData.getMetaData();
String id = null;
DateTime timestamp = null;
Location location = null;
if(metaData != null) {
id = metaData.getId();
timestamp = metaData.getTimestamp();
location = metaData.getLocation();
}
Long time = (timestamp == null) ? null : timestamp.getMillis();
Integer timeOffset =
(timestamp == null) ?
null :
timestamp.getZone().getOffset(timestamp);
Long timeAdjusted =
(timestamp == null) ? null : time + timeOffset;
String timeZoneId =
(timestamp == null) ? null : timestamp.getZone().getID();
args.add(
new Object[] {
username,
observer.getId(),
observer.getVersion(),
currData.getStream().getId(),
currData.getStream().getVersion(),
id,
time,
timeOffset,
timeAdjusted,
timeZoneId,
(location == null) ? null : (new DateTime(location.getTime(), location.getTimeZone())).toString(),
(location == null) ? null : location.getLatitude(),
(location == null) ? null : location.getLongitude(),
(location == null) ? null : location.getAccuracy(),
(location == null) ? null : location.getProvider(),
currData.getData().toString()
}
);
}
// Create the transaction.
DefaultTransactionDefinition def = new DefaultTransactionDefinition();
def.setName("Inserting stream data.");
try {
// Begin the transaction.
PlatformTransactionManager transactionManager =
new DataSourceTransactionManager(getDataSource());
TransactionStatus status = transactionManager.getTransaction(def);
try {
getJdbcTemplate().batchUpdate(sql, args);
}
catch(org.springframework.dao.DataAccessException e) {
transactionManager.rollback(status);
throw new DataAccessException(
"Error executing SQL '" + sql +"'.",
e);
}
// Commit the transaction.
try {
transactionManager.commit(status);
}
catch(TransactionException e) {
transactionManager.rollback(status);
throw new DataAccessException(
"Error while committing the transaction.",
e);
}
}
catch(TransactionException e) {
throw new DataAccessException(
"Error while attempting to rollback the transaction.",
e);
}
}
/*
* (non-Javadoc)
* @see org.ohmage.query.IObserverQueries#storeInvalidData(java.lang.String, org.ohmage.domain.Observer, java.util.Collection)
*/
@Override
public void storeInvalidData(
final String username,
final Observer observer,
final Collection<InvalidPoint> invalidData)
throws DataAccessException {
String sql =
"INSERT INTO observer_stream_data_invalid (" +
"user_id, " +
"observer_id, " +
"time_recorded, " +
"point_index, " +
"reason, " +
"data) " +
"VALUES (" +
"(SELECT id FROM user WHERE username = ?), " +
"(" +
"SELECT id " +
"FROM observer " +
"WHERE observer_id = ? " +
"AND version = ?" +
"), " +
"?, " +
"?, " +
"?, " +
"?)";
List<Object[]> args = new ArrayList<Object[]>(invalidData.size());
for(InvalidPoint currData : invalidData) {
args.add(
new Object[] {
username,
observer.getId(),
observer.getVersion(),
System.currentTimeMillis(),
currData.getIndex(),
currData.getReason(),
currData.getData()
}
);
}
// Create the transaction.
DefaultTransactionDefinition def = new DefaultTransactionDefinition();
def.setName("Inserting invalid stream data.");
try {
// Begin the transaction.
PlatformTransactionManager transactionManager =
new DataSourceTransactionManager(getDataSource());
TransactionStatus status = transactionManager.getTransaction(def);
try {
getJdbcTemplate().batchUpdate(sql, args);
}
catch(org.springframework.dao.DataAccessException e) {
transactionManager.rollback(status);
throw new DataAccessException(
"Error executing SQL '" + sql +"'.",
e);
}
// Commit the transaction.
try {
transactionManager.commit(status);
}
catch(TransactionException e) {
transactionManager.rollback(status);
throw new DataAccessException(
"Error while committing the transaction.",
e);
}
}
catch(TransactionException e) {
throw new DataAccessException(
"Error while attempting to rollback the transaction.",
e);
}
}
/*
* (non-Javadoc)
* @see org.ohmage.query.IObserverQueries#readData(org.ohmage.domain.Observer.Stream, java.lang.String, java.lang.String, java.lang.Long, org.joda.time.DateTime, org.joda.time.DateTime, boolean, long, long)
*/
@Override
public List<DataStream> readData(
final Stream stream,
final String username,
final String observerId,
final Long observerVersion,
final DateTime startDate,
final DateTime endDate,
final boolean chronological,
final long numToSkip,
final long numToReturn)
throws DataAccessException {
// Create the initial query and required set of parameters.
StringBuilder builder =
new StringBuilder(
"SELECT " +
"osd.uid, " +
"osd.time, " +
"osd.time_zone, " +
"osd.location_timestamp, " +
"osd.location_latitude, " +
"osd.location_longitude, " +
"osd.location_accuracy, " +
"osd.location_provider, " +
"osd.data " +
"FROM " +
"observer_stream_data AS osd " +
"LEFT JOIN observer_stream_link AS osl " +
"ON osd.observer_stream_link_id = osl.id " +
"WHERE " +
"osd.user_id = (" +
"SELECT id " +
"FROM user " +
"WHERE username = ?" +
") " +
"AND osl.observer_id = " +
"(SELECT id FROM observer WHERE observer_id = ?");
List<Object> parameters = new LinkedList<Object>();
parameters.add(username);
parameters.add(observerId);
// If the observer's version is specified, add it to the sub-query.
if(observerVersion != null) {
builder.append(" AND version = ?)");
parameters.add(observerVersion);
}
// Otherwise, end the subquery.
else {
builder.append(')');
}
// Add the remainder of the required parameters and their query
// components.
builder
.append(
" AND osl.observer_stream_id = " +
"(" +
"SELECT id " +
"FROM observer_stream " +
"WHERE stream_id = ? " +
"AND version = ?" +
")");
parameters.add(stream.getId());
parameters.add(stream.getVersion());
// If a start date is given, add it to the overall query.
if(startDate != null) {
builder.append(" AND osd.time_adjusted >= ?");
parameters.add(startDate.getMillis());
}
// If an end date is given, add it to the overall query.
if(endDate != null) {
builder.append(" AND osd.time_adjusted <= ?");
parameters.add(endDate.getMillis());
}
// Add the ordering based on whether or not these should be
// chronological or reverse chronological.
builder
.append(
" ORDER BY osd.time " + ((chronological) ? "ASC" : "DESC"));
// Limit the number of results based on the paging.
builder.append(" LIMIT ?, ?");
parameters.add(numToSkip);
parameters.add(numToReturn);
// Create a JSON factory, which will be used by each data point to
// deserialize its data into a JsonNode.
final JsonFactory jsonFactory = new MappingJsonFactory();
try {
return
getJdbcTemplate().query(
builder.toString(),
parameters.toArray(),
new RowMapper<DataStream>() {
/**
* Decodes the resulting data into a data stream.
*/
@Override
public DataStream mapRow(
final ResultSet rs,
final int rowNum)
throws SQLException {
MetaData.Builder metaDataBuilder =
new MetaData.Builder();
String id = rs.getString("osd.uid");
if(id != null) {
metaDataBuilder.setId(id);
}
Long time = rs.getLong("osd.time");
if(time != null) {
metaDataBuilder.setTimestamp(
new DateTime(
time,
DateTimeZone.forID(
rs.getString("osd.time_zone"))));
}
String locationTimestampString =
rs.getString("location_timestamp");
if(locationTimestampString != null) {
Location location;
try {
location =
new Location(
ISODateTimeFormat
.dateTime()
.parseDateTime(
rs.getString(
"osd.location_timestamp")),
rs.getDouble("osd.location_latitude"),
rs.getDouble("osd.location_longitude"),
rs.getDouble("osd.location_accuracy"),
rs.getString("osd.location_provider"));
}
catch(IllegalArgumentException e) {
throw new SQLException(
"The timestamp in the database is corrupted.",
e);
}
catch(NullPointerException e) {
throw new SQLException(
"A double in the database is corrupted.",
e);
}
catch(DomainException e) {
throw new SQLException(
"Could not create the location object.",
e);
}
metaDataBuilder.setLocation(location);
}
JsonNode data;
try {
JsonParser parser =
jsonFactory
.createJsonParser(
rs.getString("osd.data"));
data = parser.readValueAsTree();
}
catch(JsonParseException e) {
throw new SQLException(
"The data in the database is invalid: " +
id,
e);
}
catch(IOException e) {
throw new SQLException(
"There was a problem reading the data: " +
id,
e);
}
try {
return new DataStream(
stream,
metaDataBuilder.build(),
data);
}
catch(DomainException e) {
throw new SQLException(
"Could not create the data stream.",
e);
}
}
});
}
catch(org.springframework.dao.DataAccessException e) {
throw new DataAccessException(
"Error executing SQL '" +
builder.toString() +
"' with parameters: " +
parameters,
e);
}
}
/*
* (non-Javadoc)
* @see org.ohmage.query.IObserverQueries#readInvalidData(org.ohmage.domain.Observer, org.joda.time.DateTime, org.joda.time.DateTime, long, long)
*/
@Override
public Collection<InvalidPoint> readInvalidData(
final Observer observer,
final DateTime startDate,
final DateTime endDate,
final long numToSkip,
final long numToReturn)
throws DataAccessException {
// Build the SQL.
StringBuilder sqlBuilder =
new StringBuilder(
"SELECT osdi.point_index, osdi.reason, osdi.data " +
"FROM " +
"observer o, " +
"observer_stream_data_invalid osdi " +
"WHERE o.id = osdi.observer_id " +
"AND o.observer_id = ? " +
"AND o.version = ? ");
// Create the list of parameters.
List<Object> parameters = new LinkedList<Object>();
parameters.add(observer.getId());
parameters.add(observer.getVersion());
// If the start date was given, add it.
if(startDate != null) {
sqlBuilder.append("AND time_recorded >= ? ");
parameters.add(startDate.getMillis());
}
// If the end date was given, add it.
if(endDate != null) {
sqlBuilder.append("AND time_recorded <= ? ");
parameters.add(endDate.getMillis());
}
// Add the ordering.
sqlBuilder.append("ORDER BY time_recorded ");
// Add the paging parameters.
sqlBuilder.append("LIMIT ?, ?");
parameters.add(numToSkip);
parameters.add(numToReturn);
try {
return
getJdbcTemplate()
.query(
sqlBuilder.toString(),
parameters.toArray(),
new RowMapper<InvalidPoint>() {
/*
* (non-Javadoc)
* @see org.springframework.jdbc.core.RowMapper#mapRow(java.sql.ResultSet, int)
*/
@Override
public InvalidPoint mapRow(
final ResultSet resultSet,
final int rowNum)
throws SQLException {
// Create the point and return it.
return
new InvalidPoint(
resultSet.getLong("point_index"),
resultSet.getString("data"),
resultSet.getString("reason"),
null);
}
}
);
}
catch(org.springframework.dao.DataAccessException e) {
throw new DataAccessException(
"Error executing SQL '" +
sqlBuilder.toString() +
"' with parameters: " +
parameters,
e);
}
}
/*
* (non-Javadoc)
* @see org.ohmage.query.IObserverQueries#updateObserver(java.lang.String, org.ohmage.domain.Observer, java.util.Collection)
*/
@Override
public void updateObserver(
final String username,
final Observer observer,
final Map<String, Long> unchangedStreamIds)
throws DataAccessException {
if(username == null) {
throw new DataAccessException("The username is null.");
}
if(observer == null) {
throw new DataAccessException("The observer is null.");
}
if(unchangedStreamIds == null) {
throw new DataAccessException(
"The collection of unchanged IDs is null.");
}
// Create the transaction.
DefaultTransactionDefinition def = new DefaultTransactionDefinition();
def.setName("Creating an observer.");
try {
// Begin the transaction.
PlatformTransactionManager transactionManager =
new DataSourceTransactionManager(getDataSource());
TransactionStatus status = transactionManager.getTransaction(def);
// Observer creation SQL.
final String observerSql =
"INSERT INTO observer (" +
"observer_id, " +
"version, " +
"name, " +
"description, " +
"version_string, " +
"user_id) " +
"VALUES (?, ?, ?, ?, ?, " +
"(SELECT id FROM user WHERE username = ?))";
// Observer creation statement with parameters.
PreparedStatementCreator observerCreator =
new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(
final Connection connection)
throws SQLException {
PreparedStatement ps =
connection.prepareStatement(
observerSql,
new String[] { "id" });
ps.setString(1, observer.getId());
ps.setLong(2, observer.getVersion());
ps.setString(3, observer.getName());
ps.setString(4, observer.getDescription());
ps.setString(5, observer.getVersionString());
ps.setString(6, username);
return ps;
}
};
// The auto-generated key for the observer.
KeyHolder observerKeyHolder = new GeneratedKeyHolder();
// Create the observer.
try {
getJdbcTemplate().update(observerCreator, observerKeyHolder);
}
catch(org.springframework.dao.DataAccessException e) {
transactionManager.rollback(status);
throw new DataAccessException(
"Error executing SQL '" +
observerSql +
"' with parameters: " +
observer.getId() + ", " +
observer.getVersion() + ", " +
observer.getName() + ", " +
observer.getDescription() + ", " +
observer.getVersionString(),
e);
}
// Get the observer ID.
long observerDbId = observerKeyHolder.getKey().longValue();
// Stream creation SQL.
final String streamSql =
"INSERT INTO observer_stream (" +
"stream_id, " +
"version, " +
"name, " +
"description, " +
"with_id, " +
"with_timestamp, " +
"with_location, " +
"stream_schema) " +
"VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
// Observer-stream link SQL.
final String observerStreamSql =
"INSERT INTO observer_stream_link(" +
"observer_id, " +
"observer_stream_id" +
") " +
"VALUES (" +
"?, " +
"?" +
")";
// If all we are doing is grabbing the database ID for the stream,
// then this will take care of that. Note: The observer's ID must
// be put in twice to help get the correct version.
final String getStreamIdSql =
"SELECT os.id " +
"FROM " +
"observer o, " +
"observer_stream os, " +
"observer_stream_link osl " +
"WHERE o.observer_id = ? " +
"AND o.version = " +
"(" +
"SELECT version " +
"FROM observer " +
"WHERE observer_id = ? " +
"ORDER BY version DESC " +
"LIMIT 1, 1" +
") " +
"AND os.stream_id = ? " +
"AND os.version = ? " +
"AND o.id = osl.observer_id " +
"AND os.id = osl.observer_stream_id";
// For each stream, insert it and link it to the observer.
for(final Stream stream : observer.getStreamsMap().values()) {
// Get the stream's ID.
final String streamId = stream.getId();
// The stream's database identifier.
Long streamDbId;
// If the stream already exists in the map of stream IDs and
// versions, then get the stream's database ID for linking.
if(unchangedStreamIds.containsKey(streamId)) {
// Attempt to get the stream's database ID.
try {
streamDbId =
getJdbcTemplate()
.queryForLong(
getStreamIdSql,
new Object[] {
observer.getId(),
observer.getId(),
streamId,
stream.getVersion()
}
);
}
catch(org.springframework.dao.DataAccessException e) {
transactionManager.rollback(status);
throw new DataAccessException(
"Error executing SQL '" +
getStreamIdSql +
"' with parameters: " +
observer.getId() + ", " +
observer.getId() + ", " +
streamId + ", " +
stream.getVersion(),
e);
}
}
// Otherwise, add the new stream and retain its database ID.
else {
// Get the stream's schema as a string.
final String schema;
try {
schema = stream.getSchema().readValueAsTree().toString();
}
catch(JsonProcessingException e) {
transactionManager.rollback(status);
throw new DataAccessException(
"Error parsing the schema.",
e);
}
catch(IOException e) {
transactionManager.rollback(status);
throw new DataAccessException(
"Error reading the schema.",
e);
}
// Stream creation statement with parameters.
PreparedStatementCreator streamCreator =
new PreparedStatementCreator() {
/**
* Create the stream insertion statement.
*/
@Override
public PreparedStatement createPreparedStatement(
final Connection connection)
throws SQLException {
PreparedStatement ps =
connection.prepareStatement(
streamSql,
new String[] { "id" });
ps.setString(1, streamId);
ps.setLong(2, stream.getVersion());
ps.setString(3, stream.getName());
ps.setString(4, stream.getDescription());
ps.setObject(5, stream.getWithId());
ps.setObject(6, stream.getWithTimestamp());
ps.setObject(7, stream.getWithLocation());
ps.setString(8, schema);
return ps;
}
};
// The auto-generated key for the observer.
KeyHolder streamKeyHolder = new GeneratedKeyHolder();
// Create the observer.
try {
getJdbcTemplate().update(streamCreator, streamKeyHolder);
}
catch(org.springframework.dao.DataAccessException e) {
transactionManager.rollback(status);
throw new DataAccessException(
"Error executing SQL '" +
streamSql +
"' with parameters: " +
streamId + ", " +
stream.getVersion() + ", " +
stream.getName() + ", " +
stream.getDescription() + ", " +
stream.getWithId() + ", " +
stream.getWithTimestamp() + ", " +
stream.getWithLocation() + ", " +
schema,
e);
}
// Get the observer ID.
streamDbId = streamKeyHolder.getKey().longValue();
}
// Link the stream to the observer.
try {
getJdbcTemplate()
.update(
observerStreamSql,
new Object[] { observerDbId, streamDbId });
}
catch(org.springframework.dao.DataAccessException e) {
transactionManager.rollback(status);
throw new DataAccessException(
"Error executing SQL '" +
observerStreamSql +
"' with parameters: " +
observerDbId + ", " +
streamDbId,
e);
}
}
// Commit the transaction.
try {
transactionManager.commit(status);
}
catch(TransactionException e) {
transactionManager.rollback(status);
throw new DataAccessException(
"Error while committing the transaction.",
e);
}
}
catch(TransactionException e) {
throw new DataAccessException(
"Error while attempting to rollback the transaction.",
e);
}
}
} | src/org/ohmage/query/impl/ObserverQueries.java | package org.ohmage.query.impl;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.MappingJsonFactory;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.format.ISODateTimeFormat;
import org.ohmage.domain.DataStream;
import org.ohmage.domain.DataStream.MetaData;
import org.ohmage.domain.Location;
import org.ohmage.domain.Observer;
import org.ohmage.domain.Observer.Stream;
import org.ohmage.exception.DataAccessException;
import org.ohmage.exception.DomainException;
import org.ohmage.query.IObserverQueries;
import org.ohmage.service.ObserverServices.InvalidPoint;
import org.ohmage.util.StringUtils;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.SingleColumnRowMapper;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionException;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
/**
* This class is responsible for creating, reading, updating, and deleting
* probe information.
*
* @author John Jenkins
*/
public class ObserverQueries extends Query implements IObserverQueries {
/**
* Creates this object via dependency injection (reflection).
*
* @param dataSource
* The DataSource to use when querying the database.
*/
private ObserverQueries(DataSource dataSource) {
super(dataSource);
}
/*
* (non-Javadoc)
*
* @see org.ohmage.query.IObserverQueries#createProbe(org.ohmage.domain.Observer)
*/
@Override
public void createObserver(
final String username,
final Observer observer)
throws DataAccessException {
if(username == null) {
throw new DataAccessException("The username is null.");
}
if(observer == null) {
throw new DataAccessException("The observer is null.");
}
// Create the transaction.
DefaultTransactionDefinition def = new DefaultTransactionDefinition();
def.setName("Creating an observer.");
try {
// Begin the transaction.
PlatformTransactionManager transactionManager =
new DataSourceTransactionManager(getDataSource());
TransactionStatus status = transactionManager.getTransaction(def);
// Observer creation SQL.
final String observerSql =
"INSERT INTO observer (" +
"observer_id, " +
"version, " +
"name, " +
"description, " +
"version_string, " +
"user_id) " +
"VALUES (?, ?, ?, ?, ?, " +
"(SELECT id FROM user WHERE username = ?))";
// Observer creation statement with parameters.
PreparedStatementCreator observerCreator =
new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(
final Connection connection)
throws SQLException {
PreparedStatement ps =
connection.prepareStatement(
observerSql,
new String[] { "id" });
ps.setString(1, observer.getId());
ps.setLong(2, observer.getVersion());
ps.setString(3, observer.getName());
ps.setString(4, observer.getDescription());
ps.setString(5, observer.getVersionString());
ps.setString(6, username);
return ps;
}
};
// The auto-generated key for the observer.
KeyHolder observerKeyHolder = new GeneratedKeyHolder();
// Create the observer.
try {
getJdbcTemplate().update(observerCreator, observerKeyHolder);
}
catch(org.springframework.dao.DataAccessException e) {
transactionManager.rollback(status);
throw new DataAccessException(
"Error executing SQL '" +
observerSql +
"' with parameters: " +
observer.getId() + ", " +
observer.getVersion() + ", " +
observer.getName() + ", " +
observer.getDescription() + ", " +
observer.getVersionString(),
e);
}
// Stream creation SQL.
final String streamSql =
"INSERT INTO observer_stream (" +
"stream_id, " +
"version, " +
"name, " +
"description, " +
"with_id, " +
"with_timestamp, " +
"with_location, " +
"stream_schema)" +
"VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
// For each stream, insert it and link it to the observer.
for(final Stream stream : observer.getStreamsMap().values()) {
// This stream's creation statement with its parameters.
PreparedStatementCreator streamCreator =
new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(
final Connection connection)
throws SQLException {
PreparedStatement ps =
connection.prepareStatement(
streamSql,
new String[] { "id" });
ps.setString(1, stream.getId());
ps.setLong(2, stream.getVersion());
ps.setString(3, stream.getName());
ps.setString(4, stream.getDescription());
ps.setObject(5, stream.getWithId());
ps.setObject(6, stream.getWithTimestamp());
ps.setObject(7, stream.getWithLocation());
try {
ps.setString(
8,
stream
.getSchema()
.readValueAsTree()
.toString());
}
catch(JsonParseException e) {
throw new SQLException(
"The schema is not valid JSON.",
e);
}
catch(IOException e) {
throw new SQLException(
"Could not read the schema string.",
e);
}
return ps;
}
};
// This stream's auto-generated key.
KeyHolder streamKeyHolder = new GeneratedKeyHolder();
// Create the stream.
try {
getJdbcTemplate().update(streamCreator, streamKeyHolder);
}
catch(org.springframework.dao.DataAccessException e) {
transactionManager.rollback(status);
throw new DataAccessException(
"Error executing SQL '" +
streamSql +
"' with parameters: " +
stream.getId() + ", " +
stream.getVersion() + ", " +
stream.getName() + ", " +
stream.getDescription() + ", " +
stream.getWithId() + ", " +
stream.getWithTimestamp() + ", " +
stream.getWithLocation() + ", " +
stream.getSchema().toString(),
e);
}
// Link creation SQL.
final String linkSql =
"INSERT INTO observer_stream_link (" +
"observer_id, " +
"observer_stream_id) " +
"VALUES (?, ?)";
// Link the stream to the observer.
try {
getJdbcTemplate().update(
linkSql,
new Object[] {
observerKeyHolder.getKey().longValue(),
streamKeyHolder.getKey().longValue()
}
);
}
catch(org.springframework.dao.DataAccessException e) {
transactionManager.rollback(status);
throw new DataAccessException(
"Error executing SQL '" +
linkSql +
"' with parameters: " +
observerKeyHolder.getKey().longValue() + ", " +
streamKeyHolder.getKey().longValue(),
e);
}
}
// Commit the transaction.
try {
transactionManager.commit(status);
}
catch(TransactionException e) {
transactionManager.rollback(status);
throw new DataAccessException(
"Error while committing the transaction.",
e);
}
}
catch(TransactionException e) {
throw new DataAccessException(
"Error while attempting to rollback the transaction.",
e);
}
}
/*
* (non-Javadoc)
* @see org.ohmage.query.IObserverQueries#doesObserverExist(java.lang.String)
*/
@Override
public boolean doesObserverExist(
final String observerId)
throws DataAccessException {
String sql =
"SELECT EXISTS(SELECT id FROM observer WHERE observer_id = ?)";
try {
return
getJdbcTemplate().queryForObject(
sql,
new Object[] { observerId },
new SingleColumnRowMapper<Long>()) != 0;
}
catch(org.springframework.dao.DataAccessException e) {
throw new DataAccessException(
"Error executing SQL '" +
sql +
"' with parameter: " +
observerId);
}
}
/*
* (non-Javadoc)
* @see org.ohmage.query.IObserverQueries#getOwner(java.lang.String)
*/
@Override
public String getOwner(
final String observerId)
throws DataAccessException {
if(observerId == null) {
return null;
}
String sql =
"SELECT DISTINCT(u.username) " +
"FROM user u, observer o " +
"WHERE u.id = o.user_id " +
"AND o.observer_id = ?";
try {
return
getJdbcTemplate().queryForObject(
sql,
new Object[] { observerId },
String.class);
}
catch(org.springframework.dao.IncorrectResultSizeDataAccessException e) {
if(e.getActualSize() > 1) {
throw new DataAccessException(
"Multiple observers have the same ID: " + observerId,
e);
}
return null;
}
catch(org.springframework.dao.DataAccessException e) {
throw new DataAccessException(
"There was an error executing SQL '" +
sql +
"' with parameter: " +
observerId,
e);
}
}
/*
* (non-Javadoc)
* @see org.ohmage.query.IObserverQueries#getObservers(java.lang.String, java.lang.Long, long, long)
*/
public List<Observer> getObservers(
final String id,
final Long version,
final long numToSkip,
final long numToReturn)
throws DataAccessException {
// Build the SQL that will get all of the observers visible to the
// requesting user.
StringBuilder observerSql =
new StringBuilder(
"SELECT " +
"id, " +
"observer_id, " +
"version, " +
"name, " +
"description, " +
"version_string " +
"FROM observer o");
List<String> whereClauses = new LinkedList<String>();
List<Object> parameters = new LinkedList<Object>();
// Add the ID if it is present.
if(id != null) {
whereClauses.add("o.observer_id = ?");
parameters.add(id);
}
// Add the version if present.
if(version != null) {
whereClauses.add("o.version = ?");
parameters.add(version);
}
// Add the WHERE clauses to the query.
boolean firstPass = true;
for(String whereClause : whereClauses) {
if(firstPass) {
observerSql.append(" WHERE ");
firstPass = false;
}
else {
observerSql.append(" AND ");
}
observerSql.append(whereClause);
}
observerSql.append(" ORDER BY o.observer_id ASC, o.version DESC");
observerSql.append(" LIMIT ?, ?");
parameters.add(numToSkip);
parameters.add(numToReturn);
final Map<Long, Observer.Builder> observerBuilders =
new HashMap<Long, Observer.Builder>();
try {
getJdbcTemplate().query(
observerSql.toString(),
parameters.toArray(),
new RowMapper<Object> () {
/**
* Maps the row of data to a new observer builder.
*/
@Override
public Object mapRow(
final ResultSet rs,
final int rowNum)
throws SQLException {
Observer.Builder observerBuilder =
new Observer.Builder();
observerBuilder
.setId(rs.getString("observer_id"))
.setVersion(rs.getLong("version"))
.setName(rs.getString("name"))
.setDescription(rs.getString("description"))
.setVersionString(
rs.getString("version_string"));
observerBuilders.put(
rs.getLong("id"),
observerBuilder);
return null;
}
}
);
}
catch(org.springframework.dao.DataAccessException e) {
throw new DataAccessException(
"Error executing SQL '" +
observerSql +
"' with parameters: " +
parameters,
e);
}
final String streamSql =
"SELECT " +
"os.stream_id, " +
"os.version, " +
"os.name, " +
"os.description, " +
"os.with_id, " +
"os.with_timestamp, " +
"os.with_location, " +
"os.stream_schema " +
"FROM observer_stream os, observer_stream_link osl " +
"WHERE osl.observer_id = ? " +
"AND osl.observer_stream_id = os.id";
for(Long dbId : observerBuilders.keySet()) {
try {
observerBuilders
.get(dbId)
.addStreams(
getJdbcTemplate().query(
streamSql,
new Object[] { dbId },
new RowMapper<Observer.Stream>() {
/**
* Maps the row of data to a new stream.
*/
@Override
public Stream mapRow(
final ResultSet rs,
final int rowNum)
throws SQLException {
// Because the with_* values are optional and
// may be null, they must be retrieve in this
// special way.
Boolean withId, withTimestamp, withLocation;
withId = rs.getBoolean("with_id");
if(rs.wasNull()) {
withId = null;
}
withTimestamp =
rs.getBoolean("with_timestamp");
if(rs.wasNull()) {
withTimestamp = null;
}
withLocation = rs.getBoolean("with_location");
if(rs.wasNull()) {
withLocation = null;
}
try {
return new Observer.Stream(
rs.getString("stream_id"),
rs.getLong("version"),
rs.getString("name"),
rs.getString("description"),
withId,
withTimestamp,
withLocation,
rs.getString("stream_schema"));
}
catch(DomainException e) {
throw new SQLException(e);
}
}
}
)
);
}
catch(org.springframework.dao.DataAccessException e) {
throw new DataAccessException(
"Error executing SQL '" +
streamSql +
"' with parameter: " +
dbId,
e);
}
}
ArrayList<Observer> result =
new ArrayList<Observer>(observerBuilders.size());
for(Observer.Builder observerBuilder : observerBuilders.values()) {
try {
result.add(observerBuilder.build());
}
catch(DomainException e) {
throw new DataAccessException(
"There was a problem building an observer.",
e);
}
}
return result;
}
/*
* (non-Javadoc)
* @see org.ohmage.query.IObserverQueries#getGreatestObserverVersion(java.lang.String)
*/
@Override
public Long getGreatestObserverVersion(
final String id)
throws DataAccessException {
String sql =
"SELECT MAX(version) AS max_version " +
"FROM observer " +
"WHERE observer_id = ?";
try {
return
getJdbcTemplate().queryForLong(sql, new Object[] { id });
}
catch(org.springframework.dao.DataAccessException e) {
throw new DataAccessException(
"Error executing SQL '" +
sql +
"' with parameter: " +
id,
e);
}
}
/*
* (non-Javadoc)
* @see org.ohmage.query.IObserverQueries#getStreams(java.lang.String, java.lang.Long, java.lang.String, java.lang.Long, long, long)
*/
@Override
public Map<String, Collection<Observer.Stream>> getStreams(
final String username,
final String observerId,
final Long observerVersion,
final String streamId,
final Long streamVersion,
final long numToSkip,
final long numToReturn)
throws DataAccessException {
if(numToReturn == 0) {
return Collections.emptyMap();
}
// Create the default SQL.
StringBuilder sqlBuilder =
new StringBuilder(
"SELECT DISTINCT " +
"o.observer_id, " +
"os.stream_id, " +
"os.version, " +
"os.name, " +
"os.description, " +
"os.with_id, " +
"os.with_timestamp, " +
"os.with_location, " +
"os.stream_schema " +
"FROM " +
"observer o, " +
"observer_stream os, " +
"observer_stream_link osl " +
"WHERE o.id = osl.observer_id " +
"AND os.id = osl.observer_stream_id");
// Create the default set of parameters.
List<Object> parameters = new LinkedList<Object>();
if(username != null) {
sqlBuilder
.append(
" AND EXISTS (" +
"SELECT osd.id " +
"FROM user u, observer_stream_data osd " +
"WHERE u.username = ? " +
"AND u.id = osd.user_id " +
"AND osl.id = osd.observer_stream_link_id" +
")"
);
parameters.add(username);
}
// If querying about the observer's ID, add that WHERE clause and
// add the parameter.
if(observerId != null) {
sqlBuilder.append(" AND o.observer_id = ?");
parameters.add(observerId);
}
// If querying about the observer's version, add that WHERE clause
// and add the parameter.
if(observerVersion != null) {
sqlBuilder.append(" AND o.version = ?");
parameters.add(observerVersion);
}
// If querying about the stream's ID add the WHERE clause and the
// parameter.
if(streamId != null) {
sqlBuilder.append(" AND os.stream_id = ?");
parameters.add(streamId);
}
// If querying about the stream's version add the WHERE clause and the
// parameter.
if(streamVersion != null) {
sqlBuilder.append(" AND os.version = ?");
parameters.add(streamVersion);
}
// Add ordering to facilitate paging.
sqlBuilder
.append(
" ORDER BY o.observer_id, o.version, os.stream_id, os.version");
// Add the limits for paging.
sqlBuilder.append(" LIMIT ?, ?");
parameters.add(numToSkip);
parameters.add(numToReturn);
// Query for the results and add them to the result map.
final Map<String, Collection<Observer.Stream>> result =
new HashMap<String, Collection<Observer.Stream>>();
try {
getJdbcTemplate().query(
sqlBuilder.toString(),
parameters.toArray(),
new RowMapper<Object>() {
/**
* Maps the row of data to a new stream.
*/
@Override
public Object mapRow(
final ResultSet rs,
final int rowNum)
throws SQLException {
// Get the observer's ID.
String observerId = rs.getString("observer_id");
// Get the streams from the result.
Collection<Observer.Stream> streams =
result.get(observerId);
// If no collection exists for that observer ID yet,
// create a new collection and add it.
if(streams == null) {
streams = new LinkedList<Observer.Stream>();
result.put(observerId, streams);
}
// Because the with_* values are optional and
// may be null, they must be retrieve in this
// special way.
Boolean withId, withTimestamp, withLocation;
withId = rs.getBoolean("with_id");
if(rs.wasNull()) {
withId = null;
}
withTimestamp =
rs.getBoolean("with_timestamp");
if(rs.wasNull()) {
withTimestamp = null;
}
withLocation = rs.getBoolean("with_location");
if(rs.wasNull()) {
withLocation = null;
}
// Add the stream to its respective result list.
try {
streams
.add(
new Observer.Stream(
rs.getString("stream_id"),
rs.getLong("version"),
rs.getString("name"),
rs.getString("description"),
withId,
withTimestamp,
withLocation,
rs.getString("stream_schema")));
}
catch(DomainException e) {
throw new SQLException(e);
}
// Return nothing as it will never be used.
return null;
}
}
);
}
catch(org.springframework.dao.DataAccessException e) {
throw new DataAccessException(
"Error executing SQL '" +
sqlBuilder.toString() +
"' with parameters: " +
parameters,
e);
}
// Return the result.
return result;
}
/*
* (non-Javadoc)
* @see org.ohmage.query.IObserverQueries#getGreatestObserverVersion(java.lang.String)
*/
@Override
public Long getGreatestStreamVersion(
final String observerId,
final String streamId)
throws DataAccessException {
String sql =
"SELECT MAX(os.version) AS max_version " +
"FROM observer o, observer_stream os, observer_stream_link osl " +
"WHERE o.observer_id = ? " +
"AND os.stream_id = ? " +
"AND o.id = osl.observer_id " +
"AND osl.observer_stream_id = os.id";
try {
return
getJdbcTemplate().queryForLong(
sql,
new Object[] { observerId, streamId });
}
catch(org.springframework.dao.DataAccessException e) {
throw new DataAccessException(
"Error executing SQL '" +
sql +
"' with parameter: " +
observerId + ", " +
streamId,
e);
}
}
/*
* (non-Javadoc)
* @see org.ohmage.query.IObserverQueries#getDuplicateIds(java.lang.String, java.lang.String, java.util.Collection)
*/
@Override
public Collection<String> getDuplicateIds(
final String username,
final String observerId,
final String streamId,
final Collection<String> idsToCheck)
throws DataAccessException {
int numIds = idsToCheck.size();
if(numIds == 0) {
return Collections.emptyList();
}
StringBuilder sqlBuilder =
new StringBuilder(
"SELECT osd.uid " +
"FROM " +
"user u, " +
"observer o, " +
"observer_stream os, " +
"observer_stream_link osl, " +
"observer_stream_data osd " +
"WHERE u.username = ? " +
"AND o.observer_id = ? " +
"AND o.id = osl.observer_id " +
"AND osl.observer_stream_id = os.id " +
"AND os.stream_id = ? " +
"AND u.id = osd.user_id " +
"AND osl.id = osd.observer_stream_link_id " +
"AND osd.uid IN ");
sqlBuilder.append(StringUtils.generateStatementPList(numIds));
Collection<Object> parameters =
new ArrayList<Object>(idsToCheck.size() + 2);
parameters.add(username);
parameters.add(observerId);
parameters.add(streamId);
parameters.addAll(idsToCheck);
try {
return
getJdbcTemplate().query(
sqlBuilder.toString(),
parameters.toArray(),
new SingleColumnRowMapper<String>());
}
catch(org.springframework.dao.DataAccessException e) {
throw new DataAccessException(
"Error executing SQL '" +
sqlBuilder.toString() +
"' with parameters: " +
parameters,
e);
}
}
/*
* (non-Javadoc)
* @see org.ohmage.query.IObserverQueries#storeData(java.lang.String, java.util.Collection)
*/
@Override
public void storeData(
final String username,
final Observer observer,
final Collection<DataStream> data)
throws DataAccessException {
String sql =
"INSERT INTO observer_stream_data (" +
"user_id, " +
"observer_stream_link_id, " +
"uid, " +
"time, " +
"time_offset, " +
"time_adjusted, " +
"time_zone, " +
"location_timestamp, " +
"location_latitude, " +
"location_longitude, " +
"location_accuracy, " +
"location_provider, " +
"data) " +
"VALUES (" +
"(SELECT id FROM user WHERE username = ?), " +
"(" +
"SELECT osl.id " +
"FROM " +
"observer o, " +
"observer_stream os, " +
"observer_stream_link osl " +
"WHERE o.observer_id = ? " +
"AND o.version = ? " +
"AND os.stream_id = ? " +
"AND os.version = ? " +
"AND o.id = osl.observer_id " +
"AND os.id = osl.observer_stream_id" +
"), " +
"?, " +
"?, " +
"?, " +
"?, " +
"?, " +
"?, " +
"?, " +
"?, " +
"?, " +
"?, " +
"?)";
List<Object[]> args = new ArrayList<Object[]>(data.size());
for(DataStream currData : data) {
MetaData metaData = currData.getMetaData();
String id = null;
DateTime timestamp = null;
Location location = null;
if(metaData != null) {
id = metaData.getId();
timestamp = metaData.getTimestamp();
location = metaData.getLocation();
}
Long time = (timestamp == null) ? null : timestamp.getMillis();
Integer timeOffset =
(timestamp == null) ?
null :
timestamp.getZone().getOffset(timestamp);
Long timeAdjusted =
(timestamp == null) ? null : time + timeOffset;
String timeZoneId =
(timestamp == null) ? null : timestamp.getZone().getID();
args.add(
new Object[] {
username,
observer.getId(),
observer.getVersion(),
currData.getStream().getId(),
currData.getStream().getVersion(),
id,
time,
timeOffset,
timeAdjusted,
timeZoneId,
(location == null) ? null : (new DateTime(location.getTime(), location.getTimeZone())).toString(),
(location == null) ? null : location.getLatitude(),
(location == null) ? null : location.getLongitude(),
(location == null) ? null : location.getAccuracy(),
(location == null) ? null : location.getProvider(),
currData.getData().toString()
}
);
}
// Create the transaction.
DefaultTransactionDefinition def = new DefaultTransactionDefinition();
def.setName("Inserting stream data.");
try {
// Begin the transaction.
PlatformTransactionManager transactionManager =
new DataSourceTransactionManager(getDataSource());
TransactionStatus status = transactionManager.getTransaction(def);
try {
getJdbcTemplate().batchUpdate(sql, args);
}
catch(org.springframework.dao.DataAccessException e) {
transactionManager.rollback(status);
throw new DataAccessException(
"Error executing SQL '" + sql +"'.",
e);
}
// Commit the transaction.
try {
transactionManager.commit(status);
}
catch(TransactionException e) {
transactionManager.rollback(status);
throw new DataAccessException(
"Error while committing the transaction.",
e);
}
}
catch(TransactionException e) {
throw new DataAccessException(
"Error while attempting to rollback the transaction.",
e);
}
}
/*
* (non-Javadoc)
* @see org.ohmage.query.IObserverQueries#storeInvalidData(java.lang.String, org.ohmage.domain.Observer, java.util.Collection)
*/
@Override
public void storeInvalidData(
final String username,
final Observer observer,
final Collection<InvalidPoint> invalidData)
throws DataAccessException {
String sql =
"INSERT INTO observer_stream_data_invalid (" +
"user_id, " +
"observer_id, " +
"time_recorded, " +
"point_index, " +
"reason, " +
"data) " +
"VALUES (" +
"(SELECT id FROM user WHERE username = ?), " +
"(" +
"SELECT id " +
"FROM observer " +
"WHERE observer_id = ? " +
"AND version = ?" +
"), " +
"?, " +
"?, " +
"?, " +
"?)";
List<Object[]> args = new ArrayList<Object[]>(invalidData.size());
for(InvalidPoint currData : invalidData) {
args.add(
new Object[] {
username,
observer.getId(),
observer.getVersion(),
System.currentTimeMillis(),
currData.getIndex(),
currData.getReason(),
currData.getData()
}
);
}
// Create the transaction.
DefaultTransactionDefinition def = new DefaultTransactionDefinition();
def.setName("Inserting invalid stream data.");
try {
// Begin the transaction.
PlatformTransactionManager transactionManager =
new DataSourceTransactionManager(getDataSource());
TransactionStatus status = transactionManager.getTransaction(def);
try {
getJdbcTemplate().batchUpdate(sql, args);
}
catch(org.springframework.dao.DataAccessException e) {
transactionManager.rollback(status);
throw new DataAccessException(
"Error executing SQL '" + sql +"'.",
e);
}
// Commit the transaction.
try {
transactionManager.commit(status);
}
catch(TransactionException e) {
transactionManager.rollback(status);
throw new DataAccessException(
"Error while committing the transaction.",
e);
}
}
catch(TransactionException e) {
throw new DataAccessException(
"Error while attempting to rollback the transaction.",
e);
}
}
/*
* (non-Javadoc)
* @see org.ohmage.query.IObserverQueries#readData(org.ohmage.domain.Observer.Stream, java.lang.String, java.lang.String, java.lang.Long, org.joda.time.DateTime, org.joda.time.DateTime, boolean, long, long)
*/
@Override
public List<DataStream> readData(
final Stream stream,
final String username,
final String observerId,
final Long observerVersion,
final DateTime startDate,
final DateTime endDate,
final boolean chronological,
final long numToSkip,
final long numToReturn)
throws DataAccessException {
// Create the initial query and required set of parameters.
StringBuilder builder =
new StringBuilder(
"SELECT " +
"osd.uid, " +
"osd.time, " +
"osd.time_zone, " +
"osd.location_timestamp, " +
"osd.location_latitude, " +
"osd.location_longitude, " +
"osd.location_accuracy, " +
"osd.location_provider, " +
"osd.data " +
"FROM " +
"observer_stream_data AS osd " +
"LEFT JOIN observer_stream_link AS osl " +
"ON osd.observer_stream_link_id = osl.id " +
"WHERE " +
"osd.user_id = (" +
"SELECT id " +
"FROM user " +
"WHERE username = ?" +
") " +
"AND osl.observer_id = " +
"(SELECT id FROM observer WHERE observer_id = ?");
List<Object> parameters = new LinkedList<Object>();
parameters.add(username);
parameters.add(observerId);
// If the observer's version is specified, add it to the sub-query.
if(observerVersion != null) {
builder.append(" AND o.version = ?)");
parameters.add(observerVersion);
}
// Otherwise, end the subquery.
else {
builder.append(')');
}
// Add the remainder of the required parameters and their query
// components.
builder
.append(
" AND osl.observer_stream_id = " +
"(" +
"SELECT id " +
"FROM observer_stream " +
"WHERE stream_id = ? " +
"AND version = ?" +
")");
parameters.add(stream.getId());
parameters.add(stream.getVersion());
// If a start date is given, add it to the overall query.
if(startDate != null) {
builder.append(" AND osd.time_adjusted >= ?");
parameters.add(startDate.getMillis());
}
// If an end date is given, add it to the overall query.
if(endDate != null) {
builder.append(" AND osd.time_adjusted <= ?");
parameters.add(endDate.getMillis());
}
// Add the ordering based on whether or not these should be
// chronological or reverse chronological.
builder
.append(
" ORDER BY osd.time " + ((chronological) ? "ASC" : "DESC"));
// Limit the number of results based on the paging.
builder.append(" LIMIT ?, ?");
parameters.add(numToSkip);
parameters.add(numToReturn);
// Create a JSON factory, which will be used by each data point to
// deserialize its data into a JsonNode.
final JsonFactory jsonFactory = new MappingJsonFactory();
try {
return
getJdbcTemplate().query(
builder.toString(),
parameters.toArray(),
new RowMapper<DataStream>() {
/**
* Decodes the resulting data into a data stream.
*/
@Override
public DataStream mapRow(
final ResultSet rs,
final int rowNum)
throws SQLException {
MetaData.Builder metaDataBuilder =
new MetaData.Builder();
String id = rs.getString("osd.uid");
if(id != null) {
metaDataBuilder.setId(id);
}
Long time = rs.getLong("osd.time");
if(time != null) {
metaDataBuilder.setTimestamp(
new DateTime(
time,
DateTimeZone.forID(
rs.getString("osd.time_zone"))));
}
String locationTimestampString =
rs.getString("location_timestamp");
if(locationTimestampString != null) {
Location location;
try {
location =
new Location(
ISODateTimeFormat
.dateTime()
.parseDateTime(
rs.getString(
"osd.location_timestamp")),
rs.getDouble("osd.location_latitude"),
rs.getDouble("osd.location_longitude"),
rs.getDouble("osd.location_accuracy"),
rs.getString("osd.location_provider"));
}
catch(IllegalArgumentException e) {
throw new SQLException(
"The timestamp in the database is corrupted.",
e);
}
catch(NullPointerException e) {
throw new SQLException(
"A double in the database is corrupted.",
e);
}
catch(DomainException e) {
throw new SQLException(
"Could not create the location object.",
e);
}
metaDataBuilder.setLocation(location);
}
JsonNode data;
try {
JsonParser parser =
jsonFactory
.createJsonParser(
rs.getString("osd.data"));
data = parser.readValueAsTree();
}
catch(JsonParseException e) {
throw new SQLException(
"The data in the database is invalid: " +
id,
e);
}
catch(IOException e) {
throw new SQLException(
"There was a problem reading the data: " +
id,
e);
}
try {
return new DataStream(
stream,
metaDataBuilder.build(),
data);
}
catch(DomainException e) {
throw new SQLException(
"Could not create the data stream.",
e);
}
}
});
}
catch(org.springframework.dao.DataAccessException e) {
throw new DataAccessException(
"Error executing SQL '" +
builder.toString() +
"' with parameters: " +
parameters,
e);
}
}
/*
* (non-Javadoc)
* @see org.ohmage.query.IObserverQueries#readInvalidData(org.ohmage.domain.Observer, org.joda.time.DateTime, org.joda.time.DateTime, long, long)
*/
@Override
public Collection<InvalidPoint> readInvalidData(
final Observer observer,
final DateTime startDate,
final DateTime endDate,
final long numToSkip,
final long numToReturn)
throws DataAccessException {
// Build the SQL.
StringBuilder sqlBuilder =
new StringBuilder(
"SELECT osdi.point_index, osdi.reason, osdi.data " +
"FROM " +
"observer o, " +
"observer_stream_data_invalid osdi " +
"WHERE o.id = osdi.observer_id " +
"AND o.observer_id = ? " +
"AND o.version = ? ");
// Create the list of parameters.
List<Object> parameters = new LinkedList<Object>();
parameters.add(observer.getId());
parameters.add(observer.getVersion());
// If the start date was given, add it.
if(startDate != null) {
sqlBuilder.append("AND time_recorded >= ? ");
parameters.add(startDate.getMillis());
}
// If the end date was given, add it.
if(endDate != null) {
sqlBuilder.append("AND time_recorded <= ? ");
parameters.add(endDate.getMillis());
}
// Add the ordering.
sqlBuilder.append("ORDER BY time_recorded ");
// Add the paging parameters.
sqlBuilder.append("LIMIT ?, ?");
parameters.add(numToSkip);
parameters.add(numToReturn);
try {
return
getJdbcTemplate()
.query(
sqlBuilder.toString(),
parameters.toArray(),
new RowMapper<InvalidPoint>() {
/*
* (non-Javadoc)
* @see org.springframework.jdbc.core.RowMapper#mapRow(java.sql.ResultSet, int)
*/
@Override
public InvalidPoint mapRow(
final ResultSet resultSet,
final int rowNum)
throws SQLException {
// Create the point and return it.
return
new InvalidPoint(
resultSet.getLong("point_index"),
resultSet.getString("data"),
resultSet.getString("reason"),
null);
}
}
);
}
catch(org.springframework.dao.DataAccessException e) {
throw new DataAccessException(
"Error executing SQL '" +
sqlBuilder.toString() +
"' with parameters: " +
parameters,
e);
}
}
/*
* (non-Javadoc)
* @see org.ohmage.query.IObserverQueries#updateObserver(java.lang.String, org.ohmage.domain.Observer, java.util.Collection)
*/
@Override
public void updateObserver(
final String username,
final Observer observer,
final Map<String, Long> unchangedStreamIds)
throws DataAccessException {
if(username == null) {
throw new DataAccessException("The username is null.");
}
if(observer == null) {
throw new DataAccessException("The observer is null.");
}
if(unchangedStreamIds == null) {
throw new DataAccessException(
"The collection of unchanged IDs is null.");
}
// Create the transaction.
DefaultTransactionDefinition def = new DefaultTransactionDefinition();
def.setName("Creating an observer.");
try {
// Begin the transaction.
PlatformTransactionManager transactionManager =
new DataSourceTransactionManager(getDataSource());
TransactionStatus status = transactionManager.getTransaction(def);
// Observer creation SQL.
final String observerSql =
"INSERT INTO observer (" +
"observer_id, " +
"version, " +
"name, " +
"description, " +
"version_string, " +
"user_id) " +
"VALUES (?, ?, ?, ?, ?, " +
"(SELECT id FROM user WHERE username = ?))";
// Observer creation statement with parameters.
PreparedStatementCreator observerCreator =
new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(
final Connection connection)
throws SQLException {
PreparedStatement ps =
connection.prepareStatement(
observerSql,
new String[] { "id" });
ps.setString(1, observer.getId());
ps.setLong(2, observer.getVersion());
ps.setString(3, observer.getName());
ps.setString(4, observer.getDescription());
ps.setString(5, observer.getVersionString());
ps.setString(6, username);
return ps;
}
};
// The auto-generated key for the observer.
KeyHolder observerKeyHolder = new GeneratedKeyHolder();
// Create the observer.
try {
getJdbcTemplate().update(observerCreator, observerKeyHolder);
}
catch(org.springframework.dao.DataAccessException e) {
transactionManager.rollback(status);
throw new DataAccessException(
"Error executing SQL '" +
observerSql +
"' with parameters: " +
observer.getId() + ", " +
observer.getVersion() + ", " +
observer.getName() + ", " +
observer.getDescription() + ", " +
observer.getVersionString(),
e);
}
// Get the observer ID.
long observerDbId = observerKeyHolder.getKey().longValue();
// Stream creation SQL.
final String streamSql =
"INSERT INTO observer_stream (" +
"stream_id, " +
"version, " +
"name, " +
"description, " +
"with_id, " +
"with_timestamp, " +
"with_location, " +
"stream_schema) " +
"VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
// Observer-stream link SQL.
final String observerStreamSql =
"INSERT INTO observer_stream_link(" +
"observer_id, " +
"observer_stream_id" +
") " +
"VALUES (" +
"?, " +
"?" +
")";
// If all we are doing is grabbing the database ID for the stream,
// then this will take care of that. Note: The observer's ID must
// be put in twice to help get the correct version.
final String getStreamIdSql =
"SELECT os.id " +
"FROM " +
"observer o, " +
"observer_stream os, " +
"observer_stream_link osl " +
"WHERE o.observer_id = ? " +
"AND o.version = " +
"(" +
"SELECT version " +
"FROM observer " +
"WHERE observer_id = ? " +
"ORDER BY version DESC " +
"LIMIT 1, 1" +
") " +
"AND os.stream_id = ? " +
"AND os.version = ? " +
"AND o.id = osl.observer_id " +
"AND os.id = osl.observer_stream_id";
// For each stream, insert it and link it to the observer.
for(final Stream stream : observer.getStreamsMap().values()) {
// Get the stream's ID.
final String streamId = stream.getId();
// The stream's database identifier.
Long streamDbId;
// If the stream already exists in the map of stream IDs and
// versions, then get the stream's database ID for linking.
if(unchangedStreamIds.containsKey(streamId)) {
// Attempt to get the stream's database ID.
try {
streamDbId =
getJdbcTemplate()
.queryForLong(
getStreamIdSql,
new Object[] {
observer.getId(),
observer.getId(),
streamId,
stream.getVersion()
}
);
}
catch(org.springframework.dao.DataAccessException e) {
transactionManager.rollback(status);
throw new DataAccessException(
"Error executing SQL '" +
getStreamIdSql +
"' with parameters: " +
observer.getId() + ", " +
observer.getId() + ", " +
streamId + ", " +
stream.getVersion(),
e);
}
}
// Otherwise, add the new stream and retain its database ID.
else {
// Get the stream's schema as a string.
final String schema;
try {
schema = stream.getSchema().readValueAsTree().toString();
}
catch(JsonProcessingException e) {
transactionManager.rollback(status);
throw new DataAccessException(
"Error parsing the schema.",
e);
}
catch(IOException e) {
transactionManager.rollback(status);
throw new DataAccessException(
"Error reading the schema.",
e);
}
// Stream creation statement with parameters.
PreparedStatementCreator streamCreator =
new PreparedStatementCreator() {
/**
* Create the stream insertion statement.
*/
@Override
public PreparedStatement createPreparedStatement(
final Connection connection)
throws SQLException {
PreparedStatement ps =
connection.prepareStatement(
streamSql,
new String[] { "id" });
ps.setString(1, streamId);
ps.setLong(2, stream.getVersion());
ps.setString(3, stream.getName());
ps.setString(4, stream.getDescription());
ps.setObject(5, stream.getWithId());
ps.setObject(6, stream.getWithTimestamp());
ps.setObject(7, stream.getWithLocation());
ps.setString(8, schema);
return ps;
}
};
// The auto-generated key for the observer.
KeyHolder streamKeyHolder = new GeneratedKeyHolder();
// Create the observer.
try {
getJdbcTemplate().update(streamCreator, streamKeyHolder);
}
catch(org.springframework.dao.DataAccessException e) {
transactionManager.rollback(status);
throw new DataAccessException(
"Error executing SQL '" +
streamSql +
"' with parameters: " +
streamId + ", " +
stream.getVersion() + ", " +
stream.getName() + ", " +
stream.getDescription() + ", " +
stream.getWithId() + ", " +
stream.getWithTimestamp() + ", " +
stream.getWithLocation() + ", " +
schema,
e);
}
// Get the observer ID.
streamDbId = streamKeyHolder.getKey().longValue();
}
// Link the stream to the observer.
try {
getJdbcTemplate()
.update(
observerStreamSql,
new Object[] { observerDbId, streamDbId });
}
catch(org.springframework.dao.DataAccessException e) {
transactionManager.rollback(status);
throw new DataAccessException(
"Error executing SQL '" +
observerStreamSql +
"' with parameters: " +
observerDbId + ", " +
streamDbId,
e);
}
}
// Commit the transaction.
try {
transactionManager.commit(status);
}
catch(TransactionException e) {
transactionManager.rollback(status);
throw new DataAccessException(
"Error while committing the transaction.",
e);
}
}
catch(TransactionException e) {
throw new DataAccessException(
"Error while attempting to rollback the transaction.",
e);
}
}
} | Fixed a bug in observer/stream reading.
The observer/stream read query had a bug since its refactoring. It has been fixed.
| src/org/ohmage/query/impl/ObserverQueries.java | Fixed a bug in observer/stream reading. | <ide><path>rc/org/ohmage/query/impl/ObserverQueries.java
<ide>
<ide> // If the observer's version is specified, add it to the sub-query.
<ide> if(observerVersion != null) {
<del> builder.append(" AND o.version = ?)");
<add> builder.append(" AND version = ?)");
<ide> parameters.add(observerVersion);
<ide> }
<ide> // Otherwise, end the subquery. |
|
JavaScript | mit | 16c9d2be50b943b42ad3314f764616ce40d11189 | 0 | EdmonJiang/FA_Inventory,EdmonJiang/FA_Inventory | var express = require('express');
var router = express.Router();
var Pcinfo = require('../models/pcinfo.js');
var userinfo = {};
/* GET home page. */
router.get('/', function(req, res, next) {
Pcinfo.find({}).exec(function(err, pcinfos){
if (err){return next(new Error('could not find data!'))};
res.render('index', {pcinfos: pcinfos, currentUrl: '/index'});
})
});
router.post('/', function(req, res, next){
console.log(req.body);
userinfo = req.body;
res.end();
if(userinfo.ComputerName){
Pcinfo.findOne({ComputerName:userinfo.ComputerName}, function(err, doc){
if(doc){
for(var i in userinfo){
if(userinfo.hasOwnProperty(i)){
doc[i] = userinfo[i];
}
}
doc.updated = new Date;
doc.increment();
doc.save(function(err){
if (err){return next(new Error('save failed!'))};
console.log('save successful');
});
}else{
var pcinfo = new Pcinfo(userinfo);
pcinfo.save(function(err){
if (err){return next(new Error('save failed!'))};
})
}
})
}
});
router.get('/details/:cn', function(req, res, next){
var computer = {};
if(req.params.cn){
computer.ComputerName = req.params.cn;
Pcinfo.findOne(computer, function(err, details){
if (err || !details){
//return next(new Error('could not find the pc for delete!'));
res.render('error', {message: 'the computer does not exist.',error:{status:404}})
}else{
var objpc = {};
for(var prop in details._doc){
if(details._doc.hasOwnProperty(prop)){
objpc[prop]=details._doc[prop];
}
}
delete objpc._id;
res.render('details', {computer: objpc});
};
})
}
})
router.post('/details/:cn', function(req, res, next){
var objpc = {};
objpc.ComputerName = req.params.cn;
if(req.body){
Pcinfo.update(objpc, req.body, {upsert:false}, function(err){
if(err){
//console.log('update failed');
res.end('failed');
}
//console.log('update successful');
res.end('successful');
})
}
})
router.get('/delete/:cn', function(req, res, next){
var computer = {};
if(req.params.cn){
computer.ComputerName = req.params.cn;
Pcinfo.findOneAndRemove(computer).exec(function(err){
if (err){return next(new Error('could not find the pc!'))};
computer.status = 'This computer has been deleted!'
res.render('details', {computer: computer});
//res.redirect('/');
})
}
})
module.exports = router;
| routes/index.js | var express = require('express');
var router = express.Router();
var Pcinfo = require('../models/pcinfo.js');
var userinfo = {};
/* GET home page. */
router.get('/', function(req, res, next) {
Pcinfo.find({}).exec(function(err, pcinfos){
if (err){return next(new Error('could not find data!'))};
res.render('index', {pcinfos: pcinfos, currentUrl: '/index'});
})
});
router.post('/', function(req, res, next){
console.log(req.body);
userinfo = req.body;
res.end();
if(userinfo.ComputerName){
Pcinfo.findOne({ComputerName:userinfo.ComputerName}, function(err, doc){
if(doc){
for(var i in userinfo){
if(userinfo.hasOwnProperty(i)){
doc[i] = userinfo[i];
}
}
doc.updated = new Date;
doc.save(function(err){
if (err){return next(new Error('save failed!'))};
console.log('save successful');
});
}else{
var pcinfo = new Pcinfo(userinfo);
pcinfo.save(function(err){
if (err){return next(new Error('save failed!'))};
})
}
})
}
});
router.get('/details/:cn', function(req, res, next){
var computer = {};
if(req.params.cn){
computer.ComputerName = req.params.cn;
Pcinfo.findOne(computer, function(err, details){
if (err || !details){
//return next(new Error('could not find the pc for delete!'));
res.render('error', {message: 'the computer does not exist.',error:{status:404}})
}else{
var objpc = {};
for(var prop in details._doc){
if(details._doc.hasOwnProperty(prop)){
objpc[prop]=details._doc[prop];
}
}
delete objpc.__v;
delete objpc._id;
res.render('details', {computer: objpc});
};
})
}
})
router.post('/details/:cn', function(req, res, next){
var objpc = {};
objpc.ComputerName = req.params.cn;
if(req.body){
Pcinfo.update(objpc, req.body, {upsert:false}, function(err){
if(err){
//console.log('update failed');
res.end('failed');
}
//console.log('update successful');
res.end('successful');
})
}
})
router.get('/delete/:cn', function(req, res, next){
var computer = {};
if(req.params.cn){
computer.ComputerName = req.params.cn;
Pcinfo.findOneAndRemove(computer).exec(function(err){
if (err){return next(new Error('could not find the pc!'))};
computer.status = 'This computer has been deleted!'
res.render('details', {computer: computer});
//res.redirect('/');
})
}
})
module.exports = router;
| show __v, increment after updated
| routes/index.js | show __v, increment after updated | <ide><path>outes/index.js
<ide> }
<ide> }
<ide> doc.updated = new Date;
<add> doc.increment();
<ide> doc.save(function(err){
<ide> if (err){return next(new Error('save failed!'))};
<ide> console.log('save successful');
<ide> objpc[prop]=details._doc[prop];
<ide> }
<ide> }
<del> delete objpc.__v;
<ide> delete objpc._id;
<ide> res.render('details', {computer: objpc});
<ide> }; |
|
Java | apache-2.0 | error: pathspec 'SCUOpenBISImporter/ch/eth/scu/importer/gui/components/viewers/XMLFileNode.java' did not match any file(s) known to git
| 0868434de4bb7f5596634a2ca2b0fd3a638623e3 | 1 | aarpon/obit_annotation_tool | package ch.eth.scu.importer.gui.components.viewers;
import ch.eth.scu.importer.gui.descriptors.AbstractDescriptor;
/**
* Customized Node to be used in a JTree allowing different icons for different
* Node types
* @author Aaron Ponti
*/
public class XMLFileNode extends CustomTreeNode {
private static final long serialVersionUID = 1L;
public XMLFileNode(AbstractDescriptor object) {
super(object);
this.type = object.getType();
}
public javax.swing.Icon getIcon() {
return new javax.swing.ImageIcon(getClass().getResource("xml.png"));
}
public String getTooltip() {
return "XML file";
}
} | SCUOpenBISImporter/ch/eth/scu/importer/gui/components/viewers/XMLFileNode.java | Forgot to add XMLFileNode.java that replaces XMLNode.java.
| SCUOpenBISImporter/ch/eth/scu/importer/gui/components/viewers/XMLFileNode.java | Forgot to add XMLFileNode.java that replaces XMLNode.java. | <ide><path>CUOpenBISImporter/ch/eth/scu/importer/gui/components/viewers/XMLFileNode.java
<add>package ch.eth.scu.importer.gui.components.viewers;
<add>
<add>import ch.eth.scu.importer.gui.descriptors.AbstractDescriptor;
<add>
<add>/**
<add> * Customized Node to be used in a JTree allowing different icons for different
<add> * Node types
<add> * @author Aaron Ponti
<add> */
<add>public class XMLFileNode extends CustomTreeNode {
<add>
<add> private static final long serialVersionUID = 1L;
<add>
<add> public XMLFileNode(AbstractDescriptor object) {
<add> super(object);
<add> this.type = object.getType();
<add> }
<add>
<add> public javax.swing.Icon getIcon() {
<add> return new javax.swing.ImageIcon(getClass().getResource("xml.png"));
<add> }
<add>
<add> public String getTooltip() {
<add> return "XML file";
<add> }
<add>} |
|
Java | apache-2.0 | e893b2686db272bb3588466eee6a4c42d84350a7 | 0 | jpodeszwik/mifos,maduhu/mifos-head,jpodeszwik/mifos,maduhu/mifos-head,maduhu/head,maduhu/head,AArhin/head,maduhu/mifos-head,AArhin/head,vorburger/mifos-head,vorburger/mifos-head,maduhu/head,AArhin/head,jpodeszwik/mifos,AArhin/head,jpodeszwik/mifos,maduhu/mifos-head,maduhu/mifos-head,AArhin/head,maduhu/head,maduhu/head,vorburger/mifos-head,vorburger/mifos-head | /*
* Copyright (c) 2005-2009 Grameen Foundation USA
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*
* See also http://www.apache.org/licenses/LICENSE-2.0.html for an
* explanation of the license and how it is applied.
*/
package org.mifos.framework;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.Locale;
import java.util.Properties;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import org.mifos.application.accounts.financial.util.helpers.FinancialInitializer;
import org.mifos.application.configuration.business.MifosConfiguration;
import org.mifos.config.AccountingRules;
import org.mifos.config.ClientRules;
import org.mifos.config.Localization;
import org.mifos.config.ProcessFlowRules;
import org.mifos.framework.components.audit.util.helpers.AuditConfigurtion;
import org.mifos.framework.components.batchjobs.MifosScheduler;
import org.mifos.framework.components.configuration.business.Configuration;
import org.mifos.framework.components.logger.LoggerConstants;
import org.mifos.framework.components.logger.MifosLogManager;
import org.mifos.framework.components.logger.MifosLogger;
import org.mifos.framework.exceptions.AppNotConfiguredException;
import org.mifos.framework.exceptions.ApplicationException;
import org.mifos.framework.exceptions.HibernateProcessException;
import org.mifos.framework.exceptions.HibernateStartUpException;
import org.mifos.framework.exceptions.LoggerConfigurationException;
import org.mifos.framework.exceptions.SystemException;
import org.mifos.framework.exceptions.XMLReaderException;
import org.mifos.framework.hibernate.helper.StaticHibernateUtil;
import org.mifos.framework.persistence.DatabaseVersionPersistence;
import org.mifos.framework.security.authorization.AuthorizationManager;
import org.mifos.framework.security.authorization.HierarchyManager;
import org.mifos.framework.security.util.ActivityMapper;
import org.mifos.framework.spring.SpringUtil;
import org.mifos.framework.struts.plugin.helper.EntityMasterData;
import org.mifos.framework.struts.tags.XmlBuilder;
import org.mifos.framework.util.StandardTestingService;
import org.mifos.framework.util.helpers.Money;
/**
* This class should prepare all the sub-systems that are required by the app.
* Cleanup should also happen here when the application is shutdown.
*/
public class ApplicationInitializer implements ServletContextListener, ServletRequestListener {
private static MifosLogger LOG = null;
private static class DatabaseError {
boolean isError = false;
DatabaseErrorCode errorCode = DatabaseErrorCode.NO_DATABASE_ERROR;
String errmsg = "";
Throwable error = null;
void logError() {
LOG.fatal(errmsg, false, null, error);
}
}
public static void setDatabaseError(DatabaseErrorCode errcode, String errmsg, Throwable error) {
databaseError.isError = true;
databaseError.errorCode = errcode;
databaseError.error = error;
databaseError.errmsg = errmsg;
}
public static void clearDatabaseError() {
databaseError.isError = false;
databaseError.errorCode = DatabaseErrorCode.NO_DATABASE_ERROR;
databaseError.error = null;
databaseError.errmsg = null;
}
private static String getDatabaseConnectionInfo() {
StandardTestingService standardTestingService = new StandardTestingService();
Properties hibernateCfg = new Properties();
String info = "Using Mifos database connection settings";
try {
hibernateCfg = standardTestingService.getDatabaseConnectionSettings();
info += " from file(s): " + Arrays.toString(standardTestingService.getAllSettingsFilenames());
} catch (IOException e) {
/*
* not sure if we can actually do anything useful with this
* exception since we're likely running during container
* initialization
*/
e.printStackTrace();
}
info += " Connection URL=" + hibernateCfg.getProperty("hibernate.connection.url");
info += ". Username=" + hibernateCfg.getProperty("hibernate.connection.username");
info += ". Password=********";
return info;
}
private static DatabaseError databaseError = new DatabaseError();
public void contextInitialized(ServletContextEvent ctx) {
init();
}
public void init() {
try {
synchronized (ApplicationInitializer.class) {
initializeLogger();
initializeHibernate();
/*
* getLogger() cannot be called statically (ie: when
* initializing LOG) because MifosLogManager.initializeLogger()
* hasn't been called yet, so MifosLogManager.loggerRepository
* will be null.
*/
LOG = MifosLogManager.getLogger(LoggerConstants.FRAMEWORKLOGGER);
LOG.info("Logger has been initialised", false, null);
LOG.info(getDatabaseConnectionInfo(), false, null);
DatabaseVersionPersistence persistence = new DatabaseVersionPersistence();
try {
/*
* This is an easy way to force an actual database query to
* happen via Hibernate. Simply opening a Hibernate session
* may not actually connect to the database.
*/
persistence.isVersioned();
} catch (Throwable t) {
setDatabaseError(DatabaseErrorCode.CONNECTION_FAILURE, "Unable to connect to database.", t);
}
if (!databaseError.isError) {
try {
persistence.upgradeDatabase();
} catch (Throwable t) {
setDatabaseError(DatabaseErrorCode.UPGRADE_FAILURE, "Failed to upgrade database.", t);
}
}
if (databaseError.isError) {
databaseError.logError();
} else {
// this method is called so that supported locales will be
// loaded
// from db and stored in cache for later use
Localization.getInstance().init();
// Check ClientRules configuration in db and config file(s)
// for errors. Also caches ClientRules values.
ClientRules.init();
// Check ProcessFlowRules configuration in db and config
// file(s) for errors.
ProcessFlowRules.init();
initializeSecurity();
Money.setDefaultCurrency(AccountingRules.getMifosCurrency());
// 1/4/08 Hopefully a temporary change to force Spring
// to initialize here (rather than in struts-config.xml
// prior to loading label values into a
// cache in MifosConfiguration. When the use of the
// cache is refactored away, we should be able to move
// back to the struts based Spring initialization
SpringUtil.initializeSpring();
// Spring must be initialized before FinancialInitializer
FinancialInitializer.initialize();
EntityMasterData.getInstance().init();
initializeEntityMaster();
(new MifosScheduler()).registerTasks();
Configuration.getInstance();
MifosConfiguration.getInstance().init();
configureAuditLogValues(Localization.getInstance().getMainLocale());
}
}
} catch (Exception e) {
String errMsgStart = "unable to start Mifos web application";
if (null == LOG) {
System.err.println(errMsgStart + " and logger is not available!");
e.printStackTrace();
} else {
LOG.error(errMsgStart, e);
}
throw new Error(e);
}
}
public static void printDatabaseError(XmlBuilder xml, int dbVersion) {
synchronized (ApplicationInitializer.class) {
if (databaseError.isError) {
addDatabaseErrorMessage(xml, dbVersion);
} else {
addNoFurtherDetailsMessage(xml);
}
}
}
private static void addNoFurtherDetailsMessage(XmlBuilder xml) {
xml.startTag("p");
xml.text("I don't have any further details, unfortunately.");
xml.endTag("p");
xml.text("\n");
}
private static void addDatabaseErrorMessage(XmlBuilder xml, int dbVersion) {
xml.startTag("p", "style", "font-weight: bolder; color: red; font-size: x-large;");
xml.text(databaseError.errmsg);
xml.text("\n");
if (databaseError.errorCode.equals(DatabaseErrorCode.UPGRADE_FAILURE)) {
addDatabaseVersionMessage(xml, dbVersion);
}
xml.endTag("p");
if (databaseError.errorCode.equals(DatabaseErrorCode.CONNECTION_FAILURE)) {
addConnectionFailureMessage(xml);
}
xml.text("\n");
xml.startTag("p");
xml.text("More details:");
xml.endTag("p");
xml.text("\n");
if (null != databaseError.error.getCause()) {
xml.startTag("p", "style", "font-weight: bolder; color: blue;");
xml.text(databaseError.error.getCause().toString());
xml.endTag("p");
xml.text("\n");
}
xml.startTag("p", "style", "font-weight: bolder; color: blue;");
xml.text(getDatabaseConnectionInfo());
xml.endTag("p");
xml.text("\n");
addStackTraceHtml(xml);
}
private static void addConnectionFailureMessage(XmlBuilder xml) {
xml.startTag("p");
xml.text("Possible causes:");
xml.startTag("ul");
xml.startTag("li");
xml.text("MySQL is not running");
xml.endTag("li");
xml.startTag("li");
xml.text("MySQL is listening on a different port than Mifos is expecting");
xml.endTag("li");
xml.startTag("li");
xml.text("incorrect username or password");
xml.endTag("li");
xml.endTag("ul");
xml.endTag("p");
xml.text("\n");
xml.startTag("p");
xml.startTag("a", "href",
"http://www.mifos.org/knowledge/support/deploying-mifos/configuration/guide");
xml.text("More about configuring your database connection.");
xml.endTag("a");
xml.endTag("p");
xml.text("\n");
}
private static void addDatabaseVersionMessage(XmlBuilder xml, int dbVersion) {
if (dbVersion == -1) {
xml.text("Database is too old to have a version.\n");
} else {
xml.text("Database Version = " + dbVersion + "\n");
}
xml.text("Application Version = " + DatabaseVersionPersistence.APPLICATION_VERSION + ".\n");
}
private static void addStackTraceHtml(XmlBuilder xml) {
xml.startTag("p");
xml.text("Stack trace:");
xml.endTag("p");
xml.text("\n");
xml.startTag("pre");
StringWriter stackTrace = new StringWriter();
databaseError.error.printStackTrace(new PrintWriter(stackTrace));
xml.text("\n" + stackTrace.toString());
xml.endTag("pre");
xml.text("\n");
}
/**
* Initializes Hibernate by making it read the hibernate.cfg file and also
* setting the same with hibernate session factory.
*/
public static void initializeHibernate() throws AppNotConfiguredException {
try {
StaticHibernateUtil.initialize();
} catch (HibernateStartUpException e) {
throw new AppNotConfiguredException(e);
}
}
/**
* Initializes the logger using loggerconfiguration.xml
*
* @throws AppNotConfiguredException
* - IF there is any exception while configuring the logger
*/
private void initializeLogger() throws AppNotConfiguredException {
try {
MifosLogManager.configureLogging();
} catch (LoggerConfigurationException lce) {
throw new AppNotConfiguredException(lce);
}
}
/**
* This function initialize and bring up the authorization and
* authentication services
*
* @throws AppNotConfiguredException
* - IF there is any failures during init
*/
private void initializeSecurity() throws AppNotConfiguredException {
try {
ActivityMapper.getInstance().init();
AuthorizationManager.getInstance().init();
HierarchyManager.getInstance().init();
} catch (XMLReaderException e) {
throw new AppNotConfiguredException(e);
} catch (ApplicationException ae) {
throw new AppNotConfiguredException(ae);
} catch (SystemException se) {
throw new AppNotConfiguredException(se);
}
}
private void initializeEntityMaster() throws HibernateProcessException {
EntityMasterData.getInstance().init();
}
private void configureAuditLogValues(Locale locale) throws SystemException {
AuditConfigurtion.init(locale);
}
public void contextDestroyed(ServletContextEvent ctx) {
}
public void requestDestroyed(ServletRequestEvent event) {
StaticHibernateUtil.closeSession();
}
public void requestInitialized(ServletRequestEvent event) {
}
}
| application/src/main/java/org/mifos/framework/ApplicationInitializer.java | /*
* Copyright (c) 2005-2009 Grameen Foundation USA
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*
* See also http://www.apache.org/licenses/LICENSE-2.0.html for an
* explanation of the license and how it is applied.
*/
package org.mifos.framework;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.Properties;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import org.mifos.application.accounts.financial.util.helpers.FinancialInitializer;
import org.mifos.application.configuration.business.MifosConfiguration;
import org.mifos.config.AccountingRules;
import org.mifos.config.ClientRules;
import org.mifos.config.Localization;
import org.mifos.config.ProcessFlowRules;
import org.mifos.core.MifosRuntimeException;
import org.mifos.framework.components.audit.util.helpers.AuditConfigurtion;
import org.mifos.framework.components.batchjobs.MifosScheduler;
import org.mifos.framework.components.configuration.business.Configuration;
import org.mifos.framework.components.logger.LoggerConstants;
import org.mifos.framework.components.logger.MifosLogManager;
import org.mifos.framework.components.logger.MifosLogger;
import org.mifos.framework.exceptions.AppNotConfiguredException;
import org.mifos.framework.exceptions.ApplicationException;
import org.mifos.framework.exceptions.HibernateProcessException;
import org.mifos.framework.exceptions.HibernateStartUpException;
import org.mifos.framework.exceptions.LoggerConfigurationException;
import org.mifos.framework.exceptions.SystemException;
import org.mifos.framework.exceptions.XMLReaderException;
import org.mifos.framework.hibernate.helper.StaticHibernateUtil;
import org.mifos.framework.persistence.DatabaseVersionPersistence;
import org.mifos.framework.plugin.PluginManager;
import org.mifos.framework.security.authorization.AuthorizationManager;
import org.mifos.framework.security.authorization.HierarchyManager;
import org.mifos.framework.security.util.ActivityMapper;
import org.mifos.framework.spring.SpringUtil;
import org.mifos.framework.struts.plugin.helper.EntityMasterData;
import org.mifos.framework.struts.tags.XmlBuilder;
import org.mifos.framework.util.StandardTestingService;
import org.mifos.framework.util.helpers.Money;
import org.mifos.spi.TransactionImport;
/**
* This class should prepare all the sub-systems that are required by the app.
* Cleanup should also happen here when the application is shutdown.
*/
public class ApplicationInitializer implements ServletContextListener, ServletRequestListener {
private static MifosLogger LOG = null;
private static class DatabaseError {
boolean isError = false;
DatabaseErrorCode errorCode = DatabaseErrorCode.NO_DATABASE_ERROR;
String errmsg = "";
Throwable error = null;
void logError() {
LOG.fatal(errmsg, false, null, error);
}
}
public static void setDatabaseError(DatabaseErrorCode errcode, String errmsg, Throwable error) {
databaseError.isError = true;
databaseError.errorCode = errcode;
databaseError.error = error;
databaseError.errmsg = errmsg;
}
public static void clearDatabaseError() {
databaseError.isError = false;
databaseError.errorCode = DatabaseErrorCode.NO_DATABASE_ERROR;
databaseError.error = null;
databaseError.errmsg = null;
}
private static String getDatabaseConnectionInfo() {
StandardTestingService standardTestingService = new StandardTestingService();
Properties hibernateCfg = new Properties();
String info = "Using Mifos database connection settings";
try {
hibernateCfg = standardTestingService.getDatabaseConnectionSettings();
info += " from file(s): " + Arrays.toString(standardTestingService.getAllSettingsFilenames());
} catch (IOException e) {
/*
* not sure if we can actually do anything useful with this
* exception since we're likely running during container
* initialization
*/
e.printStackTrace();
}
info += " Connection URL=" + hibernateCfg.getProperty("hibernate.connection.url");
info += ". Username=" + hibernateCfg.getProperty("hibernate.connection.username");
info += ". Password=********";
return info;
}
private static DatabaseError databaseError = new DatabaseError();
public void contextInitialized(ServletContextEvent ctx) {
init();
}
public void init() {
try {
synchronized (ApplicationInitializer.class) {
initializeLogger();
initializeHibernate();
/*
* getLogger() cannot be called statically (ie: when
* initializing LOG) because MifosLogManager.initializeLogger()
* hasn't been called yet, so MifosLogManager.loggerRepository
* will be null.
*/
LOG = MifosLogManager.getLogger(LoggerConstants.FRAMEWORKLOGGER);
LOG.info("Logger has been initialised", false, null);
LOG.info(getDatabaseConnectionInfo(), false, null);
DatabaseVersionPersistence persistence = new DatabaseVersionPersistence();
try {
/*
* This is an easy way to force an actual database query to
* happen via Hibernate. Simply opening a Hibernate session
* may not actually connect to the database.
*/
persistence.isVersioned();
} catch (Throwable t) {
setDatabaseError(DatabaseErrorCode.CONNECTION_FAILURE, "Unable to connect to database.", t);
}
if (!databaseError.isError) {
try {
persistence.upgradeDatabase();
} catch (Throwable t) {
setDatabaseError(DatabaseErrorCode.UPGRADE_FAILURE, "Failed to upgrade database.", t);
}
}
if (databaseError.isError) {
databaseError.logError();
} else {
// this method is called so that supported locales will be
// loaded
// from db and stored in cache for later use
Localization.getInstance().init();
// Check ClientRules configuration in db and config file(s)
// for errors. Also caches ClientRules values.
ClientRules.init();
// Check ProcessFlowRules configuration in db and config
// file(s) for errors.
ProcessFlowRules.init();
initializeSecurity();
Money.setDefaultCurrency(AccountingRules.getMifosCurrency());
// 1/4/08 Hopefully a temporary change to force Spring
// to initialize here (rather than in struts-config.xml
// prior to loading label values into a
// cache in MifosConfiguration. When the use of the
// cache is refactored away, we should be able to move
// back to the struts based Spring initialization
SpringUtil.initializeSpring();
// Spring must be initialized before FinancialInitializer
FinancialInitializer.initialize();
EntityMasterData.getInstance().init();
initializeEntityMaster();
(new MifosScheduler()).registerTasks();
Configuration.getInstance();
MifosConfiguration.getInstance().init();
configureAuditLogValues(Localization.getInstance().getMainLocale());
List<String> pluginsLoaded = new PluginManager().getImportPluginNames();
if (!pluginsLoaded.isEmpty()) {
LOG.info("loaded plugins: " + pluginsLoaded);
}
}
}
} catch (Exception e) {
String errMsgStart = "unable to start Mifos web application";
if (null == LOG) {
System.err.println(errMsgStart + " and logger is not available!");
e.printStackTrace();
} else {
LOG.error(errMsgStart, e);
}
throw new Error(e);
}
}
public static void printDatabaseError(XmlBuilder xml, int dbVersion) {
synchronized (ApplicationInitializer.class) {
if (databaseError.isError) {
addDatabaseErrorMessage(xml, dbVersion);
} else {
addNoFurtherDetailsMessage(xml);
}
}
}
private static void addNoFurtherDetailsMessage(XmlBuilder xml) {
xml.startTag("p");
xml.text("I don't have any further details, unfortunately.");
xml.endTag("p");
xml.text("\n");
}
private static void addDatabaseErrorMessage(XmlBuilder xml, int dbVersion) {
xml.startTag("p", "style", "font-weight: bolder; color: red; font-size: x-large;");
xml.text(databaseError.errmsg);
xml.text("\n");
if (databaseError.errorCode.equals(DatabaseErrorCode.UPGRADE_FAILURE)) {
addDatabaseVersionMessage(xml, dbVersion);
}
xml.endTag("p");
if (databaseError.errorCode.equals(DatabaseErrorCode.CONNECTION_FAILURE)) {
addConnectionFailureMessage(xml);
}
xml.text("\n");
xml.startTag("p");
xml.text("More details:");
xml.endTag("p");
xml.text("\n");
if (null != databaseError.error.getCause()) {
xml.startTag("p", "style", "font-weight: bolder; color: blue;");
xml.text(databaseError.error.getCause().toString());
xml.endTag("p");
xml.text("\n");
}
xml.startTag("p", "style", "font-weight: bolder; color: blue;");
xml.text(getDatabaseConnectionInfo());
xml.endTag("p");
xml.text("\n");
addStackTraceHtml(xml);
}
private static void addConnectionFailureMessage(XmlBuilder xml) {
xml.startTag("p");
xml.text("Possible causes:");
xml.startTag("ul");
xml.startTag("li");
xml.text("MySQL is not running");
xml.endTag("li");
xml.startTag("li");
xml.text("MySQL is listening on a different port than Mifos is expecting");
xml.endTag("li");
xml.startTag("li");
xml.text("incorrect username or password");
xml.endTag("li");
xml.endTag("ul");
xml.endTag("p");
xml.text("\n");
xml.startTag("p");
xml.startTag("a", "href",
"http://www.mifos.org/knowledge/support/deploying-mifos/configuration/guide");
xml.text("More about configuring your database connection.");
xml.endTag("a");
xml.endTag("p");
xml.text("\n");
}
private static void addDatabaseVersionMessage(XmlBuilder xml, int dbVersion) {
if (dbVersion == -1) {
xml.text("Database is too old to have a version.\n");
} else {
xml.text("Database Version = " + dbVersion + "\n");
}
xml.text("Application Version = " + DatabaseVersionPersistence.APPLICATION_VERSION + ".\n");
}
private static void addStackTraceHtml(XmlBuilder xml) {
xml.startTag("p");
xml.text("Stack trace:");
xml.endTag("p");
xml.text("\n");
xml.startTag("pre");
StringWriter stackTrace = new StringWriter();
databaseError.error.printStackTrace(new PrintWriter(stackTrace));
xml.text("\n" + stackTrace.toString());
xml.endTag("pre");
xml.text("\n");
}
/**
* Initializes Hibernate by making it read the hibernate.cfg file and also
* setting the same with hibernate session factory.
*/
public static void initializeHibernate() throws AppNotConfiguredException {
try {
StaticHibernateUtil.initialize();
} catch (HibernateStartUpException e) {
throw new AppNotConfiguredException(e);
}
}
/**
* Initializes the logger using loggerconfiguration.xml
*
* @throws AppNotConfiguredException
* - IF there is any exception while configuring the logger
*/
private void initializeLogger() throws AppNotConfiguredException {
try {
MifosLogManager.configureLogging();
} catch (LoggerConfigurationException lce) {
throw new AppNotConfiguredException(lce);
}
}
/**
* This function initialize and bring up the authorization and
* authentication services
*
* @throws AppNotConfiguredException
* - IF there is any failures during init
*/
private void initializeSecurity() throws AppNotConfiguredException {
try {
ActivityMapper.getInstance().init();
AuthorizationManager.getInstance().init();
HierarchyManager.getInstance().init();
} catch (XMLReaderException e) {
throw new AppNotConfiguredException(e);
} catch (ApplicationException ae) {
throw new AppNotConfiguredException(ae);
} catch (SystemException se) {
throw new AppNotConfiguredException(se);
}
}
private void initializeEntityMaster() throws HibernateProcessException {
EntityMasterData.getInstance().init();
}
private void configureAuditLogValues(Locale locale) throws SystemException {
AuditConfigurtion.init(locale);
}
public void contextDestroyed(ServletContextEvent ctx) {
}
public void requestDestroyed(ServletRequestEvent event) {
StaticHibernateUtil.closeSession();
}
public void requestInitialized(ServletRequestEvent event) {
}
}
| If an incorrectly implemented transaction import plugin is installed,
trying to load it during application initialization will crash Mifos.
This was the original intent of the code calling PluginManager at the
end of init(). When the fault is deferred to clicking on the "Import
transactions" page:
* except for imports, Mifos can still be used
* the error appears in the browser
* the error is more informative
Instead of beefing up the code during application initialization, it
seems like a better choice to allow plugin failure upon hitting the
"Import transactions" page.
git-svn-id: 6bd94cac40bd5c1df74b384d972046d926de6ffa@16097 a8845c50-7012-0410-95d3-8e1449b9b1e4
| application/src/main/java/org/mifos/framework/ApplicationInitializer.java | If an incorrectly implemented transaction import plugin is installed, trying to load it during application initialization will crash Mifos. This was the original intent of the code calling PluginManager at the end of init(). When the fault is deferred to clicking on the "Import transactions" page: * except for imports, Mifos can still be used * the error appears in the browser * the error is more informative | <ide><path>pplication/src/main/java/org/mifos/framework/ApplicationInitializer.java
<ide> import java.io.PrintWriter;
<ide> import java.io.StringWriter;
<ide> import java.util.Arrays;
<del>import java.util.List;
<ide> import java.util.Locale;
<ide> import java.util.Properties;
<ide>
<ide> import org.mifos.config.ClientRules;
<ide> import org.mifos.config.Localization;
<ide> import org.mifos.config.ProcessFlowRules;
<del>import org.mifos.core.MifosRuntimeException;
<ide> import org.mifos.framework.components.audit.util.helpers.AuditConfigurtion;
<ide> import org.mifos.framework.components.batchjobs.MifosScheduler;
<ide> import org.mifos.framework.components.configuration.business.Configuration;
<ide> import org.mifos.framework.exceptions.XMLReaderException;
<ide> import org.mifos.framework.hibernate.helper.StaticHibernateUtil;
<ide> import org.mifos.framework.persistence.DatabaseVersionPersistence;
<del>import org.mifos.framework.plugin.PluginManager;
<ide> import org.mifos.framework.security.authorization.AuthorizationManager;
<ide> import org.mifos.framework.security.authorization.HierarchyManager;
<ide> import org.mifos.framework.security.util.ActivityMapper;
<ide> import org.mifos.framework.struts.tags.XmlBuilder;
<ide> import org.mifos.framework.util.StandardTestingService;
<ide> import org.mifos.framework.util.helpers.Money;
<del>import org.mifos.spi.TransactionImport;
<ide>
<ide> /**
<ide> * This class should prepare all the sub-systems that are required by the app.
<ide> Configuration.getInstance();
<ide> MifosConfiguration.getInstance().init();
<ide> configureAuditLogValues(Localization.getInstance().getMainLocale());
<del>
<del> List<String> pluginsLoaded = new PluginManager().getImportPluginNames();
<del> if (!pluginsLoaded.isEmpty()) {
<del> LOG.info("loaded plugins: " + pluginsLoaded);
<del> }
<ide> }
<ide> }
<ide> } catch (Exception e) { |
|
Java | agpl-3.0 | ac0879034b811381e40c700e353e0a19fac124e4 | 0 | rroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstat,rroart/stockstat | package roart.ml;
import java.text.DecimalFormat;
import java.util.List;
import java.util.Map;
import org.jfree.util.Log;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import roart.aggregate.Aggregator;
import roart.indicator.Indicator;
import roart.indicator.IndicatorMACD;
import roart.util.Constants;
public abstract class MLClassifyModel {
private Logger log = LoggerFactory.getLogger(this.getClass());
public abstract int getId();
public abstract String getName();
//public abstract int addTitles(Object[] objs, int retindex, String title, String key, String subType, List<Integer> typeList, Map<Integer, String> mapTypes, MLDao dao);
//@Override
public int addTitles(Object[] objs, int retindex, Aggregator indicator, String title, String key, String subType, List<Integer> typeList0, Map<Integer, String> mapTypes0, MLClassifyDao dao) {
List<Integer> typeList = indicator.getTypeList();
Map<Integer, String> mapTypes = indicator.getMapTypes();
for (int mapTypeInt : typeList) {
String mapType = mapTypes.get(mapTypeInt);
String val = "";
//String lr = "" + DbSpark.eval("LogisticRegression ", title, "common");
String lr = "";
// TODO workaround
try {
val = "" + roundme(dao.eval(getId(), key, subType + mapType));
} catch (Exception e) {
log.error("Exception fix later, refactor", e);
}
objs[retindex++] = title + Constants.WEBBR + subType + getName() + mapType +val;
}
return retindex;
}
//public int addResults(Object[] fields, int retindex, String id, Aggregator indicator, Map<Integer, Map<String, Double[]>> commonIdTypeModelHistMap,String subType, List<Integer> typeList0, Map<Integer, String> mapTypes0 ) {
public int addResults(Object[] fields, int retindex, String id, MLClassifyModel model, Aggregator indicator, Map<String, Map<String, Double[]>> mapResult, Map<Double, String> labelMapShort) {
List<Integer> typeList = indicator.getTypeList();
Map<Integer, String> mapTypes = indicator.getMapTypes();
for (int mapTypeInt : typeList) {
String mapType = mapTypes.get(mapTypeInt);
Map<String, Double[]> resultMap1 = mapResult.get(mapType);
Double[] type = null;
if (resultMap1 != null) {
type = resultMap1.get(id);
} else {
System.out.println("map null " + mapType);
}
fields[retindex++] = type != null ? labelMapShort.get(type[0]) : null;
}
return retindex;
}
public static String roundme(Double eval) {
if (eval == null) {
return null;
}
DecimalFormat df = new DecimalFormat("#.00");
return df.format(eval);
}
public int getSizes(Aggregator indicator) {
List<Integer> typeList = indicator.getTypeList();
if (typeList == null) {
return 0;
}
return typeList.size();
}
public abstract String getEngineName();
}
| core/src/main/java/roart/ml/MLClassifyModel.java | package roart.ml;
import java.text.DecimalFormat;
import java.util.List;
import java.util.Map;
import org.jfree.util.Log;
import roart.aggregate.Aggregator;
import roart.indicator.Indicator;
import roart.indicator.IndicatorMACD;
import roart.util.Constants;
public abstract class MLClassifyModel {
public abstract int getId();
public abstract String getName();
//public abstract int addTitles(Object[] objs, int retindex, String title, String key, String subType, List<Integer> typeList, Map<Integer, String> mapTypes, MLDao dao);
//@Override
public int addTitles(Object[] objs, int retindex, Aggregator indicator, String title, String key, String subType, List<Integer> typeList0, Map<Integer, String> mapTypes0, MLClassifyDao dao) {
List<Integer> typeList = indicator.getTypeList();
Map<Integer, String> mapTypes = indicator.getMapTypes();
for (int mapTypeInt : typeList) {
String mapType = mapTypes.get(mapTypeInt);
String val = "";
//String lr = "" + DbSpark.eval("LogisticRegression ", title, "common");
String lr = "";
// TODO workaround
try {
val = "" + roundme(dao.eval(getId(), key, subType + mapType));
} catch (Exception e) {
Log.error("Exception fix later, refactor", e);
}
objs[retindex++] = title + Constants.WEBBR + subType + getName() + mapType +val;
}
return retindex;
}
//public int addResults(Object[] fields, int retindex, String id, Aggregator indicator, Map<Integer, Map<String, Double[]>> commonIdTypeModelHistMap,String subType, List<Integer> typeList0, Map<Integer, String> mapTypes0 ) {
public int addResults(Object[] fields, int retindex, String id, MLClassifyModel model, Aggregator indicator, Map<String, Map<String, Double[]>> mapResult, Map<Double, String> labelMapShort) {
List<Integer> typeList = indicator.getTypeList();
Map<Integer, String> mapTypes = indicator.getMapTypes();
for (int mapTypeInt : typeList) {
String mapType = mapTypes.get(mapTypeInt);
Map<String, Double[]> resultMap1 = mapResult.get(mapType);
Double[] type = null;
if (resultMap1 != null) {
resultMap1.get(id);
} else {
System.out.println("map null " + mapType);
}
fields[retindex++] = type != null ? labelMapShort.get(type[0]) : null;
}
return retindex;
}
public static String roundme(Double eval) {
if (eval == null) {
return null;
}
DecimalFormat df = new DecimalFormat("#.00");
return df.format(eval);
}
public int getSizes(Aggregator indicator) {
List<Integer> typeList = indicator.getTypeList();
if (typeList == null) {
return 0;
}
return typeList.size();
}
public abstract String getEngineName();
}
| Use proper log. It is good to actually set the var.
| core/src/main/java/roart/ml/MLClassifyModel.java | Use proper log. It is good to actually set the var. | <ide><path>ore/src/main/java/roart/ml/MLClassifyModel.java
<ide> import java.util.Map;
<ide>
<ide> import org.jfree.util.Log;
<add>import org.slf4j.Logger;
<add>import org.slf4j.LoggerFactory;
<ide>
<ide> import roart.aggregate.Aggregator;
<ide> import roart.indicator.Indicator;
<ide> import roart.util.Constants;
<ide>
<ide> public abstract class MLClassifyModel {
<add> private Logger log = LoggerFactory.getLogger(this.getClass());
<ide> public abstract int getId();
<ide>
<ide> public abstract String getName();
<ide> try {
<ide> val = "" + roundme(dao.eval(getId(), key, subType + mapType));
<ide> } catch (Exception e) {
<del> Log.error("Exception fix later, refactor", e);
<add> log.error("Exception fix later, refactor", e);
<ide> }
<ide> objs[retindex++] = title + Constants.WEBBR + subType + getName() + mapType +val;
<ide> }
<ide> Map<String, Double[]> resultMap1 = mapResult.get(mapType);
<ide> Double[] type = null;
<ide> if (resultMap1 != null) {
<del> resultMap1.get(id);
<add> type = resultMap1.get(id);
<ide> } else {
<ide> System.out.println("map null " + mapType);
<ide> } |
|
Java | mit | 31aa20657d84f39b806c65ccc128439b3afaa202 | 0 | conveyal/r5,conveyal/r5,conveyal/r5,conveyal/r5,conveyal/r5 | package com.conveyal.analysis.datasource;
import com.conveyal.file.FileStorageFormat;
import com.google.common.collect.Sets;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.io.FilenameUtils;
import java.io.File;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import static com.conveyal.r5.common.Util.isNullOrEmpty;
import static com.google.common.base.Preconditions.checkState;
/**
* Utility class with common static methods for validating and processing uploaded spatial data files.
*/
public abstract class DataSourceUtil {
/**
* Detect the format of a batch of user-uploaded files. Once the intended file type has been established, we
* validate the list of uploaded files, making sure certain preconditions are met. Some kinds of uploads must
* contain multiple files (.shp) while most others must contain only a single file (.csv, .gpkg etc.).
* Note that this does not perform structural or semantic validation of file contents, just the high-level
* characteristics of the set of file names.
* @throws DataSourceException if the type of the upload can't be detected or preconditions are violated.
* @return the expected type of the uploaded file or files, never null.
*/
public static FileStorageFormat detectUploadFormatAndValidate (List<FileItem> fileItems) {
if (isNullOrEmpty(fileItems)) {
throw new DataSourceException("You must select some files to upload.");
}
Set<String> fileExtensions = extractFileExtensions(fileItems);
if (fileExtensions.isEmpty()) {
throw new DataSourceException("No file extensions seen, cannot detect upload type.");
}
checkFileCharacteristics(fileItems);
if (fileExtensions.contains("zip")) {
throw new DataSourceException("Upload of spatial .zip files not yet supported");
// TODO unzip and process unzipped files - will need to peek inside to detect GTFS uploads first.
// detectUploadFormatAndValidate(unzipped)
}
// Check that if upload contains any of the Shapefile sidecar files, it contains all of the required ones.
final Set<String> shapefileExtensions = Sets.newHashSet("shp", "dbf", "prj");
if ( ! Sets.intersection(fileExtensions, shapefileExtensions).isEmpty()) {
if (fileExtensions.containsAll(shapefileExtensions)) {
verifyBaseNamesSame(fileItems);
// TODO check that any additional file is .shx, and that there are no more than 4 files.
} else {
throw new DataSourceException("You must multi-select at least SHP, DBF, and PRJ files for shapefile upload.");
}
return FileStorageFormat.SHP;
}
// The upload was not a Shapefile. All other formats should contain one single file.
if (fileExtensions.size() != 1) {
throw new DataSourceException("For any format but Shapefile, upload only one file at a time.");
}
final String extension = fileExtensions.stream().findFirst().get();
// TODO replace with iteration over FileStorageFormat.values() and their lists of extensions
if (extension.equals("grid")) {
return FileStorageFormat.GRID;
} else if (extension.equals("csv")) {
return FileStorageFormat.CSV;
} else if (extension.equals("geojson") || extension.equals("json")) {
return FileStorageFormat.GEOJSON;
} else if (extension.equals("gpkg")) {
return FileStorageFormat.GEOPACKAGE;
} else if (extension.equals("tif") || extension.equals("tiff") || extension.equals("geotiff")) {
return FileStorageFormat.GEOTIFF;
}
throw new DataSourceException("Could not detect format of uploaded spatial data.");
}
/**
* Check that all FileItems supplied are stored in disk files (not memory), that they are all readable and all
* have nonzero size.
*/
private static void checkFileCharacteristics (List<FileItem> fileItems) {
for (FileItem fileItem : fileItems) {
checkState(fileItem instanceof DiskFileItem, "Uploaded file was not stored to disk.");
File diskFile = ((DiskFileItem)fileItem).getStoreLocation();
checkState(diskFile.exists(), "Uploaded file does not exist on filesystem as expected.");
checkState(diskFile.canRead(), "Read permissions were not granted on uploaded file.");
checkState(diskFile.length() > 0, "Uploaded file was empty (contained no data).");
}
}
/**
* Given a list of FileItems, return a set of all unique file extensions present, normalized to lower case.
* Always returns a set instance which may be empty, but never null.
*/
private static Set<String> extractFileExtensions (List<FileItem> fileItems) {
Set<String> fileExtensions = new HashSet<>();
for (FileItem fileItem : fileItems) {
String fileName = fileItem.getName();
String extension = FilenameUtils.getExtension(fileName);
if (extension.isEmpty()) {
throw new DataSourceException("Filename has no extension: " + fileName);
}
fileExtensions.add(extension.toLowerCase(Locale.ROOT));
}
return fileExtensions;
}
/** In uploads containing more than one file, all files are expected to have the same name before the extension. */
private static void verifyBaseNamesSame (List<FileItem> fileItems) {
String firstBaseName = null;
for (FileItem fileItem : fileItems) {
String baseName = FilenameUtils.getBaseName(fileItem.getName());
if (firstBaseName == null) {
firstBaseName = baseName;
} else if (!firstBaseName.equals(baseName)) {
throw new DataSourceException("In a shapefile upload, all files must have the same base name.");
}
}
}
}
| src/main/java/com/conveyal/analysis/datasource/DataSourceUtil.java | package com.conveyal.analysis.datasource;
import com.conveyal.analysis.AnalysisServerException;
import com.conveyal.file.FileStorageFormat;
import com.google.common.collect.Sets;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.io.FilenameUtils;
import java.io.File;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import static com.conveyal.r5.common.Util.isNullOrEmpty;
import static com.google.common.base.Preconditions.checkState;
/**
* Utility class with common static methods for validating and processing uploaded spatial data files.
*/
public abstract class DataSourceUtil {
/**
* Detect the format of a batch of user-uploaded files. Once the intended file type has been established, we
* validate the list of uploaded files, making sure certain preconditions are met. Some kinds of uploads must
* contain multiple files (.shp) while most others must contain only a single file (.csv, .gpkg etc.).
* Note that this does not perform structural or semantic validation of file contents, just the high-level
* characteristics of the set of file names.
* @throws DataSourceException if the type of the upload can't be detected or preconditions are violated.
* @return the expected type of the uploaded file or files, never null.
*/
public static FileStorageFormat detectUploadFormatAndValidate (List<FileItem> fileItems) {
if (isNullOrEmpty(fileItems)) {
throw new DataSourceException("You must select some files to upload.");
}
Set<String> fileExtensions = extractFileExtensions(fileItems);
if (fileExtensions.isEmpty()) {
throw new DataSourceException("No file extensions seen, cannot detect upload type.");
}
checkFileCharacteristics(fileItems);
if (fileExtensions.contains("zip")) {
throw new DataSourceException("Upload of spatial .zip files not yet supported");
// TODO unzip and process unzipped files - will need to peek inside to detect GTFS uploads first.
// detectUploadFormatAndValidate(unzipped)
}
// Check that if upload contains any of the Shapefile sidecar files, it contains all of the required ones.
final Set<String> shapefileExtensions = Sets.newHashSet("shp", "dbf", "prj");
if ( ! Sets.intersection(fileExtensions, shapefileExtensions).isEmpty()) {
if (fileExtensions.containsAll(shapefileExtensions)) {
verifyBaseNamesSame(fileItems);
// TODO check that any additional file is .shx, and that there are no more than 4 files.
} else {
throw new DataSourceException("You must multi-select at least SHP, DBF, and PRJ files for shapefile upload.");
}
return FileStorageFormat.SHP;
}
// The upload was not a Shapefile. All other formats should contain one single file.
if (fileExtensions.size() != 1) {
throw new DataSourceException("For any format but Shapefile, upload only one file at a time.");
}
final String extension = fileExtensions.stream().findFirst().get();
// TODO replace with iteration over FileStorageFormat.values() and their lists of extensions
if (extension.equals("grid")) {
return FileStorageFormat.GRID;
} else if (extension.equals("csv")) {
return FileStorageFormat.CSV;
} else if (extension.equals("geojson") || extension.equals("json")) {
return FileStorageFormat.GEOJSON;
} else if (extension.equals("gpkg")) {
return FileStorageFormat.GEOPACKAGE;
} else if (extension.equals("tif") || extension.equals("tiff") || extension.equals("geotiff")) {
return FileStorageFormat.GEOTIFF;
}
throw new DataSourceException("Could not detect format of uploaded spatial data.");
}
/**
* Check that all FileItems supplied are stored in disk files (not memory), that they are all readable and all
* have nonzero size.
*/
private static void checkFileCharacteristics (List<FileItem> fileItems) {
for (FileItem fileItem : fileItems) {
checkState(fileItem instanceof DiskFileItem, "Uploaded file was not stored to disk.");
File diskFile = ((DiskFileItem)fileItem).getStoreLocation();
checkState(diskFile.exists(), "Uploaded file does not exist on filesystem as expected.");
checkState(diskFile.canRead(), "Read permissions were not granted on uploaded file.");
checkState(diskFile.length() > 0, "Uploaded file was empty (contained no data).");
}
}
/**
* Given a list of FileItems, return a set of all unique file extensions present, normalized to lower case.
* Always returns a set instance which may be empty, but never null.
*/
private static Set<String> extractFileExtensions (List<FileItem> fileItems) {
Set<String> fileExtensions = new HashSet<>();
for (FileItem fileItem : fileItems) {
String fileName = fileItem.getName();
String extension = FilenameUtils.getExtension(fileName);
if (extension.isEmpty()) {
new DataSourceException("Filename has no extension: " + fileName);
}
fileExtensions.add(extension.toLowerCase(Locale.ROOT));
}
return fileExtensions;
}
/** In uploads containing more than one file, all files are expected to have the same name before the extension. */
private static void verifyBaseNamesSame (List<FileItem> fileItems) {
String firstBaseName = null;
for (FileItem fileItem : fileItems) {
String baseName = FilenameUtils.getBaseName(fileItem.getName());
if (firstBaseName == null) {
firstBaseName = baseName;
} else if (!firstBaseName.equals(baseName)) {
throw new DataSourceException("In a shapefile upload, all files must have the same base name.");
}
}
}
}
| fix: actually throw exception
| src/main/java/com/conveyal/analysis/datasource/DataSourceUtil.java | fix: actually throw exception | <ide><path>rc/main/java/com/conveyal/analysis/datasource/DataSourceUtil.java
<ide> package com.conveyal.analysis.datasource;
<del>
<del>import com.conveyal.analysis.AnalysisServerException;
<ide>
<ide> import com.conveyal.file.FileStorageFormat;
<ide> import com.google.common.collect.Sets;
<ide> String fileName = fileItem.getName();
<ide> String extension = FilenameUtils.getExtension(fileName);
<ide> if (extension.isEmpty()) {
<del> new DataSourceException("Filename has no extension: " + fileName);
<add> throw new DataSourceException("Filename has no extension: " + fileName);
<ide> }
<ide> fileExtensions.add(extension.toLowerCase(Locale.ROOT));
<ide> } |
|
Java | apache-2.0 | 7c6ca2fba394e58cc74cfde2e42cf667c06e1376 | 0 | nmsasaki/SilentPhoneTimer | package ca.nmsasaki.silenttouch;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;
import java.util.Calendar;
import java.text.DateFormat;
public class MyWidgetProvider extends AppWidgetProvider {
// when testing minimum is 2 minutes because I round seconds down to 00 to timer expires on minute change
//private static final long SILENT_DURATION_MILLISECONDS = 30 * 60 * 1000;
private static final long SILENT_DURATION_MILLISECONDS = 2 * 60 * 1000;
private static final String TAG = "SilentTouch";
private static final int MY_NOTIFICATION_ID = 1;
private static final String INTENT_ACTION_WIDGET_CLICK = "ca.nmsasaki.silenttouch.INTENT_ACTION_WIDGET_CLICK";
private static final String INTENT_ACTION_NOTIFICATION_CANCEL_CLICK = "ca.nmsasaki.silenttouch.INTENT_ACTION_NOTIFICATION_CANCEL_CLICK";
private static final String INTENT_ACTION_TIMER_EXPIRED = "ca.nmsasaki.silenttouch.INTENT_ACTION_TIMER_EXPIRED";
// mToast is used to cancel an existing toast if user clicks on widget in succession
// should be ok if this state gets cleaned up by android
private static Toast mToast = null;
// TODO: remove dependence on this variable used for updating an existing alarm
private static long mAlarmExpire = 0;
// TODO: remove dependence on this variable used for updating exiting timer
private static PendingIntent mAlarmIntent = null;
@Override
public void onEnabled(Context context) {
super.onEnabled(context);
Log.d(TAG, "MyWidgetProvider::onEnabled");
}
@Override
public void onReceive(Context context, Intent intent) {
// super.onReceive(context, intent);
Log.i(TAG, "MyWidgetProvider::onReceive - enter");
final String curIntentAction = intent.getAction();
Log.i(TAG, "onReceive Intent=" + curIntentAction);
if (curIntentAction == INTENT_ACTION_WIDGET_CLICK) {
// User clicked on widget
// Perform actions before notifying user
// this will expose performance delays and show bugs
Log.i(TAG, "INTENT_ACTION_WIDGET_CLICK - enter");
// ----------------------------------------------------
// check current ringermode
AudioManager audioManager = (AudioManager) context
.getSystemService(Context.AUDIO_SERVICE);
final int curAudioMode = audioManager.getRingerMode();
// TODO: Extract RINGERMODE string to function
String curModeString = "UNKNOWN";
switch (curAudioMode) {
case AudioManager.RINGER_MODE_NORMAL:
curModeString = "NORMAL";
break;
case AudioManager.RINGER_MODE_SILENT:
curModeString = "SILENT";
break;
case AudioManager.RINGER_MODE_VIBRATE:
curModeString = "VIBRATE";
break;
default:
break;
}
Log.i(TAG, "AudioMode=" + curModeString);
// --------------------------------------------------
// set timer to re-enable original ringer mode
AlarmManager alarmMgr = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
// TODO: move calendar getInstance and refactor code to extract truncate seconds
// into separate function that takes start time as a function
Calendar calendar = Calendar.getInstance();
if (mAlarmIntent == null) {
// Create a NEW timer for Canceling Silent Mode
// -----------------------------------------
Intent intentAlarmReceiver = new Intent(context,
MyWidgetProvider.class);
intentAlarmReceiver.setAction(INTENT_ACTION_TIMER_EXPIRED);
mAlarmIntent = PendingIntent.getBroadcast(context, 0,
intentAlarmReceiver, 0);
mAlarmExpire = System.currentTimeMillis()
+ SILENT_DURATION_MILLISECONDS;
// truncate seconds
calendar.setTimeInMillis(mAlarmExpire);
calendar.set(Calendar.SECOND,0);
mAlarmExpire = calendar.getTimeInMillis();
alarmMgr.set(AlarmManager.RTC_WAKEUP, mAlarmExpire,
mAlarmIntent);
Log.i(TAG, "AudioMode=" + curModeString);
} else {
// Update existing timer
// ------------------------------------------
mAlarmExpire = mAlarmExpire + SILENT_DURATION_MILLISECONDS;
// truncate seconds
calendar.setTimeInMillis(mAlarmExpire);
calendar.set(Calendar.SECOND,0);
mAlarmExpire = calendar.getTimeInMillis();
alarmMgr.set(AlarmManager.RTC_WAKEUP, mAlarmExpire,
mAlarmIntent);
}
// TODO: Extract Dateformatting to function
final DateFormat dateFormatterUser = DateFormat
.getTimeInstance(DateFormat.SHORT);
final DateFormat dateFormatterLog = DateFormat
.getTimeInstance(DateFormat.LONG);
final String dateStringUser = dateFormatterUser
.format(mAlarmExpire);
final String dateStringLog = dateFormatterLog.format(mAlarmExpire);
Log.i(TAG, "onReceive Set expireTime=" + dateStringLog);
// ----------------------------------------------------
// set ringer mode after alarm is set
// to ensure mode will become re-enabled
if (curAudioMode != AudioManager.RINGER_MODE_SILENT) {
audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
Log.i(TAG, "AudioMode=RINGER_MODE_SILENT");
}
// ----------------------------------------------------
// Create toast to alert user
String toastText = context.getString(R.string.toast_ON);
toastText = String.format(toastText, dateStringUser);
if (mToast != null) {
mToast.cancel();
}
mToast = Toast.makeText(context, toastText, Toast.LENGTH_LONG);
mToast.show();
// ------------------------------------------------
// Build notification
// notification strings
final String notiTitle = context
.getString(R.string.notification_title);
final String notiCancel = context
.getString(R.string.notification_ON_cancel);
String notiContentText = context
.getString(R.string.notification_ON_content);
notiContentText = String.format(notiContentText, dateStringUser);
// Pending intent to be fired when notification is clicked
Intent notiIntent = new Intent(context, MyWidgetProvider.class);
notiIntent.setAction(INTENT_ACTION_NOTIFICATION_CANCEL_CLICK);
PendingIntent cancelPendingIntent = PendingIntent.getBroadcast(
context, 0, notiIntent, 0);
// Define the Notification's expanded message and Intent:
Notification.Builder notificationBuilder = new Notification.Builder(
context)
.setSmallIcon(R.drawable.ic_notify)
.setContentTitle(notiTitle)
.setContentText(notiContentText)
.addAction(android.R.drawable.ic_lock_silent_mode_off,
notiCancel, cancelPendingIntent);
// Pass the Notification to the NotificationManager:
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(MY_NOTIFICATION_ID,
notificationBuilder.build());
Log.i(TAG, "INTENT_ACTION_WIDGET_CLICK - exit");
} else if (curIntentAction == INTENT_ACTION_TIMER_EXPIRED) {
Log.i(TAG, "INTENT_ACTION_TIMER_EXPIRED - enter");
// Timer expired - restore previous notification type
// --------------------------------------------------
// enable previous ringerMode
AudioManager audioManager = (AudioManager) context
.getSystemService(Context.AUDIO_SERVICE);
final int curAudioMode = audioManager.getRingerMode();
// TODO: Extract RINGERMODE string to function
String curModeString = "UNKNOWN";
switch (curAudioMode) {
case AudioManager.RINGER_MODE_NORMAL:
curModeString = "NORMAL";
break;
case AudioManager.RINGER_MODE_SILENT:
curModeString = "SILENT";
break;
case AudioManager.RINGER_MODE_VIBRATE:
curModeString = "VIBRATE";
break;
default:
break;
}
Log.i(TAG, "AudioMode=" + curModeString);
if (curAudioMode == AudioManager.RINGER_MODE_SILENT) {
audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
Log.i(TAG, "AudioMode=RINGER_MODE_NORMAL");
}
// -------------------------------------------
// Build notification to say timer expired
final long alarmExpired = System.currentTimeMillis();
// TODO: Extract Dateformatting to function
final DateFormat dateFormatterUser = DateFormat
.getTimeInstance(DateFormat.SHORT);
final DateFormat dateFormatterLog = DateFormat
.getTimeInstance(DateFormat.LONG);
String dateStringUser = dateFormatterUser.format(alarmExpired);
String dateStringLog = dateFormatterLog.format(alarmExpired);
Log.i(TAG, "onReceive Actual expireTime:" + dateStringLog);
final String notiTitle = context
.getString(R.string.notification_title);
String notiContentText = context
.getString(R.string.notification_OFF_timer);
notiContentText = String.format(notiContentText, dateStringUser);
// Define the Notification's expanded message and Intent:
Notification.Builder notificationBuilder = new Notification.Builder(
context)
.setSmallIcon(R.drawable.ic_notify)
.setContentTitle(notiTitle).setContentText(notiContentText);
// Pass the Notification to the NotificationManager:
NotificationManager mNotificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(MY_NOTIFICATION_ID,
notificationBuilder.build());
mAlarmIntent = null;
Log.i(TAG, "INTENT_ACTION_TIMER_EXPIRED - exit");
} else if (intent.getAction() == INTENT_ACTION_NOTIFICATION_CANCEL_CLICK) {
Log.i(TAG, "INTENT_ACTION_NOTIFICATION_CANCEL_CLICK - enter");
// User canceled the mode manually from notifications
// -----------------------------------------------
// Restore previous RingerMode
AudioManager audioManager = (AudioManager) context
.getSystemService(Context.AUDIO_SERVICE);
final int curAudioMode = audioManager.getRingerMode();
String curModeString = "UNKNOWN";
switch (curAudioMode) {
case AudioManager.RINGER_MODE_NORMAL:
curModeString = "NORMAL";
break;
case AudioManager.RINGER_MODE_SILENT:
curModeString = "SILENT";
break;
case AudioManager.RINGER_MODE_VIBRATE:
curModeString = "VIBRATE";
break;
default:
break;
}
Log.i(TAG, "AudioMode=" + curModeString);
if (curAudioMode == AudioManager.RINGER_MODE_SILENT) {
audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
Log.i(TAG, "AudioMode=RINGER_MODE_NORMAL");
}
// -------------------------------------------
// cancel timer
AlarmManager alarmMgr = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
if (alarmMgr != null && mAlarmIntent != null) {
alarmMgr.cancel(mAlarmIntent);
}
// -------------------------------------------
// clear notification
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(MY_NOTIFICATION_ID);
mAlarmIntent = null;
Log.i(TAG, "INTENT_ACTION_NOTIFICATION_CANCEL_CLICK - exit");
}
super.onReceive(context, intent);
Log.i(TAG, "MyWidgetProvider::onReceive - exit");
}
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
Log.i(TAG, "MyWidgetProvider::onUpdate - enter");
ComponentName thisWidget = new ComponentName(context,
MyWidgetProvider.class);
RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
R.layout.widget_layout);
// Register an onClickListener for widget update
// ----------------------------------------------------
Intent updateIntent = new Intent(context, MyWidgetProvider.class);
updateIntent.setAction(INTENT_ACTION_WIDGET_CLICK);
// updateIntent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
// updateIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS,
// appWidgetIds);
PendingIntent updatePIntent = PendingIntent.getBroadcast(context, 0,
updateIntent, 0);
remoteViews.setOnClickPendingIntent(R.id.widget_image, updatePIntent);
appWidgetManager.updateAppWidget(thisWidget, remoteViews);
Log.i(TAG, "MyWidgetProvider::onUpdate - Register Widget Click Intent");
// ----------------------------------------------------
// // Update the widgets via the service
// ----------------------------------------------------
// context.startService(intent);
// ----------------------------------------------------
Log.i(TAG, "MyWidgetProvider::onUpdate - exit");
}
}
| src/ca/nmsasaki/silenttouch/MyWidgetProvider.java | package ca.nmsasaki.silenttouch;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.text.DateFormat;
public class MyWidgetProvider extends AppWidgetProvider {
// when testing minimum is 2 minutes because I round seconds down to 00 to timer expires on minute change
//private static final long SILENT_DURATION_MILLISECONDS = 30 * 60 * 1000;
private static final long SILENT_DURATION_MILLISECONDS = 2 * 60 * 1000;
private static final String TAG = "SilentTouch";
private static final int MY_NOTIFICATION_ID = 1;
private static final String INTENT_ACTION_WIDGET_CLICK = "ca.nmsasaki.silenttouch.INTENT_ACTION_WIDGET_CLICK";
private static final String INTENT_ACTION_NOTIFICATION_CANCEL_CLICK = "ca.nmsasaki.silenttouch.INTENT_ACTION_NOTIFICATION_CANCEL_CLICK";
private static final String INTENT_ACTION_TIMER_EXPIRED = "ca.nmsasaki.silenttouch.INTENT_ACTION_TIMER_EXPIRED";
// mToast is used to cancel an existing toast if user clicks on widget in succession
// should be ok if this state gets cleaned up by android
private static Toast mToast = null;
// TODO: remove dependence on this variable used for updating an existing alarm
private static long mAlarmExpire = 0;
// TODO: remove dependence on this variable used for updating exiting timer
private static PendingIntent mAlarmIntent = null;
@Override
public void onEnabled(Context context) {
super.onEnabled(context);
Log.d(TAG, "MyWidgetProvider::onEnabled");
}
@Override
public void onReceive(Context context, Intent intent) {
// super.onReceive(context, intent);
Log.i(TAG, "MyWidgetProvider::onReceive - enter");
final String curIntentAction = intent.getAction();
Log.i(TAG, "onReceive Intent=" + curIntentAction);
if (curIntentAction == INTENT_ACTION_WIDGET_CLICK) {
// User clicked on widget
// Perform actions before notifying user
// this will expose performance delays and show bugs
Log.i(TAG, "INTENT_ACTION_WIDGET_CLICK - enter");
// ----------------------------------------------------
// check current ringermode
AudioManager audioManager = (AudioManager) context
.getSystemService(Context.AUDIO_SERVICE);
final int curAudioMode = audioManager.getRingerMode();
// TODO: Extract RINGERMODE string to function
String curModeString = "UNKNOWN";
switch (curAudioMode) {
case AudioManager.RINGER_MODE_NORMAL:
curModeString = "NORMAL";
break;
case AudioManager.RINGER_MODE_SILENT:
curModeString = "SILENT";
break;
case AudioManager.RINGER_MODE_VIBRATE:
curModeString = "VIBRATE";
break;
default:
break;
}
Log.i(TAG, "AudioMode=" + curModeString);
// --------------------------------------------------
// set timer to re-enable original ringer mode
AlarmManager alarmMgr = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
// TODO: move calendar getInstance and refactor code to extract truncate seconds
// into separate function that takes start time as a function
Calendar calendar = Calendar.getInstance();
if (mAlarmIntent == null) {
// Create a NEW timer for Canceling Silent Mode
// -----------------------------------------
Intent intentAlarmReceiver = new Intent(context,
MyWidgetProvider.class);
intentAlarmReceiver.setAction(INTENT_ACTION_TIMER_EXPIRED);
mAlarmIntent = PendingIntent.getBroadcast(context, 0,
intentAlarmReceiver, 0);
mAlarmExpire = System.currentTimeMillis()
+ SILENT_DURATION_MILLISECONDS;
// truncate seconds
calendar.setTimeInMillis(mAlarmExpire);
calendar.set(Calendar.SECOND,0);
mAlarmExpire = calendar.getTimeInMillis();
alarmMgr.set(AlarmManager.RTC_WAKEUP, mAlarmExpire,
mAlarmIntent);
Log.i(TAG, "AudioMode=" + curModeString);
} else {
// Update existing timer
// ------------------------------------------
mAlarmExpire = mAlarmExpire + SILENT_DURATION_MILLISECONDS;
// truncate seconds
calendar.setTimeInMillis(mAlarmExpire);
calendar.set(Calendar.SECOND,0);
mAlarmExpire = calendar.getTimeInMillis();
alarmMgr.set(AlarmManager.RTC_WAKEUP, mAlarmExpire,
mAlarmIntent);
}
// TODO: Extract Dateformatting to function
final DateFormat dateFormatterUser = DateFormat
.getTimeInstance(DateFormat.SHORT);
final DateFormat dateFormatterLog = DateFormat
.getTimeInstance(DateFormat.LONG);
final String dateStringUser = dateFormatterUser
.format(mAlarmExpire);
final String dateStringLog = dateFormatterLog.format(mAlarmExpire);
Log.i(TAG, "onReceive Set expireTime=" + dateStringLog);
// ----------------------------------------------------
// set ringer mode after alarm is set
// to ensure mode will become re-enabled
if (curAudioMode != AudioManager.RINGER_MODE_SILENT) {
audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
Log.i(TAG, "AudioMode=RINGER_MODE_SILENT");
}
// ----------------------------------------------------
// Create toast to alert user
String toastText = context.getString(R.string.toast_ON);
toastText = String.format(toastText, dateStringUser);
if (mToast != null) {
mToast.cancel();
}
mToast = Toast.makeText(context, toastText, Toast.LENGTH_LONG);
mToast.show();
// ------------------------------------------------
// Build notification
// notification strings
final String notiTitle = context
.getString(R.string.notification_title);
final String notiCancel = context
.getString(R.string.notification_ON_cancel);
String notiContentText = context
.getString(R.string.notification_ON_content);
notiContentText = String.format(notiContentText, dateStringUser);
// Pending intent to be fired when notification is clicked
Intent notiIntent = new Intent(context, MyWidgetProvider.class);
notiIntent.setAction(INTENT_ACTION_NOTIFICATION_CANCEL_CLICK);
PendingIntent cancelPendingIntent = PendingIntent.getBroadcast(
context, 0, notiIntent, 0);
// Define the Notification's expanded message and Intent:
Notification.Builder notificationBuilder = new Notification.Builder(
context)
.setSmallIcon(R.drawable.ic_notify)
.setContentTitle(notiTitle)
.setContentText(notiContentText)
.addAction(android.R.drawable.ic_lock_silent_mode_off,
notiCancel, cancelPendingIntent);
// Pass the Notification to the NotificationManager:
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(MY_NOTIFICATION_ID,
notificationBuilder.build());
Log.i(TAG, "INTENT_ACTION_WIDGET_CLICK - exit");
} else if (curIntentAction == INTENT_ACTION_TIMER_EXPIRED) {
Log.i(TAG, "INTENT_ACTION_TIMER_EXPIRED - enter");
// Timer expired - restore previous notification type
// --------------------------------------------------
// enable previous ringerMode
AudioManager audioManager = (AudioManager) context
.getSystemService(Context.AUDIO_SERVICE);
final int curAudioMode = audioManager.getRingerMode();
// TODO: Extract RINGERMODE string to function
String curModeString = "UNKNOWN";
switch (curAudioMode) {
case AudioManager.RINGER_MODE_NORMAL:
curModeString = "NORMAL";
break;
case AudioManager.RINGER_MODE_SILENT:
curModeString = "SILENT";
break;
case AudioManager.RINGER_MODE_VIBRATE:
curModeString = "VIBRATE";
break;
default:
break;
}
Log.i(TAG, "AudioMode=" + curModeString);
if (curAudioMode == AudioManager.RINGER_MODE_SILENT) {
audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
Log.i(TAG, "AudioMode=RINGER_MODE_NORMAL");
}
// -------------------------------------------
// Build notification to say timer expired
final long alarmExpired = System.currentTimeMillis();
// TODO: Extract Dateformatting to function
final DateFormat dateFormatterUser = DateFormat
.getTimeInstance(DateFormat.SHORT);
final DateFormat dateFormatterLog = DateFormat
.getTimeInstance(DateFormat.LONG);
String dateStringUser = dateFormatterUser.format(alarmExpired);
String dateStringLog = dateFormatterLog.format(alarmExpired);
Log.i(TAG, "onReceive Actual expireTime:" + dateStringLog);
final String notiTitle = context
.getString(R.string.notification_title);
String notiContentText = context
.getString(R.string.notification_OFF_timer);
notiContentText = String.format(notiContentText, dateStringUser);
// Define the Notification's expanded message and Intent:
Notification.Builder notificationBuilder = new Notification.Builder(
context)
.setSmallIcon(R.drawable.ic_notify)
.setContentTitle(notiTitle).setContentText(notiContentText);
// Pass the Notification to the NotificationManager:
NotificationManager mNotificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(MY_NOTIFICATION_ID,
notificationBuilder.build());
mAlarmIntent = null;
Log.i(TAG, "INTENT_ACTION_TIMER_EXPIRED - exit");
} else if (intent.getAction() == INTENT_ACTION_NOTIFICATION_CANCEL_CLICK) {
Log.i(TAG, "INTENT_ACTION_NOTIFICATION_CANCEL_CLICK - enter");
// User canceled the mode manually from notifications
// -----------------------------------------------
// Restore previous RingerMode
AudioManager audioManager = (AudioManager) context
.getSystemService(Context.AUDIO_SERVICE);
final int curAudioMode = audioManager.getRingerMode();
String curModeString = "UNKNOWN";
switch (curAudioMode) {
case AudioManager.RINGER_MODE_NORMAL:
curModeString = "NORMAL";
break;
case AudioManager.RINGER_MODE_SILENT:
curModeString = "SILENT";
break;
case AudioManager.RINGER_MODE_VIBRATE:
curModeString = "VIBRATE";
break;
default:
break;
}
Log.i(TAG, "AudioMode=" + curModeString);
if (curAudioMode == AudioManager.RINGER_MODE_SILENT) {
audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
Log.i(TAG, "AudioMode=RINGER_MODE_NORMAL");
}
// -------------------------------------------
// cancel timer
AlarmManager alarmMgr = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
if (alarmMgr != null && mAlarmIntent != null) {
alarmMgr.cancel(mAlarmIntent);
}
// -------------------------------------------
// clear notification
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.cancel(MY_NOTIFICATION_ID);
mAlarmIntent = null;
Log.i(TAG, "INTENT_ACTION_NOTIFICATION_CANCEL_CLICK - exit");
}
super.onReceive(context, intent);
Log.i(TAG, "MyWidgetProvider::onReceive - exit");
}
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
Log.i(TAG, "MyWidgetProvider::onUpdate - enter");
ComponentName thisWidget = new ComponentName(context,
MyWidgetProvider.class);
RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
R.layout.widget_layout);
// Register an onClickListener for widget update
// ----------------------------------------------------
Intent updateIntent = new Intent(context, MyWidgetProvider.class);
updateIntent.setAction(INTENT_ACTION_WIDGET_CLICK);
// updateIntent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
// updateIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS,
// appWidgetIds);
PendingIntent updatePIntent = PendingIntent.getBroadcast(context, 0,
updateIntent, 0);
remoteViews.setOnClickPendingIntent(R.id.widget_image, updatePIntent);
appWidgetManager.updateAppWidget(thisWidget, remoteViews);
Log.i(TAG, "MyWidgetProvider::onUpdate - Register Widget Click Intent");
// ----------------------------------------------------
// // Update the widgets via the service
// ----------------------------------------------------
// context.startService(intent);
// ----------------------------------------------------
Log.i(TAG, "MyWidgetProvider::onUpdate - exit");
}
}
| removed warning | src/ca/nmsasaki/silenttouch/MyWidgetProvider.java | removed warning | <ide><path>rc/ca/nmsasaki/silenttouch/MyWidgetProvider.java
<ide> import android.widget.Toast;
<ide>
<ide> import java.util.Calendar;
<del>import java.util.GregorianCalendar;
<ide> import java.text.DateFormat;
<ide>
<ide> public class MyWidgetProvider extends AppWidgetProvider { |
|
JavaScript | mit | 0e9f7637d97e774604f2a318d6cb3ba544b59275 | 0 | LN-Zap/zap-desktop,LN-Zap/zap-desktop,LN-Zap/zap-desktop | import React, { useEffect } from 'react'
import createScheduler from '@zap/utils/scheduler'
import PropTypes from 'prop-types'
import Activity from 'containers/Activity'
import Wallet from 'containers/Wallet'
import { MainContent } from 'components/UI'
// Bitcoin blocks come on average every 10 mins
// but we poll a lot more frequently to make UI a little bit more responsive
const TX_REFETCH_INTERVAL = 1000 * 60 * 1
// Initial re-fetch after 2 seconds.
const INITIAL_REFETCH_INTERVAL = 2000
// Fetch node data no less than once every 10 minutes.
const MAX_REFETCH_INTERVAL = 1000 * 60 * 10
// Amount to increment re-fetch timer by after each fetch.
const BACKOFF_SCHEDULE = 1.5
// App scheduler / polling service
const appScheduler = createScheduler()
function App({
isAppReady,
modals,
payReq,
fetchActivityHistory,
setIsWalletOpen,
fetchPeers,
fetchTransactions,
setModals,
}) {
/**
* App scheduler / polling service setup. Add new app-wide polls here
*/
useEffect(() => {
/**
* Fetch node data on an exponentially incrementing backoff schedule so that when the app is first mounted, we fetch
* node data quite frequently but as time goes on the frequency is reduced down to a maximum of MAX_REFETCH_INTERVAL
*/
appScheduler.addTask({
task: fetchPeers,
taskId: 'fetchPeers',
baseDelay: INITIAL_REFETCH_INTERVAL,
maxDelay: MAX_REFETCH_INTERVAL,
backoff: BACKOFF_SCHEDULE,
})
appScheduler.addTask({
task: fetchTransactions,
taskId: 'fetchTransactions',
baseDelay: TX_REFETCH_INTERVAL,
})
return () => {
appScheduler.removeAllTasks()
}
}, [fetchPeers, fetchTransactions])
useEffect(() => {
// Set wallet open state.
setIsWalletOpen(true)
// fetch data from lnd.
fetchActivityHistory()
// fetch node info.
fetchPeers()
}, [fetchActivityHistory, fetchPeers, setIsWalletOpen])
// Open the pay form when a payment link is used.
useEffect(() => {
if (isAppReady && payReq) {
if (!modals.find(m => m.type === 'PAY_FORM')) {
setModals([{ type: 'PAY_FORM' }])
}
}
}, [payReq, isAppReady, modals, setModals])
if (!isAppReady) {
return null
}
return (
<MainContent>
<Wallet />
<Activity />
</MainContent>
)
}
App.propTypes = {
fetchActivityHistory: PropTypes.func.isRequired,
fetchPeers: PropTypes.func.isRequired,
fetchTransactions: PropTypes.func.isRequired,
isAppReady: PropTypes.bool.isRequired,
modals: PropTypes.array.isRequired,
payReq: PropTypes.object,
setIsWalletOpen: PropTypes.func.isRequired,
setModals: PropTypes.func.isRequired,
}
export default App
| renderer/components/App/App.js | import React, { useEffect, useState } from 'react'
import PropTypes from 'prop-types'
import Activity from 'containers/Activity'
import Wallet from 'containers/Wallet'
import { MainContent } from 'components/UI'
import { useInterval } from 'hooks'
// Bitcoin blocks come on average every 10 mins
// but we poll a lot more frequently to make UI a little bit more responsive
const TX_REFETCH_INTERVAL = 1000 * 60 * 1
// Initial re-fetch after 2 seconds.
const INITIAL_REFETCH_INTERVAL = 2000
// Fetch node data no less than once every 10 minutes.
const MAX_REFETCH_INTERVAL = 1000 * 60 * 10
// Amount to increment re-fetch timer by after each fetch.
const BACKOFF_SCHEDULE = 1.5
function App({
isAppReady,
modals,
payReq,
fetchActivityHistory,
setIsWalletOpen,
fetchPeers,
fetchTransactions,
setModals,
}) {
const [nextFetchIn, setNextFetchIn] = useState(INITIAL_REFETCH_INTERVAL)
/**
* Fetch node data on an exponentially incrementing backoff schedule so that when the app is first mounted, we fetch
* node data quite frequently but as time goes on the frequency is reduced down to a maximum of MAX_REFETCH_INTERVAL
*/
const fetchData = () => {
setNextFetchIn(Math.round(Math.min(nextFetchIn * BACKOFF_SCHEDULE, MAX_REFETCH_INTERVAL)))
// Fetch information about connected peers.
fetchPeers()
}
useEffect(() => {
// Set wallet open state.
setIsWalletOpen(true)
// fetch data from lnd.
fetchActivityHistory()
// fetch node info.
fetchPeers()
}, [fetchActivityHistory, fetchPeers, setIsWalletOpen])
// Open the pay form when a payment link is used.
useEffect(() => {
if (isAppReady && payReq) {
if (!modals.find(m => m.type === 'PAY_FORM')) {
setModals([{ type: 'PAY_FORM' }])
}
}
}, [payReq, isAppReady, modals, setModals])
useInterval(fetchData, nextFetchIn)
useInterval(fetchTransactions, TX_REFETCH_INTERVAL)
if (!isAppReady) {
return null
}
return (
<MainContent>
<Wallet />
<Activity />
</MainContent>
)
}
App.propTypes = {
fetchActivityHistory: PropTypes.func.isRequired,
fetchPeers: PropTypes.func.isRequired,
fetchTransactions: PropTypes.func.isRequired,
isAppReady: PropTypes.bool.isRequired,
modals: PropTypes.array.isRequired,
payReq: PropTypes.object,
setIsWalletOpen: PropTypes.func.isRequired,
setModals: PropTypes.func.isRequired,
}
export default App
| perf(app): prevent superfluous top level re-renders
| renderer/components/App/App.js | perf(app): prevent superfluous top level re-renders | <ide><path>enderer/components/App/App.js
<del>import React, { useEffect, useState } from 'react'
<add>import React, { useEffect } from 'react'
<add>import createScheduler from '@zap/utils/scheduler'
<ide> import PropTypes from 'prop-types'
<ide> import Activity from 'containers/Activity'
<ide> import Wallet from 'containers/Wallet'
<ide> import { MainContent } from 'components/UI'
<del>import { useInterval } from 'hooks'
<ide>
<ide> // Bitcoin blocks come on average every 10 mins
<ide> // but we poll a lot more frequently to make UI a little bit more responsive
<ide> // Amount to increment re-fetch timer by after each fetch.
<ide> const BACKOFF_SCHEDULE = 1.5
<ide>
<add>// App scheduler / polling service
<add>const appScheduler = createScheduler()
<add>
<ide> function App({
<ide> isAppReady,
<ide> modals,
<ide> fetchTransactions,
<ide> setModals,
<ide> }) {
<del> const [nextFetchIn, setNextFetchIn] = useState(INITIAL_REFETCH_INTERVAL)
<ide> /**
<del> * Fetch node data on an exponentially incrementing backoff schedule so that when the app is first mounted, we fetch
<del> * node data quite frequently but as time goes on the frequency is reduced down to a maximum of MAX_REFETCH_INTERVAL
<add> * App scheduler / polling service setup. Add new app-wide polls here
<ide> */
<del> const fetchData = () => {
<del> setNextFetchIn(Math.round(Math.min(nextFetchIn * BACKOFF_SCHEDULE, MAX_REFETCH_INTERVAL)))
<del> // Fetch information about connected peers.
<del> fetchPeers()
<del> }
<add> useEffect(() => {
<add> /**
<add> * Fetch node data on an exponentially incrementing backoff schedule so that when the app is first mounted, we fetch
<add> * node data quite frequently but as time goes on the frequency is reduced down to a maximum of MAX_REFETCH_INTERVAL
<add> */
<add> appScheduler.addTask({
<add> task: fetchPeers,
<add> taskId: 'fetchPeers',
<add> baseDelay: INITIAL_REFETCH_INTERVAL,
<add> maxDelay: MAX_REFETCH_INTERVAL,
<add> backoff: BACKOFF_SCHEDULE,
<add> })
<add>
<add> appScheduler.addTask({
<add> task: fetchTransactions,
<add> taskId: 'fetchTransactions',
<add> baseDelay: TX_REFETCH_INTERVAL,
<add> })
<add>
<add> return () => {
<add> appScheduler.removeAllTasks()
<add> }
<add> }, [fetchPeers, fetchTransactions])
<ide>
<ide> useEffect(() => {
<ide> // Set wallet open state.
<ide> }
<ide> }
<ide> }, [payReq, isAppReady, modals, setModals])
<del>
<del> useInterval(fetchData, nextFetchIn)
<del> useInterval(fetchTransactions, TX_REFETCH_INTERVAL)
<ide>
<ide> if (!isAppReady) {
<ide> return null |
|
JavaScript | apache-2.0 | 497293f61c4869a1b9989895b6934fd79f3cae01 | 0 | jivesoftware/jive-sdk,jivesoftware/jive-sdk,jivesoftware/jive-sdk | /*
* Copyright 2013 Jive Software
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* A simple REST service to store and retrieve todos from a file database.
*
* This is not meant for production use and only mean as a service to server
* the example app.
*/
var jive = require('jive-sdk'),
db = jive.service.persistence(),
shared = require("../../../{{{TILE_PREFIX}}}todoConfig/shared.js");
var update = function( todo, description ) {
jive.events.emit("todoUpdate", todo, description);
};
var todoHandler = function(req, res) {
shared.getClientIDForRequest(req).then(function(clientid) {
var project = req.param("project"),
assignee = req.param("assignee"),
criteria = {};
if(clientid) {
criteria.clientid = clientid;
}
if(project) {
criteria.project = project;
}
if( assignee ) {
criteria.assignee = assignee;
}
db.find("todos",criteria).then(function( todos ) {
res.status(200);
res.set({'Content-Type': 'application/json'});
res.send( JSON.stringify({todos: todos }, null, 4 ));
});
});
};
var todoCreator = function(req, res) {
shared.getClientIDForRequest(req).then(function(clientid) {
if( !req.body.name ) {
res.status(400);
res.send("Expected json body with name");
return;
}
var todo = {};
for(var key in req.body){
todo[key] = req.body[key];
}
todo.clientid = clientid;
var id = todo.id;
if (!id) {
id =(new Date()).getTime();
todo.id = id
}
db.save("todos", id, todo ).then(function( data ) {
res.status(200);
res.set( {
'Content-Type': 'application/json',
'Pragma': 'no-cache'
});
update(data, "Created todo '" + todo.name + "'");
res.send( data );
});
});
};
var todoDetailHandler = function(req, res) {
var id = parseInt(req.param("id"), 10);
db.find( "todos", {id: id} ).then( function ( todos ) {
res.set( {
'Content-Type': 'application/json',
'Pragma': 'no-cache'
});
if( todos.length > 0) {
res.status( 200 );
res.send( JSON.stringify( todos[0], null, 4 ) );
} else {
res.status( 404 );
res.send("");
}
} );
};
var todoEditHandler = function(req, res) {
var id = parseInt(req.param("id"), 10 ),
todoStatus = req.param("status"),
name = req.param("name"),
assignee = req.param("assignee"),
project = req.param("project");
db.find( "todos", {id: id} ).then( function ( todos ) {
var todo;
res.set( {
'Content-Type': 'application/json',
'Pragma': 'no-cache'
});
if( todos.length > 0) {
todo = todos[0];
todo.status = todoStatus;
todo.name = name;
todo.assignee = assignee;
todo.project = project;
db.save("todos", todo.id, todo ).then(function() {
update(todo, "Edited todo '" + todo.name + "' status ='" + todo.status + "'");
res.status( 200 );
res.send( JSON.stringify( todo, null, 4 ) );
});
} else {
res.status( 404 );
res.send("");
}
} );
};
exports.todoHandler = {
'path' : 'todos',
'verb' : 'get',
'route': todoHandler
};
exports.todoDetailHandler = {
'path' : "todos/:id",
'verb' : 'get',
'route': todoDetailHandler
};
exports.todoEditHandler = {
'path' : "todos/:id",
'verb' : 'put',
'route': todoEditHandler
};
exports.todoCreator = {
'path' : 'todos',
'verb' : 'post',
'route': todoCreator
}; | jive-sdk-service/generator/examples/todo/services/todo/backend/routes/tasks.js | /*
* Copyright 2013 Jive Software
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* A simple REST service to store and retrieve todos from a file database.
*
* This is not meant for production use and only mean as a service to server
* the example app.
*/
var jive = require('jive-sdk'),
db = jive.service.persistence(),
shared = require("../../../{{{TILE_PREFIX}}}todoConfig/shared.js");
var update = function( todo, description ) {
jive.events.emit("todoUpdate", todo, description);
};
var todoHandler = function(req, res) {
shared.getClientIDForRequest(req).then(function(clientid) {
var project = req.param("project"),
assignee = req.param("assignee"),
criteria = {};
if(clientid) {
criteria.clientid = clientid;
}
if(project) {
criteria.project = project;
}
if( assignee ) {
criteria.assignee = assignee;
}
db.find("todos",criteria).then(function( todos ) {
res.status(200);
res.set({'Content-Type': 'application/json'});
res.send( JSON.stringify({todos: todos }, null, 4 ));
});
});
};
var todoCreator = function(req, res) {
shared.getClientIDForRequest(req).then(function(clientid) {
if( !req.body.name ) {
res.status(400);
res.send("Expected json body with name");
return;
}
var todo = {};
for(var key in req.body){
todo[key] = req.body[key];
}
todo.clientid = clientid;
var id = todo.id;
if (!id) {
id =(new Date()).getTime();
todo.id = id
}
db.save("todos", id, todo ).then(function( data ) {
res.status(200);
res.set( {
'Content-Type': 'application/json',
'Pragma': 'no-cache'
});
update(data, "Created todo '" + todo.name + "'");
res.send( data );
});
});
};
var todoDetailHandler = function(req, res) {
var id = parseInt(req.param("id"), 10);
db.find( "todos", {id: id} ).then( function ( todos ) {
res.set( {
'Content-Type': 'application/json',
'Pragma': 'no-cache'
});
if( todos.length > 0) {
res.status( 200 );
res.send( JSON.stringify( todos[0], null, 4 ) );
} else {
res.status( 404 );
res.send("");
}
} );
};
var todoEditHandler = function(req, res) {
var id = parseInt(req.param("id"), 10 ),
todoStatus = req.param("status"),
name = req.param("name"),
project = req.param("project");
db.find( "todos", {id: id} ).then( function ( todos ) {
var todo;
res.set( {
'Content-Type': 'application/json',
'Pragma': 'no-cache'
});
if( todos.length > 0) {
todo = todos[0];
todo.status = todoStatus;
todo.name = name;
todo.project = project;
db.save("todos", todo.id, todo ).then(function() {
update(todo, "Edited todo '" + todo.name + "' status ='" + todo.status + "'");
res.status( 200 );
res.send( JSON.stringify( todo, null, 4 ) );
});
} else {
res.status( 404 );
res.send("");
}
} );
};
exports.todoHandler = {
'path' : 'todos',
'verb' : 'get',
'route': todoHandler
};
exports.todoDetailHandler = {
'path' : "todos/:id",
'verb' : 'get',
'route': todoDetailHandler
};
exports.todoEditHandler = {
'path' : "todos/:id",
'verb' : 'put',
'route': todoEditHandler
};
exports.todoCreator = {
'path' : 'todos',
'verb' : 'post',
'route': todoCreator
}; | Allowed assignee to change via the edit handler.
| jive-sdk-service/generator/examples/todo/services/todo/backend/routes/tasks.js | Allowed assignee to change via the edit handler. | <ide><path>ive-sdk-service/generator/examples/todo/services/todo/backend/routes/tasks.js
<ide> var id = parseInt(req.param("id"), 10 ),
<ide> todoStatus = req.param("status"),
<ide> name = req.param("name"),
<add> assignee = req.param("assignee"),
<ide> project = req.param("project");
<ide> db.find( "todos", {id: id} ).then( function ( todos ) {
<ide> var todo;
<ide> todo = todos[0];
<ide> todo.status = todoStatus;
<ide> todo.name = name;
<add> todo.assignee = assignee;
<ide> todo.project = project;
<ide> db.save("todos", todo.id, todo ).then(function() {
<ide> update(todo, "Edited todo '" + todo.name + "' status ='" + todo.status + "'"); |
|
Java | agpl-3.0 | a9838c9daeb803ffd684e943c8d66b63b477364c | 0 | zuowang/voltdb,kumarrus/voltdb,flybird119/voltdb,deerwalk/voltdb,simonzhangsm/voltdb,zuowang/voltdb,creative-quant/voltdb,simonzhangsm/voltdb,zuowang/voltdb,wolffcm/voltdb,kumarrus/voltdb,wolffcm/voltdb,creative-quant/voltdb,deerwalk/voltdb,flybird119/voltdb,deerwalk/voltdb,VoltDB/voltdb,kumarrus/voltdb,kobronson/cs-voltdb,wolffcm/voltdb,wolffcm/voltdb,paulmartel/voltdb,simonzhangsm/voltdb,simonzhangsm/voltdb,zuowang/voltdb,VoltDB/voltdb,kobronson/cs-voltdb,migue/voltdb,ingted/voltdb,flybird119/voltdb,wolffcm/voltdb,ingted/voltdb,creative-quant/voltdb,simonzhangsm/voltdb,zuowang/voltdb,wolffcm/voltdb,paulmartel/voltdb,ingted/voltdb,ingted/voltdb,kumarrus/voltdb,kobronson/cs-voltdb,migue/voltdb,kobronson/cs-voltdb,ingted/voltdb,deerwalk/voltdb,paulmartel/voltdb,paulmartel/voltdb,flybird119/voltdb,deerwalk/voltdb,VoltDB/voltdb,migue/voltdb,wolffcm/voltdb,VoltDB/voltdb,creative-quant/voltdb,ingted/voltdb,kobronson/cs-voltdb,simonzhangsm/voltdb,flybird119/voltdb,flybird119/voltdb,kumarrus/voltdb,kumarrus/voltdb,VoltDB/voltdb,kumarrus/voltdb,kumarrus/voltdb,kobronson/cs-voltdb,ingted/voltdb,paulmartel/voltdb,deerwalk/voltdb,simonzhangsm/voltdb,deerwalk/voltdb,wolffcm/voltdb,creative-quant/voltdb,zuowang/voltdb,flybird119/voltdb,migue/voltdb,migue/voltdb,simonzhangsm/voltdb,flybird119/voltdb,creative-quant/voltdb,VoltDB/voltdb,kobronson/cs-voltdb,paulmartel/voltdb,kobronson/cs-voltdb,paulmartel/voltdb,migue/voltdb,creative-quant/voltdb,paulmartel/voltdb,deerwalk/voltdb,migue/voltdb,zuowang/voltdb,creative-quant/voltdb,migue/voltdb,zuowang/voltdb,ingted/voltdb,VoltDB/voltdb | /* This file is part of VoltDB.
* Copyright (C) 2008-2012 VoltDB Inc.
*
* VoltDB is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* VoltDB is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with VoltDB. If not, see <http://www.gnu.org/licenses/>.
*/
package org.voltdb.dtxn;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.zookeeper_voltpatches.WatchedEvent;
import org.apache.zookeeper_voltpatches.Watcher;
import org.apache.zookeeper_voltpatches.ZooKeeper;
import org.json_voltpatches.JSONException;
import org.json_voltpatches.JSONObject;
import org.voltcore.logging.VoltLogger;
import org.voltcore.utils.MiscUtils;
public class MailboxTracker {
private static final VoltLogger log = new VoltLogger("HOST");
private final ZooKeeper m_zk;
private volatile Map<Integer, ArrayList<Long>> m_hostsToSites =
new HashMap<Integer, ArrayList<Long>>();
private volatile Map<Integer, ArrayList<Long>> m_partitionsToSites =
new HashMap<Integer, ArrayList<Long>>();
private volatile Map<Long, Integer> m_sitesToPartitions =
new HashMap<Long, Integer>();
private volatile Map<Integer, Long> m_hostsToPlanners =
new HashMap<Integer, Long>();
private volatile Map<Integer, ArrayList<Long>> m_hostsToInitiators =
new HashMap<Integer, ArrayList<Long>>();
public MailboxTracker(ZooKeeper zk) throws Exception {
m_zk = zk;
getAndWatchSites();
getAndWatchPlanners();
getAndWatchInitiators();
}
private void getAndWatchSites() throws Exception {
List<String> children = m_zk.getChildren("/mailboxes/executionsites", new Watcher() {
@Override
public void process(WatchedEvent event) {
try {
getAndWatchSites();
} catch (Exception e) {
log.error(e.getMessage());
}
}
});
Map<Integer, ArrayList<Long>> hostsToSites = new HashMap<Integer, ArrayList<Long>>();
Map<Integer, ArrayList<Long>> partitionsToSites = new HashMap<Integer, ArrayList<Long>>();
Map<Long, Integer> sitesToPartitions = new HashMap<Long, Integer>();
for (String child : children) {
byte[] data = m_zk.getData("/mailboxes/executionsites/" + child, false, null);
JSONObject jsObj = new JSONObject(new String(data, "UTF-8"));
try {
long HSId = jsObj.getLong("HSId");
int partitionId = jsObj.getInt("partitionId");
int hostId = MiscUtils.getHostIdFromHSId(HSId);
ArrayList<Long> sites = hostsToSites.get(hostId);
if (sites == null)
{
sites = new ArrayList<Long>();
hostsToSites.put(hostId, sites);
}
sites.add(HSId);
sites = partitionsToSites.get(partitionId);
if (sites == null) {
sites = new ArrayList<Long>();
partitionsToSites.put(partitionId, sites);
}
sites.add(HSId);
sitesToPartitions.put(HSId, partitionId);
} catch (JSONException e) {
log.error(e.getMessage());
}
}
m_hostsToSites = hostsToSites;
m_partitionsToSites = partitionsToSites;
m_sitesToPartitions = sitesToPartitions;
}
private void getAndWatchPlanners() throws Exception {
List<String> children = m_zk.getChildren("/mailboxes/asyncplanners", new Watcher() {
@Override
public void process(WatchedEvent event) {
try {
getAndWatchPlanners();
} catch (Exception e) {
log.error(e.getMessage());
}
}
});
Map<Integer, Long> hostsToPlanners = new HashMap<Integer, Long>();
for (String child : children) {
byte[] data = m_zk.getData("/mailboxes/asyncplanners/" + child, false, null);
JSONObject jsObj = new JSONObject(new String(data, "UTF-8"));
try {
long HSId = jsObj.getLong("HSId");
hostsToPlanners.put(MiscUtils.getHostIdFromHSId(HSId), HSId);
} catch (JSONException e) {
log.error(e.getMessage());
}
}
m_hostsToPlanners = hostsToPlanners;
}
private void getAndWatchInitiators() throws Exception {
List<String> children = m_zk.getChildren("/mailboxes/initiators", new Watcher() {
@Override
public void process(WatchedEvent event) {
try {
getAndWatchInitiators();
} catch (Exception e) {
log.error(e.getMessage());
}
}
});
Map<Integer, ArrayList<Long>> hostsToInitiators = new HashMap<Integer, ArrayList<Long>>();
for (String child : children) {
byte[] data = m_zk.getData("/mailboxes/initiators/" + child, false, null);
JSONObject jsObj = new JSONObject(new String(data, "UTF-8"));
try {
long HSId = jsObj.getLong("HSId");
int hostId = MiscUtils.getHostIdFromHSId(HSId);
ArrayList<Long> initiators = hostsToInitiators.get(hostId);
if (initiators == null) {
initiators = new ArrayList<Long>();
hostsToInitiators.put(hostId, initiators);
}
initiators.add(HSId);
// TODO: needs to determine if it's the master or replica
} catch (JSONException e) {
log.error(e.getMessage());
}
}
m_hostsToInitiators = hostsToInitiators;
}
public static int getHostForHSId(long HSId) {
return MiscUtils.getHostIdFromHSId(HSId);
}
public List<Long> getSitesForHost(int hostId) {
return m_hostsToSites.get(hostId);
}
public List<Long> getSitesForPartition(int partitionId) {
return m_partitionsToSites.get(partitionId);
}
public Integer getPartitionForSite(long hsId) {
return m_sitesToPartitions.get(hsId);
}
public Long getPlannerForHost(int hostId) {
return m_hostsToPlanners.get(hostId);
}
public List<Long> getInitiatorForHost(int hostId) {
return m_hostsToInitiators.get(hostId);
}
public Set<Integer> getAllHosts() {
HashSet<Integer> hosts = new HashSet<Integer>();
hosts.addAll(m_hostsToSites.keySet());
return hosts;
}
public Set<Long> getAllSites() {
HashSet<Long> sites = new HashSet<Long>();
for (Collection<Long> values : m_hostsToSites.values()) {
sites.addAll(values);
}
return sites;
}
public Set<Long> getAllInitiators() {
HashSet<Long> initiators = new HashSet<Long>();
for (Collection<Long> values : m_hostsToInitiators.values()) {
initiators.addAll(values);
}
return initiators;
}
}
| src/frontend/org/voltdb/dtxn/MailboxTracker.java | /* This file is part of VoltDB.
* Copyright (C) 2008-2012 VoltDB Inc.
*
* VoltDB is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* VoltDB is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with VoltDB. If not, see <http://www.gnu.org/licenses/>.
*/
package org.voltdb.dtxn;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.zookeeper_voltpatches.WatchedEvent;
import org.apache.zookeeper_voltpatches.Watcher;
import org.apache.zookeeper_voltpatches.ZooKeeper;
import org.json_voltpatches.JSONException;
import org.json_voltpatches.JSONObject;
import org.voltcore.logging.VoltLogger;
import org.voltcore.utils.MiscUtils;
public class MailboxTracker {
private static final VoltLogger log = new VoltLogger("HOST");
private final ZooKeeper m_zk;
private volatile Map<Integer, ArrayList<Long>> m_hostsToSites =
new HashMap<Integer, ArrayList<Long>>();
private volatile Map<Integer, ArrayList<Long>> m_partitionsToSites =
new HashMap<Integer, ArrayList<Long>>();
private volatile Map<Long, Integer> m_sitesToPartitions =
new HashMap<Long, Integer>();
private volatile Map<Integer, Long> m_hostsToPlanners =
new HashMap<Integer, Long>();
private volatile Map<Integer, ArrayList<Long>> m_hostsToInitiators =
new HashMap<Integer, ArrayList<Long>>();
public MailboxTracker(ZooKeeper zk) throws Exception {
m_zk = zk;
getAndWatchSites();
getAndWatchPlanners();
getAndWatchInitiators();
}
private void getAndWatchSites() throws Exception {
List<String> children = m_zk.getChildren("/mailboxes/executionsites", new Watcher() {
@Override
public void process(WatchedEvent event) {
try {
getAndWatchSites();
} catch (Exception e) {
log.error(e.getMessage());
}
}
});
Map<Integer, ArrayList<Long>> hostsToSites = new HashMap<Integer, ArrayList<Long>>();
Map<Integer, ArrayList<Long>> partitionsToSites = new HashMap<Integer, ArrayList<Long>>();
Map<Long, Integer> sitesToPartitions = new HashMap<Long, Integer>();
for (String child : children) {
byte[] data = m_zk.getData("/mailboxes/executionsites/" + child, false, null);
JSONObject jsObj = new JSONObject(new String(data, "UTF-8"));
try {
long HSId = jsObj.getLong("HSId");
int partitionId = jsObj.getInt("partitionId");
int hostId = MiscUtils.getHostIdFromHSId(HSId);
ArrayList<Long> sites = hostsToSites.get(hostId);
if (sites == null)
{
sites = new ArrayList<Long>();
hostsToSites.put(hostId, sites);
}
sites.add(HSId);
sites = partitionsToSites.get(partitionId);
if (sites == null) {
sites = new ArrayList<Long>();
partitionsToSites.put(partitionId, sites);
}
sites.add(HSId);
sitesToPartitions.put(HSId, partitionId);
} catch (JSONException e) {
log.error(e.getMessage());
}
}
m_hostsToSites = hostsToSites;
m_partitionsToSites = partitionsToSites;
m_sitesToPartitions = sitesToPartitions;
}
private void getAndWatchPlanners() throws Exception {
List<String> children = m_zk.getChildren("/mailboxes/asyncplanners", new Watcher() {
@Override
public void process(WatchedEvent event) {
try {
getAndWatchPlanners();
} catch (Exception e) {
log.error(e.getMessage());
}
}
});
Map<Integer, Long> hostsToPlanners = new HashMap<Integer, Long>();
for (String child : children) {
byte[] data = m_zk.getData("/mailboxes/asyncplanners/" + child, false, null);
JSONObject jsObj = new JSONObject(new String(data, "UTF-8"));
try {
long HSId = jsObj.getLong("HSId");
hostsToPlanners.put(MiscUtils.getHostIdFromHSId(HSId), HSId);
} catch (JSONException e) {
log.error(e.getMessage());
}
}
m_hostsToPlanners = hostsToPlanners;
}
private void getAndWatchInitiators() throws Exception {
List<String> children = m_zk.getChildren("/mailboxes/initiators", new Watcher() {
@Override
public void process(WatchedEvent event) {
try {
getAndWatchInitiators();
} catch (Exception e) {
log.error(e.getMessage());
}
}
});
Map<Integer, ArrayList<Long>> hostsToInitiators = new HashMap<Integer, ArrayList<Long>>();
for (String child : children) {
byte[] data = m_zk.getData("/mailboxes/initiators/" + child, false, null);
JSONObject jsObj = new JSONObject(new String(data, "UTF-8"));
try {
long HSId = jsObj.getLong("HSId");
int hostId = MiscUtils.getHostIdFromHSId(HSId);
ArrayList<Long> initiators = new ArrayList<Long>();
hostsToInitiators.put(hostId, initiators);
initiators.add(HSId);
initiators = new ArrayList<Long>();
initiators.add(HSId);
// TODO: needs to determine if it's the master or replica
} catch (JSONException e) {
log.error(e.getMessage());
}
}
m_hostsToInitiators = hostsToInitiators;
}
public static int getHostForHSId(long HSId) {
return MiscUtils.getHostIdFromHSId(HSId);
}
public List<Long> getSitesForHost(int hostId) {
return m_hostsToSites.get(hostId);
}
public List<Long> getSitesForPartition(int partitionId) {
return m_partitionsToSites.get(partitionId);
}
public Integer getPartitionForSite(long hsId) {
return m_sitesToPartitions.get(hsId);
}
public Long getPlannerForHost(int hostId) {
return m_hostsToPlanners.get(hostId);
}
public List<Long> getInitiatorForHost(int hostId) {
return m_hostsToInitiators.get(hostId);
}
public Set<Integer> getAllHosts() {
HashSet<Integer> hosts = new HashSet<Integer>();
hosts.addAll(m_hostsToSites.keySet());
return hosts;
}
public Set<Long> getAllSites() {
HashSet<Long> sites = new HashSet<Long>();
for (Collection<Long> values : m_hostsToSites.values()) {
sites.addAll(values);
}
return sites;
}
public Set<Long> getAllInitiators() {
HashSet<Long> initiators = new HashSet<Long>();
for (Collection<Long> values : m_hostsToInitiators.values()) {
initiators.addAll(values);
}
return initiators;
}
}
| Fix mailbox tracker.
| src/frontend/org/voltdb/dtxn/MailboxTracker.java | Fix mailbox tracker. | <ide><path>rc/frontend/org/voltdb/dtxn/MailboxTracker.java
<ide> long HSId = jsObj.getLong("HSId");
<ide> int hostId = MiscUtils.getHostIdFromHSId(HSId);
<ide>
<del> ArrayList<Long> initiators = new ArrayList<Long>();
<del> hostsToInitiators.put(hostId, initiators);
<add> ArrayList<Long> initiators = hostsToInitiators.get(hostId);
<add> if (initiators == null) {
<add> initiators = new ArrayList<Long>();
<add> hostsToInitiators.put(hostId, initiators);
<add> }
<ide> initiators.add(HSId);
<del>
<del> initiators = new ArrayList<Long>();
<del> initiators.add(HSId);
<del>
<ide> // TODO: needs to determine if it's the master or replica
<ide> } catch (JSONException e) {
<ide> log.error(e.getMessage()); |
|
JavaScript | mit | 6e001fff2fcf6f94f28e213c249d74b414daadb3 | 0 | lsm/superplumber,lsm/superpipe | 'use strict'
/**
* Module dependencies
*/
var Pipe = require('./pipe')
var slice = require('lodash.slice')
var assign = require('lodash.assign')
var foreach = require('lodash.foreach')
var toArray = require('lodash.toarray')
var isArray = require('lodash.isarray')
var Injector = require('insider')
/**
* Pipeline constructor. Pipeline is the place where you define a series of
* operations you need to do when certain things happened (events).
*
* @param {SuperPipe} [superpipe] Instance of SuperPipe.
* @return {Pipeline} Instance of Pipeline.
*/
var Pipeline = module.exports = function Pipeline(superpipe, pipes) {
var pipeline = assign(function() {
Pipe.toPipe(pipeline).apply(null, toArray(arguments))
}, pipelineFunctions)
var _pipes = isArray(pipes) ? slice(pipes) : []
var injector
/**
* Pipeline reconstruction functions. Define them inline as we want to keep
* `_pipes` private.
*/
/**
* Remove a pipe from the end of pipes and return it.
*/
pipeline.pop = function() {
return _pipes.pop()
}
/**
* Push a pipe into pipeline
* @param {Object} pipe
* @return {Pipeline}
*/
pipeline.push = function(pipe) {
_pipes.push(pipe)
return this
}
pipeline.getPipes = function() {
return slice(_pipes)
}
pipeline.getInjector = function() {
return injector
}
pipeline.concat = function(pipeline) {
var pipes = _pipes.concat(pipeline.getPipes())
var concated = new Pipeline(injector, pipes)
concated.debug(this.debug())
concated.errorHandler = this.errorHandler
return concated
}
/**
* Create a new pipeline using a slice of the original pipeline
* @param {Number} [begin]
* @param {Number} [end]
* @return {Pipeline}
*/
pipeline.slice = function(begin, end) {
var sliced = new Pipeline(injector, slice(_pipes, begin, end))
sliced.debug(this.debug())
sliced.errorHandler = this.errorHandler
return sliced
}
/**
* Connect a pipeline to a instance of Superpipe.
* Then the pipeline will use that superpipe as
* its container of dependencies injection.
*
* @param {Superpipe} superpipe instance of superpipe
* @return {Pipeline} Instance of Pipeline
*/
pipeline.connect = function(superpipe) {
if (superpipe && true === superpipe.instanceOfSuperPipe)
injector = superpipe.injector
else if (superpipe && superpipe.getAll && superpipe.get && superpipe.set)
injector = superpipe
else
injector = new Injector()
return pipeline
}
// Connect pipeline with superpipe (share container of dependency injection)
pipeline.connect(superpipe)
return pipeline
}
/**
* Static function which convert a pipeline to a pipe function
* @type {Function}
*/
Pipeline.toPipe = Pipe.toPipe
/**
* Pipeline instance functions
*/
var pipelineFunctions = {}
/**
* Put function and its dependencies to the pipeline.
*
* @param {Function|String|Number|Array} fn
* - Function: The pipe function
* - String: Name of function which could be found in dependencies.
* - Number: Number of miliseconds to throttle the pipeline.
* - Array: A array which contains both `fn` (first) and `deps` (rest).
* @param {Array|String} ...deps String or array of names of dependencies.
* @return {Pipeline} Instance of this Pipeline.
*/
pipelineFunctions.pipe = function(fn, deps, supplies) {
var type = typeof fn
if ('number' === typeof fn) {
return this.throttle(fn)
} else if ('string' === type) {
if ('emit' === fn)
// .pipe('emit', 'event name', ['event', 'object'])
return this.emit(deps, supplies)
else
return this.dipe(fn, deps, supplies)
} else if (true === fn.instanceOfPipeline) {
fn = fn.toPipe(this.getInjector())
}
// save to the pipes array as a pipes unit
var pipe = buildPipe(fn, deps, supplies)
this.push(pipe)
return this
}
pipelineFunctions.emit = function(eventName, deps) {
var self = this
var fn = function() {
var args = toArray(arguments)
args.unshift(eventName)
var emit = self.getInjector().get('emit')
emit.apply(null, args)
}
// Build the pipe.
var pipe = buildPipe(fn, deps)
this.push(pipe)
return this
}
pipelineFunctions.dipe = function(name, deps, supplies) {
var pipe
var fn = function() {
var ofn = pipe.ofn
if ('function' === typeof ofn) {
// when it's a function call it with rest of the arguments
var result = ofn.apply(this, toArray(arguments))
if ('boolean' === typeof result)
return pipe.not ? !result : result
else
return result
} else if ('boolean' === typeof ofn) {
// directly return the value when it is a boolean for flow control
return pipe.not ? !ofn : ofn
} else if (true === pipe.optional && 'undefined' === typeof ofn) {
// Optional pipe which pipe function can not be found.
// Return true to ignore and go next.
return true
} else {
throw new Error('Dependency `' + name + '` is not a function.')
}
}
// Build the pipe.
pipe = buildPipe(fn, deps, supplies)
if (/^!/.test(name)) {
pipe.not = true
name = name.slice(1)
}
if (/\?$/.test(name)) {
// Optional pipe if function name ends with question mark.
pipe.optional = true
// Remove the trailing question mark.
name = name.slice(0, name.length - 1)
}
// Set the original function name to the pipe object for later dependency discovery.
pipe.fnName = name
return this.push(pipe)
}
pipelineFunctions.throttle = function(msec) {
// Generate a throttle function and push to pipes
var timestamp
return this.push({
fn: function throttleFn() {
var now = new Date()
if (!timestamp || now - timestamp > msec) {
timestamp = new Date()
return true
} else {
return false
}
}
})
}
pipelineFunctions.wait = function(msec) {
// Generate a wait function and push to pipes
return this.push({
fn: function waitFn(next) {
setTimeout(next, msec)
},
deps: ['next']
})
}
pipelineFunctions.clone = function(superpipe) {
var cloned = this.slice()
if (superpipe)
cloned.connect(superpipe)
return cloned
}
pipelineFunctions.toPipe = function(superpipe, name) {
var cloned = this.clone(superpipe)
return Pipeline.toPipe(cloned, name)
}
pipelineFunctions.toCurriedPipe = function(name) {
var sliced = this.slice()
return function(superpipe) {
if (superpipe)
sliced.connect(superpipe)
return sliced.toPipe(null, name)
}
}
/**
* Set the error handler for this pipeline.
*
* @param {Function|String} fn
* - Function: The pipe function
* - String: Name of function which could be found in dependencies.
* @param {Array|String} deps... String or array of names of dependencies.
* @return {Pipeline} Instance of this Pipeline.
*/
pipelineFunctions.error = function(fn, deps) {
if ('number' === typeof fn)
throw new Error('Error handler does not accept numeric argument.')
this.errorHandler = this.pipe(fn, deps).pop()
return this
}
pipelineFunctions.debug = function(enabled) {
if ('undefined' === typeof enabled)
return this._debug
this._debug = enabled
return this
}
/**
* Private functions
*/
function getFnName(fn) {
var f = 'function' === typeof fn
var s = f && ((fn.name && ['', fn.name]) || fn.toString().match(/function ([^\(]+)/))
if (f)
return s && s[1] || 'anonymous'
}
/**
* The actual function for building a pipe.
*
* @param {Function} fn
* - Function: The pipe function
* - String: Name of function which could be found in dependencies.
* - Number: Number of miliseconds to throttle the pipeline.
* - Array: A array which contains both `fn` (first) and `deps` (rest).
* @param {Array|String} deps... String or array of names of dependencies.
* @return {Object} An object contains dependencies injected function and deps.
*/
function buildPipe(fn, deps, supplies) {
if ('function' !== typeof fn)
throw new Error('fn should be a function, got ' + typeof fn)
var depsType = typeof deps
if ('string' === depsType || 'number' === depsType)
deps = [deps]
if ('string' === typeof supplies)
supplies = [supplies]
if (deps && !isArray(deps))
throw new Error('deps should be either string or array of dependency names if present')
if (supplies && !isArray(supplies))
throw new Error('supplies should be either string or array of dependency names if present')
// If first dep is a number it tells us the number of original function
// arguments we need to pass for calling the pipe function.
if (deps) {
var firstDep = deps[0]
if ('number' === typeof firstDep && 0 < firstDep) {
deps[0] = null
while (1 < firstDep) {
deps.unshift(null)
firstDep--
}
}
}
// Detect any mapped supplies. Use the format `theOriginalName:theNewName` in
// `supplies` array would cause the `setDep('theOriginalName', obj)` to actually
// set the dependency equals calling `setDep('theNewName', obj)` hence mapped
// the dependency name.
var setDepMap
foreach(supplies, function(supply) {
if (/:/.test(supply)) {
setDepMap = setDepMap || {}
var mapping = supply.split(':')
setDepMap[mapping[0]] = mapping[1]
}
})
// Return pipe object with function and its metadata.
return {
fn: fn, // Original or wrapped function, should be never changed.
ofn: fn, // The ofn property might be changed during pipeline execution for
// loading/generating pipe functions dynamically.
deps: deps,
fnName: getFnName(fn),
supplies: supplies,
setDepMap: setDepMap
}
}
| lib/pipeline.js | 'use strict'
/**
* Module dependencies
*/
var bind = require('lodash.bind')
var Pipe = require('./pipe')
var slice = require('lodash.slice')
var assign = require('lodash.assign')
var foreach = require('lodash.foreach')
var toArray = require('lodash.toarray')
var isArray = require('lodash.isarray')
var Injector = require('insider')
/**
* Pipeline constructor. Pipeline is the place where you define a series of
* operations you need to do when certain things happened (events).
*
* @param {SuperPipe} [superpipe] Instance of SuperPipe.
* @return {Pipeline} Instance of Pipeline.
*/
var Pipeline = module.exports = function Pipeline(superpipe) {
var pipeline = assign(function(superpipe, name) {
pipeline.toPipe(superpipe, name)()
}, Pipeline.prototype)
pipeline.pipes = []
pipeline.connect(superpipe)
return pipeline
}
/**
* Static function which convert a pipeline to a pipe function
* @type {Function}
*/
Pipeline.toPipe = Pipe.toPipe
/**
* Connect a pipeline to a instance of Superpipe or Injector.
* Then the pipeline will use that superpipe/inector as
* its container of dependencies injection.
*
* @param {Superpipe|Injector} superpipe [description]
* @return {Pipeline} Instance of Pipeline
*/
Pipeline.prototype.connect = function(superpipe) {
if (superpipe && superpipe.instanceOfSuperPipe) {
this.superpipe = superpipe
this.injector = superpipe.injector
} else if (superpipe && superpipe instanceof Injector) {
this.injector = superpipe
} else {
this.injector = new Injector()
}
return this
}
/**
* Listen to a event emits from the emitter.
*
* @param {EventEmitter} [emitter] The emitter to listen events from.
* The superpipe instance will be used as emitter if only event name is provided.
* @param {String} name Name of the event to listen.
* @return {Pipeline} Instance of this Pipeline.
*/
Pipeline.prototype.listenTo = function(emitter, name) {
function listenTo(eventEmitter, eventName, pipeline) {
var listenFn = eventEmitter.on || eventEmitter.addEventListener || eventEmitter.addListener
if ('function' !== typeof listenFn)
throw new Error('emitter has no listening funciton "on, addEventListener or addListener"')
listenFn = bind(listenFn, eventEmitter)
listenFn(eventName, Pipeline.toPipe(pipeline))
}
if ('string' === typeof emitter) {
var superpipe = this.superpipe
if (name) {
// listenTo('nameOfEmitter', 'some event')
var self = this
var emitterName = emitter
emitter = superpipe.getDep(emitterName)
if (!emitter) {
superpipe.onSetDep(emitterName, function(newEmitter, oldEmitter) {
if (oldEmitter) {
var removeAll = (oldEmitter.removeAllListeners || oldEmitter.off)
removeAll && removeAll.call(oldEmitter, name)
}
listenTo(newEmitter, name, self)
})
return this
}
} else {
// listenTo('some event')
name = emitter
emitter = superpipe
}
}
listenTo(emitter, name, this)
return this
}
/**
* Put function and its dependencies to the pipeline.
*
* @param {Function|String|Number|Array} fn
* - Function: The pipe function
* - String: Name of function which could be found in dependencies.
* - Number: Number of miliseconds to throttle the pipeline.
* - Array: A array which contains both `fn` (first) and `deps` (rest).
* @param {Array|String} ...deps String or array of names of dependencies.
* @return {Pipeline} Instance of this Pipeline.
*/
Pipeline.prototype.pipe = function(fn, deps, supplies) {
var type = typeof fn
if ('number' === typeof fn) {
return this.throttle(fn)
} else if ('string' === type) {
if ('emit' === fn)
// .pipe('emit', 'event name', ['event', 'object'])
return this.emit(deps, supplies)
else
return this.dipe(fn, deps, supplies)
} else if (fn instanceof Pipeline) {
fn = fn.toPipe()
}
// save to the pipes array as a pipes unit
var pipe = this.buildPipe(fn, deps, supplies)
this.push(pipe)
return this
}
Pipeline.prototype.emit = function(eventName, deps) {
var self = this
var fn = function() {
var args = toArray(arguments)
args.unshift(eventName)
var emit = self.injector.get('emit')
emit.apply(null, args)
}
// Build the pipe.
var pipe = this.buildPipe(fn, deps)
this.push(pipe)
return this
}
Pipeline.prototype.dipe = function(name, deps, supplies) {
var pipe
var fn = function() {
var ofn = pipe.ofn
if ('function' === typeof ofn) {
// when it's a function call it with rest of the arguments
var result = ofn.apply(this, toArray(arguments))
if ('boolean' === typeof result)
return pipe.not ? !result : result
else
return result
} else if ('boolean' === typeof ofn) {
// directly return the value when it is a boolean for flow control
return pipe.not ? !ofn : ofn
} else if (true === pipe.optional && 'undefined' === typeof ofn) {
// Optional pipe which pipe function can not be found.
// Return true to ignore and go next.
return true
} else {
throw new Error('Dependency ' + name + ' is not a function or boolean.')
}
}
// Build the pipe.
pipe = this.buildPipe(fn, deps, supplies)
if (/^!/.test(name)) {
pipe.not = true
name = name.slice(1)
}
if (/\?$/.test(name)) {
// Optional pipe if function name ends with question mark.
pipe.optional = true
// Remove the trailing question mark.
name = name.slice(0, name.length - 1)
}
// Set the original function name to the pipe object for later dependency discovery.
pipe.fnName = name
return this.push(pipe)
}
Pipeline.prototype.throttle = function(msec) {
// Generate a throttle function and push to pipes
var timestamp
return this.push({
fn: function throttleFn() {
var now = new Date()
if (!timestamp || now - timestamp > msec) {
timestamp = new Date()
return true
} else {
return false
}
}
})
}
Pipeline.prototype.push = function(pipe) {
this.pipes.push(pipe)
return this
}
/**
* The actual function for building a pipe.
*
* @param {Function} fn
* - Function: The pipe function
* - String: Name of function which could be found in dependencies.
* - Number: Number of miliseconds to throttle the pipeline.
* - Array: A array which contains both `fn` (first) and `deps` (rest).
* @param {Array|String} deps... String or array of names of dependencies.
* @return {Object} An object contains dependencies injected function and deps.
*/
Pipeline.prototype.buildPipe = function(fn, deps, supplies) {
if ('function' !== typeof fn)
throw new Error('fn should be a function, got ' + typeof fn)
var depsType = typeof deps
if ('string' === depsType || 'number' === depsType)
deps = [deps]
if ('string' === typeof supplies)
supplies = [supplies]
if (deps && !isArray(deps))
throw new Error('deps should be either string or array of dependency names if present')
if (supplies && !isArray(supplies))
throw new Error('supplies should be either string or array of dependency names if present')
// If first dep is a number it tells us the number of original function
// arguments we need to pass for calling the pipe function.
if (deps) {
var firstDep = deps[0]
if ('number' === typeof firstDep && 0 < firstDep) {
deps[0] = null
while (1 < firstDep) {
deps.unshift(null)
firstDep--
}
}
}
// Detect any mapped supplies. Use the format `theOriginalName:theNewName` in
// `supplies` array would cause the `setDep('theOriginalName', obj)` to actually
// set the dependency equals calling `setDep('theNewName', obj)` hence mapped
// the dependency name.
var setDepMap
foreach(supplies, function(supply) {
if (/:/.test(supply)) {
setDepMap = setDepMap || {}
var mapping = supply.split(':')
setDepMap[mapping[0]] = mapping[1]
}
})
// Return pipe object with function and its metadata.
return {
fn: fn, // Original or wrapped function, should be never changed.
ofn: fn, // The ofn property might be changed during pipeline execution for
// loading/generating pipe functions dynamically.
deps: deps,
fnName: getFnName(fn),
supplies: supplies,
setDepMap: setDepMap
}
}
Pipeline.prototype.slice = function(begin, end) {
var sliced = new Pipeline(this.superpipe || this.injector)
sliced.debug(this.debug())
sliced.errorHandler = this.errorHandler
sliced.pipes = slice(this.pipes, begin, end)
return sliced
}
Pipeline.prototype.clone = function(superpipe) {
var cloned = this.slice()
if (superpipe)
cloned.connect(superpipe)
return cloned
}
Pipeline.prototype.concat = function(pipeline, begin, end) {
var concated = this.slice()
concated.pipes = concated.pipes.concat(slice(pipeline.pipes, begin, end))
return concated
}
Pipeline.prototype.toPipe = function(superpipe, name) {
var pipeline = this.clone(superpipe)
return Pipeline.toPipe(pipeline, slice(pipeline.pipes), name)
}
Pipeline.prototype.toCurriedPipe = function(name) {
var self = this.slice()
return function(superpipe) {
if (superpipe)
self.connect(superpipe)
return self.toPipe(null, name)
}
}
/**
* Set the error handler for this pipeline.
*
* @param {Function|String} fn
* - Function: The pipe function
* - String: Name of function which could be found in dependencies.
* @param {Array|String} deps... String or array of names of dependencies.
* @return {Pipeline} Instance of this Pipeline.
*/
Pipeline.prototype.error = function(fn, deps) {
if ('number' === typeof fn)
throw new Error('Error handler does not accept numeric argument.')
this.errorHandler = this.pipe(fn, deps).pipes.pop()
return this
}
Pipeline.prototype.debug = function(enabled) {
if ('undefined' === typeof enabled)
return this._debug
this._debug = enabled
return this
}
function getFnName(fn) {
var f = 'function' === typeof fn
var s = f && ((fn.name && ['', fn.name]) || fn.toString().match(/function ([^\(]+)/))
if (f)
return s && s[1] || 'anonymous'
}
| Convert to non-class style. Make `pipes` and `injector` real private.
| lib/pipeline.js | Convert to non-class style. Make `pipes` and `injector` real private. | <ide><path>ib/pipeline.js
<ide> /**
<ide> * Module dependencies
<ide> */
<del>var bind = require('lodash.bind')
<ide> var Pipe = require('./pipe')
<ide> var slice = require('lodash.slice')
<ide> var assign = require('lodash.assign')
<ide> * @param {SuperPipe} [superpipe] Instance of SuperPipe.
<ide> * @return {Pipeline} Instance of Pipeline.
<ide> */
<del>var Pipeline = module.exports = function Pipeline(superpipe) {
<del> var pipeline = assign(function(superpipe, name) {
<del> pipeline.toPipe(superpipe, name)()
<del> }, Pipeline.prototype)
<del>
<del> pipeline.pipes = []
<add>var Pipeline = module.exports = function Pipeline(superpipe, pipes) {
<add> var pipeline = assign(function() {
<add> Pipe.toPipe(pipeline).apply(null, toArray(arguments))
<add> }, pipelineFunctions)
<add>
<add> var _pipes = isArray(pipes) ? slice(pipes) : []
<add> var injector
<add>
<add> /**
<add> * Pipeline reconstruction functions. Define them inline as we want to keep
<add> * `_pipes` private.
<add> */
<add>
<add> /**
<add> * Remove a pipe from the end of pipes and return it.
<add> */
<add> pipeline.pop = function() {
<add> return _pipes.pop()
<add> }
<add>
<add> /**
<add> * Push a pipe into pipeline
<add> * @param {Object} pipe
<add> * @return {Pipeline}
<add> */
<add> pipeline.push = function(pipe) {
<add> _pipes.push(pipe)
<add> return this
<add> }
<add>
<add> pipeline.getPipes = function() {
<add> return slice(_pipes)
<add> }
<add>
<add> pipeline.getInjector = function() {
<add> return injector
<add> }
<add>
<add> pipeline.concat = function(pipeline) {
<add> var pipes = _pipes.concat(pipeline.getPipes())
<add> var concated = new Pipeline(injector, pipes)
<add> concated.debug(this.debug())
<add> concated.errorHandler = this.errorHandler
<add> return concated
<add> }
<add>
<add> /**
<add> * Create a new pipeline using a slice of the original pipeline
<add> * @param {Number} [begin]
<add> * @param {Number} [end]
<add> * @return {Pipeline}
<add> */
<add> pipeline.slice = function(begin, end) {
<add> var sliced = new Pipeline(injector, slice(_pipes, begin, end))
<add> sliced.debug(this.debug())
<add> sliced.errorHandler = this.errorHandler
<add> return sliced
<add> }
<add>
<add> /**
<add> * Connect a pipeline to a instance of Superpipe.
<add> * Then the pipeline will use that superpipe as
<add> * its container of dependencies injection.
<add> *
<add> * @param {Superpipe} superpipe instance of superpipe
<add> * @return {Pipeline} Instance of Pipeline
<add> */
<add> pipeline.connect = function(superpipe) {
<add> if (superpipe && true === superpipe.instanceOfSuperPipe)
<add> injector = superpipe.injector
<add> else if (superpipe && superpipe.getAll && superpipe.get && superpipe.set)
<add> injector = superpipe
<add> else
<add> injector = new Injector()
<add> return pipeline
<add> }
<add>
<add> // Connect pipeline with superpipe (share container of dependency injection)
<ide> pipeline.connect(superpipe)
<ide>
<ide> return pipeline
<ide> Pipeline.toPipe = Pipe.toPipe
<ide>
<ide> /**
<del> * Connect a pipeline to a instance of Superpipe or Injector.
<del> * Then the pipeline will use that superpipe/inector as
<del> * its container of dependencies injection.
<del> *
<del> * @param {Superpipe|Injector} superpipe [description]
<del> * @return {Pipeline} Instance of Pipeline
<del> */
<del>Pipeline.prototype.connect = function(superpipe) {
<del> if (superpipe && superpipe.instanceOfSuperPipe) {
<del> this.superpipe = superpipe
<del> this.injector = superpipe.injector
<del> } else if (superpipe && superpipe instanceof Injector) {
<del> this.injector = superpipe
<del> } else {
<del> this.injector = new Injector()
<del> }
<del>
<del> return this
<del>}
<del>
<del>/**
<del> * Listen to a event emits from the emitter.
<del> *
<del> * @param {EventEmitter} [emitter] The emitter to listen events from.
<del> * The superpipe instance will be used as emitter if only event name is provided.
<del> * @param {String} name Name of the event to listen.
<del> * @return {Pipeline} Instance of this Pipeline.
<del> */
<del>Pipeline.prototype.listenTo = function(emitter, name) {
<del> function listenTo(eventEmitter, eventName, pipeline) {
<del> var listenFn = eventEmitter.on || eventEmitter.addEventListener || eventEmitter.addListener
<del> if ('function' !== typeof listenFn)
<del> throw new Error('emitter has no listening funciton "on, addEventListener or addListener"')
<del> listenFn = bind(listenFn, eventEmitter)
<del> listenFn(eventName, Pipeline.toPipe(pipeline))
<del> }
<del>
<del> if ('string' === typeof emitter) {
<del> var superpipe = this.superpipe
<del> if (name) {
<del> // listenTo('nameOfEmitter', 'some event')
<del> var self = this
<del> var emitterName = emitter
<del> emitter = superpipe.getDep(emitterName)
<del> if (!emitter) {
<del> superpipe.onSetDep(emitterName, function(newEmitter, oldEmitter) {
<del> if (oldEmitter) {
<del> var removeAll = (oldEmitter.removeAllListeners || oldEmitter.off)
<del> removeAll && removeAll.call(oldEmitter, name)
<del> }
<del> listenTo(newEmitter, name, self)
<del> })
<del> return this
<del> }
<del> } else {
<del> // listenTo('some event')
<del> name = emitter
<del> emitter = superpipe
<del> }
<del> }
<del>
<del> listenTo(emitter, name, this)
<del> return this
<del>}
<add> * Pipeline instance functions
<add> */
<add>var pipelineFunctions = {}
<ide>
<ide> /**
<ide> * Put function and its dependencies to the pipeline.
<ide> * @param {Array|String} ...deps String or array of names of dependencies.
<ide> * @return {Pipeline} Instance of this Pipeline.
<ide> */
<del>Pipeline.prototype.pipe = function(fn, deps, supplies) {
<add>pipelineFunctions.pipe = function(fn, deps, supplies) {
<ide> var type = typeof fn
<ide>
<ide> if ('number' === typeof fn) {
<ide> return this.emit(deps, supplies)
<ide> else
<ide> return this.dipe(fn, deps, supplies)
<del> } else if (fn instanceof Pipeline) {
<del> fn = fn.toPipe()
<add> } else if (true === fn.instanceOfPipeline) {
<add> fn = fn.toPipe(this.getInjector())
<ide> }
<ide>
<ide> // save to the pipes array as a pipes unit
<del> var pipe = this.buildPipe(fn, deps, supplies)
<add> var pipe = buildPipe(fn, deps, supplies)
<ide> this.push(pipe)
<ide> return this
<ide> }
<ide>
<del>Pipeline.prototype.emit = function(eventName, deps) {
<add>pipelineFunctions.emit = function(eventName, deps) {
<ide> var self = this
<ide> var fn = function() {
<ide> var args = toArray(arguments)
<ide> args.unshift(eventName)
<del> var emit = self.injector.get('emit')
<add> var emit = self.getInjector().get('emit')
<ide> emit.apply(null, args)
<ide> }
<ide>
<ide> // Build the pipe.
<del> var pipe = this.buildPipe(fn, deps)
<add> var pipe = buildPipe(fn, deps)
<ide> this.push(pipe)
<ide>
<ide> return this
<ide> }
<ide>
<del>Pipeline.prototype.dipe = function(name, deps, supplies) {
<add>pipelineFunctions.dipe = function(name, deps, supplies) {
<ide> var pipe
<ide> var fn = function() {
<ide> var ofn = pipe.ofn
<ide> // Return true to ignore and go next.
<ide> return true
<ide> } else {
<del> throw new Error('Dependency ' + name + ' is not a function or boolean.')
<add> throw new Error('Dependency `' + name + '` is not a function.')
<ide> }
<ide> }
<ide>
<ide> // Build the pipe.
<del> pipe = this.buildPipe(fn, deps, supplies)
<add> pipe = buildPipe(fn, deps, supplies)
<ide>
<ide> if (/^!/.test(name)) {
<ide> pipe.not = true
<ide> return this.push(pipe)
<ide> }
<ide>
<del>Pipeline.prototype.throttle = function(msec) {
<add>pipelineFunctions.throttle = function(msec) {
<ide> // Generate a throttle function and push to pipes
<ide> var timestamp
<ide> return this.push({
<ide> })
<ide> }
<ide>
<del>Pipeline.prototype.push = function(pipe) {
<del> this.pipes.push(pipe)
<add>pipelineFunctions.wait = function(msec) {
<add> // Generate a wait function and push to pipes
<add> return this.push({
<add> fn: function waitFn(next) {
<add> setTimeout(next, msec)
<add> },
<add> deps: ['next']
<add> })
<add>}
<add>
<add>pipelineFunctions.clone = function(superpipe) {
<add> var cloned = this.slice()
<add> if (superpipe)
<add> cloned.connect(superpipe)
<add> return cloned
<add>}
<add>
<add>pipelineFunctions.toPipe = function(superpipe, name) {
<add> var cloned = this.clone(superpipe)
<add> return Pipeline.toPipe(cloned, name)
<add>}
<add>
<add>pipelineFunctions.toCurriedPipe = function(name) {
<add> var sliced = this.slice()
<add> return function(superpipe) {
<add> if (superpipe)
<add> sliced.connect(superpipe)
<add> return sliced.toPipe(null, name)
<add> }
<add>}
<add>
<add>/**
<add> * Set the error handler for this pipeline.
<add> *
<add> * @param {Function|String} fn
<add> * - Function: The pipe function
<add> * - String: Name of function which could be found in dependencies.
<add> * @param {Array|String} deps... String or array of names of dependencies.
<add> * @return {Pipeline} Instance of this Pipeline.
<add> */
<add>pipelineFunctions.error = function(fn, deps) {
<add> if ('number' === typeof fn)
<add> throw new Error('Error handler does not accept numeric argument.')
<add> this.errorHandler = this.pipe(fn, deps).pop()
<ide> return this
<add>}
<add>
<add>pipelineFunctions.debug = function(enabled) {
<add> if ('undefined' === typeof enabled)
<add> return this._debug
<add> this._debug = enabled
<add> return this
<add>}
<add>
<add>/**
<add> * Private functions
<add> */
<add>
<add>function getFnName(fn) {
<add> var f = 'function' === typeof fn
<add> var s = f && ((fn.name && ['', fn.name]) || fn.toString().match(/function ([^\(]+)/))
<add> if (f)
<add> return s && s[1] || 'anonymous'
<ide> }
<ide>
<ide> /**
<ide> * @param {Array|String} deps... String or array of names of dependencies.
<ide> * @return {Object} An object contains dependencies injected function and deps.
<ide> */
<del>Pipeline.prototype.buildPipe = function(fn, deps, supplies) {
<add>function buildPipe(fn, deps, supplies) {
<ide> if ('function' !== typeof fn)
<ide> throw new Error('fn should be a function, got ' + typeof fn)
<ide>
<ide> setDepMap: setDepMap
<ide> }
<ide> }
<del>
<del>Pipeline.prototype.slice = function(begin, end) {
<del> var sliced = new Pipeline(this.superpipe || this.injector)
<del> sliced.debug(this.debug())
<del> sliced.errorHandler = this.errorHandler
<del> sliced.pipes = slice(this.pipes, begin, end)
<del>
<del> return sliced
<del>}
<del>
<del>Pipeline.prototype.clone = function(superpipe) {
<del> var cloned = this.slice()
<del> if (superpipe)
<del> cloned.connect(superpipe)
<del> return cloned
<del>}
<del>
<del>Pipeline.prototype.concat = function(pipeline, begin, end) {
<del> var concated = this.slice()
<del> concated.pipes = concated.pipes.concat(slice(pipeline.pipes, begin, end))
<del>
<del> return concated
<del>}
<del>
<del>Pipeline.prototype.toPipe = function(superpipe, name) {
<del> var pipeline = this.clone(superpipe)
<del> return Pipeline.toPipe(pipeline, slice(pipeline.pipes), name)
<del>}
<del>
<del>Pipeline.prototype.toCurriedPipe = function(name) {
<del> var self = this.slice()
<del> return function(superpipe) {
<del> if (superpipe)
<del> self.connect(superpipe)
<del> return self.toPipe(null, name)
<del> }
<del>}
<del>
<del>/**
<del> * Set the error handler for this pipeline.
<del> *
<del> * @param {Function|String} fn
<del> * - Function: The pipe function
<del> * - String: Name of function which could be found in dependencies.
<del> * @param {Array|String} deps... String or array of names of dependencies.
<del> * @return {Pipeline} Instance of this Pipeline.
<del> */
<del>Pipeline.prototype.error = function(fn, deps) {
<del> if ('number' === typeof fn)
<del> throw new Error('Error handler does not accept numeric argument.')
<del> this.errorHandler = this.pipe(fn, deps).pipes.pop()
<del> return this
<del>}
<del>
<del>Pipeline.prototype.debug = function(enabled) {
<del> if ('undefined' === typeof enabled)
<del> return this._debug
<del> this._debug = enabled
<del> return this
<del>}
<del>
<del>function getFnName(fn) {
<del> var f = 'function' === typeof fn
<del> var s = f && ((fn.name && ['', fn.name]) || fn.toString().match(/function ([^\(]+)/))
<del> if (f)
<del> return s && s[1] || 'anonymous'
<del>} |
|
Java | apache-2.0 | 57662ae21736e3471abe664fa3154ce986920f7b | 0 | ricepanda/rice,ricepanda/rice,ricepanda/rice,ricepanda/rice | /**
* Copyright 2005-2013 The Kuali Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl2.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.rice.krad.data.provider.util;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.kuali.rice.krad.data.DataObjectService;
import org.kuali.rice.krad.data.DataObjectUtils;
import org.kuali.rice.krad.data.DataObjectWrapper;
import org.kuali.rice.krad.data.metadata.DataObjectAttributeRelationship;
import org.kuali.rice.krad.data.metadata.DataObjectCollection;
import org.kuali.rice.krad.data.metadata.DataObjectMetadata;
import org.kuali.rice.krad.data.metadata.DataObjectRelationship;
import org.kuali.rice.krad.data.metadata.MetadataRepository;
/**
* Links parent-child object references
*/
public class ReferenceLinker {
private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(ReferenceLinker.class);
private DataObjectService dataObjectService;
public ReferenceLinker(DataObjectService dataObjectService) {
this.dataObjectService = dataObjectService;
}
protected DataObjectService getDataObjectService() {
return dataObjectService;
}
protected MetadataRepository getMetadataRepository() {
return getDataObjectService().getMetadataRepository();
}
/**
* For each reference object to the parent persistableObject, sets the key
* values for that object. First, if the reference object already has a
* value for the key, the value is left unchanged. Otherwise, for
* non-anonymous keys, the value is taken from the parent object. For
* anonymous keys, all other persistableObjects are checked until a value
* for the key is found.
*/
public void linkObjects(Object persistableObject) {
linkObjectsWithCircularReferenceCheck(persistableObject, new HashSet<Object>());
}
protected void linkObjectsWithCircularReferenceCheck(Object persistableObject, Set<Object> referenceSet) {
if (referenceSet.contains(persistableObject) || DataObjectUtils.isNull(persistableObject)) {
return;
}
if (LOG.isDebugEnabled()) {
LOG.debug("Attempting to link reference objects on " + persistableObject);
}
referenceSet.add(persistableObject);
DataObjectMetadata metadata = getMetadataRepository().getMetadata(persistableObject.getClass());
if (metadata == null) {
LOG.warn("Unable to find metadata for "
+ persistableObject.getClass()
+ " when linking references, skipping");
return;
}
linkRelationships(metadata, persistableObject, referenceSet);
linkCollections(metadata, persistableObject, referenceSet);
}
protected void linkRelationships(DataObjectMetadata metadata, Object persistableObject, Set<Object> referenceSet) {
// iterate through all object references for the persistableObject
List<DataObjectRelationship> objectReferences = metadata.getRelationships();
if (LOG.isDebugEnabled()) {
LOG.debug("Obtained relationships for linking: " + objectReferences);
}
DataObjectWrapper<?> parentWrap = getDataObjectService().wrap(persistableObject);
for (DataObjectRelationship referenceDescriptor : objectReferences) {
// get the actual reference object
String fieldName = referenceDescriptor.getName();
Object childObject = parentWrap.getPropertyValue(fieldName);
boolean updatableRelationship = referenceDescriptor.isSavedWithParent();
if (childObject == null) {
if (LOG.isDebugEnabled()) {
LOG.debug("Referenced object for field " + fieldName + " is null, skipping");
}
continue;
} else if (referenceSet.contains(childObject)) {
if (LOG.isDebugEnabled()) {
LOG.debug("We've previously linked the object assigned to " + fieldName + ", skipping");
}
continue;
}
// recursively link object
linkObjectsWithCircularReferenceCheck(childObject, referenceSet);
// iterate through the keys for the reference object and set
// value
List<DataObjectAttributeRelationship> refAttrs = referenceDescriptor.getAttributeRelationships();
DataObjectMetadata refCld = getMetadataRepository().getMetadata(referenceDescriptor.getRelatedType());
if (refCld == null) {
LOG.warn("No metadata found in repository for referenced object: " + referenceDescriptor);
continue;
}
// List<String> refPkNames = refCld.getPrimaryKeyAttributeNames();
if (LOG.isDebugEnabled()) {
LOG.debug("Linking Referenced fields with parent's FK fields:" + "\n***Refs: " + refAttrs);
}
// Two cases: Updatable Reference (owned child object) or non-updatable (reference data)
// In the former case, we always want to push our keys down into the child, since that
// is what will maintain the relationship.
// In the latter: We assume that the parent object's key fields are correct, only
// setting them from the embedded object *IF* they are null.
// (Since we can't effectively tell which one is the master.)
// Go through all the attribute relationships to copy the key fields as appropriate
DataObjectWrapper<?> childWrap = getDataObjectService().wrap(childObject);
if (updatableRelationship) {
linkUpdatableRelationship(parentWrap, childWrap, refAttrs);
} else { // non-updatable (reference-only) relationship
linkNonUpdatableRelationship(parentWrap, childWrap, refAttrs);
}
}
}
protected void linkUpdatableRelationship(DataObjectWrapper<?> parentWrap, DataObjectWrapper<?> childWrap,
List<DataObjectAttributeRelationship> refAttrs) {
DataObjectMetadata referenceMetadata = childWrap.getMetadata();
List<String> childPkAttributes = referenceMetadata.getPrimaryKeyAttributeNames();
List<String> parentPkAttributes = parentWrap.getMetadata().getPrimaryKeyAttributeNames();
for (DataObjectAttributeRelationship attrRel : refAttrs) {
Object parentPropertyValue = parentWrap.getPropertyValue(attrRel.getParentAttributeName());
Object childPropertyValue = childWrap.getPropertyValueNullSafe(attrRel.getChildAttributeName());
// if fk is set in main object, take value from there
if (parentPropertyValue != null && StringUtils.isNotBlank(parentPropertyValue.toString())) {
// if the child's value is a PK field then we don't want to set it
// *unless* it's null, which we assume is an invalid situation
// and indicates that it has not been set yet
if (childPkAttributes.contains(attrRel.getChildAttributeName()) && childPropertyValue != null
&& StringUtils.isNotBlank(childPropertyValue.toString())) {
if (LOG.isDebugEnabled()) {
LOG.debug("Relationship is to PK value on child object - it may not be changed. Skipping: "
+ childWrap.getWrappedClass().getName() + "." + attrRel.getChildAttributeName());
}
continue;
}
if (LOG.isDebugEnabled()) {
LOG.debug("Parent Object has FK value set (" + attrRel.getParentAttributeName() + "="
+ parentPropertyValue + "): using that");
}
childWrap.setPropertyValue(attrRel.getChildAttributeName(), parentPropertyValue);
} else {
// The FK field on the parent is blank,
// but the child has key values - so set the parent so they link properly
if (childPropertyValue != null && StringUtils.isNotBlank(childPropertyValue.toString())) {
if (parentPkAttributes.contains(attrRel.getParentAttributeName())) {
if (LOG.isDebugEnabled()) {
LOG.debug("Relationship is to PK value on parent object - it may not be changed. Skipping: "
+ parentWrap.getWrappedClass().getName() + "." + attrRel.getParentAttributeName());
}
continue;
}
if (LOG.isDebugEnabled()) {
LOG.debug("Child Object has FK value set (" + attrRel.getChildAttributeName() + "="
+ childPropertyValue + "): using that");
}
parentWrap.setPropertyValue(attrRel.getParentAttributeName(), childPropertyValue);
}
}
}
}
protected void linkNonUpdatableRelationship(DataObjectWrapper<?> parentWrap, DataObjectWrapper<?> childWrap,
List<DataObjectAttributeRelationship> refAttrs) {
for (DataObjectAttributeRelationship attrRel : refAttrs) {
Object parentPropertyValue = parentWrap.getPropertyValueNullSafe(attrRel.getParentAttributeName());
if (parentPropertyValue != null && StringUtils.isNotBlank(parentPropertyValue.toString())) {
// Skip this property, it has already been set on the parent object
continue;
}
Object childPropertyValue = childWrap.getPropertyValueNullSafe(attrRel.getChildAttributeName());
// don't bother setting parent if it's not set itself
if (childPropertyValue == null || StringUtils.isBlank(childPropertyValue.toString())) {
continue;
}
if (LOG.isDebugEnabled()) {
LOG.debug("Child Object has FK value set (" + attrRel.getChildAttributeName() + "="
+ childPropertyValue + "): using that");
}
parentWrap.setPropertyValue(attrRel.getParentAttributeName(), childPropertyValue);
}
}
protected void linkCollections(DataObjectMetadata metadata, Object persistableObject, Set<Object> referenceSet) {
List<DataObjectCollection> collections = metadata.getCollections();
if (LOG.isDebugEnabled()) {
LOG.debug("Obtained collections for linking: " + collections);
}
for (DataObjectCollection collectionMetadata : collections) {
// We only process collections if they are being saved with the parent
if (!collectionMetadata.isSavedWithParent()) {
continue;
}
// get the actual reference object
String fieldName = collectionMetadata.getName();
DataObjectWrapper<?> parentObjectWrapper = getDataObjectService().wrap(persistableObject);
Collection<?> collection = (Collection<?>) parentObjectWrapper.getPropertyValue(fieldName);
if (collection == null) {
if (LOG.isDebugEnabled()) {
LOG.debug("Referenced collection for field " + fieldName + " is null, skipping");
}
continue;
} else if (referenceSet.contains(collection)) {
if (LOG.isDebugEnabled()) {
LOG.debug("We've previously linked the object assigned to " + fieldName + ", skipping");
}
continue;
}
List<DataObjectAttributeRelationship> collectionAttributeRelationships = collectionMetadata
.getAttributeRelationships();
// Need to iterate through the collection, setting FK values as needed and telling each child object to link
// itself
for (Object collectionItem : collection) {
// recursively link object
linkObjectsWithCircularReferenceCheck(collectionItem, referenceSet);
DataObjectWrapper<Object> collItemWrapper = getDataObjectService().wrap(collectionItem);
// Now - go through the keys relating the parent object to each child and set them so that they are
// linked properly
for (DataObjectAttributeRelationship rel : collectionAttributeRelationships) {
collItemWrapper.setPropertyValue(rel.getChildAttributeName(),
parentObjectWrapper.getPropertyValueNullSafe(rel.getParentAttributeName()));
}
}
}
}
}
| rice-framework/krad-data/src/main/java/org/kuali/rice/krad/data/provider/util/ReferenceLinker.java | /**
* Copyright 2005-2013 The Kuali Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl2.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.rice.krad.data.provider.util;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.kuali.rice.krad.data.DataObjectService;
import org.kuali.rice.krad.data.DataObjectUtils;
import org.kuali.rice.krad.data.DataObjectWrapper;
import org.kuali.rice.krad.data.metadata.DataObjectAttributeRelationship;
import org.kuali.rice.krad.data.metadata.DataObjectCollection;
import org.kuali.rice.krad.data.metadata.DataObjectMetadata;
import org.kuali.rice.krad.data.metadata.DataObjectRelationship;
import org.kuali.rice.krad.data.metadata.MetadataRepository;
/**
* Links parent-child object references
*/
public class ReferenceLinker {
private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(ReferenceLinker.class);
private DataObjectService dataObjectService;
public ReferenceLinker(DataObjectService dataObjectService) {
this.dataObjectService = dataObjectService;
}
protected DataObjectService getDataObjectService() {
return dataObjectService;
}
protected MetadataRepository getMetadataRepository() {
return getDataObjectService().getMetadataRepository();
}
/**
* For each reference object to the parent persistableObject, sets the key
* values for that object. First, if the reference object already has a
* value for the key, the value is left unchanged. Otherwise, for
* non-anonymous keys, the value is taken from the parent object. For
* anonymous keys, all other persistableObjects are checked until a value
* for the key is found.
*/
public void linkObjects(Object persistableObject) {
linkObjectsWithCircularReferenceCheck(persistableObject, new HashSet<Object>());
}
protected void linkObjectsWithCircularReferenceCheck(Object persistableObject, Set<Object> referenceSet) {
if (referenceSet.contains(persistableObject) || DataObjectUtils.isNull(persistableObject)) {
return;
}
if (LOG.isDebugEnabled()) {
LOG.debug("Attempting to link reference objects on " + persistableObject);
}
referenceSet.add(persistableObject);
DataObjectMetadata metadata = getMetadataRepository().getMetadata(persistableObject.getClass());
if (metadata == null) {
LOG.warn("Unable to find metadata for "
+ persistableObject.getClass()
+ " when linking references, skipping");
return;
}
linkRelationships(metadata, persistableObject, referenceSet);
linkCollections(metadata, persistableObject, referenceSet);
}
protected void linkRelationships(DataObjectMetadata metadata, Object persistableObject, Set<Object> referenceSet) {
// iterate through all object references for the persistableObject
List<DataObjectRelationship> objectReferences = metadata.getRelationships();
if (LOG.isDebugEnabled()) {
LOG.debug("Obtained relationships for linking: " + objectReferences);
}
DataObjectWrapper<?> wrap = getDataObjectService().wrap(persistableObject);
for (DataObjectRelationship referenceDescriptor : objectReferences) {
// get the actual reference object
String fieldName = referenceDescriptor.getName();
Object referenceObject = wrap.getPropertyValue(fieldName);
boolean updatableRelationship = referenceDescriptor.isSavedWithParent();
if (referenceObject == null) {
if (LOG.isDebugEnabled()) {
LOG.debug("Referenced object for field " + fieldName + " is null, skipping");
}
continue;
} else if (referenceSet.contains(referenceObject)) {
if (LOG.isDebugEnabled()) {
LOG.debug("We've previously linked the object assigned to " + fieldName + ", skipping");
}
continue;
}
// recursively link object
linkObjectsWithCircularReferenceCheck(referenceObject, referenceSet);
// iterate through the keys for the reference object and set
// value
List<DataObjectAttributeRelationship> refAttrs = referenceDescriptor.getAttributeRelationships();
DataObjectMetadata refCld = getMetadataRepository().getMetadata(referenceDescriptor.getRelatedType());
if (refCld == null) {
LOG.warn("No metadata found in repository for referenced object: " + referenceDescriptor);
continue;
}
// List<String> refPkNames = refCld.getPrimaryKeyAttributeNames();
if (LOG.isDebugEnabled()) {
LOG.debug("Linking Referenced fields with parent's FK fields:" + "\n***Refs: " + refAttrs);
}
// Two cases: Updatable Reference (owned child object) or non-updatable (reference data)
// In the former case, we always want to push our keys down into the child, since that
// is what will maintain the relationship.
// In the latter: We assume that the parent object's key fields are correct, only
// setting them from the embedded object *IF* they are null.
// (Since we can't effectively tell which one is the master.)
// Go through all the attribute relationships to copy the key fields as appropriate
DataObjectWrapper<?> referenceWrap = getDataObjectService().wrap(referenceObject);
if (updatableRelationship) {
DataObjectMetadata referenceMetadata = getMetadataRepository().getMetadata(referenceDescriptor.getRelatedType());
List<String> childPkAttributes = referenceMetadata.getPrimaryKeyAttributeNames();
List<String> parentPkAttributes = metadata.getPrimaryKeyAttributeNames();
for (DataObjectAttributeRelationship attrRel : refAttrs) {
Object parentPropertyValue = wrap.getPropertyValue(attrRel.getParentAttributeName());
Object childPropertyValue = referenceWrap.getPropertyValueNullSafe(attrRel.getChildAttributeName());
// if fk is set in main object, take value from there
if (parentPropertyValue != null && StringUtils.isNotBlank(parentPropertyValue.toString())) {
// if the child's value is a PK field then we don't want to set it
// *unless* it's null, which we assume is an invalid situation
// and indicates that it has not been set yet
if (childPkAttributes.contains(attrRel.getChildAttributeName()) && childPropertyValue != null
&& StringUtils.isNotBlank(childPropertyValue.toString())) {
if (LOG.isDebugEnabled()) {
LOG.debug("Relationship is to PK value on child object - it may not be changed. Skipping: "
+ referenceDescriptor.getClass().getName()
+ "."
+ referenceDescriptor.getName() + "." + attrRel.getChildAttributeName());
}
continue;
}
if (LOG.isDebugEnabled()) {
LOG.debug("Parent Object has FK value set (" + attrRel.getParentAttributeName() + "="
+ parentPropertyValue + "): using that");
}
referenceWrap.setPropertyValue(attrRel.getChildAttributeName(), parentPropertyValue);
} else {
// The FK field on the parent is blank,
// but the child has key values - so set the parent so they link properly
if (childPropertyValue != null && StringUtils.isNotBlank(childPropertyValue.toString())) {
if (parentPkAttributes.contains(attrRel.getParentAttributeName())) {
if (LOG.isDebugEnabled()) {
LOG.debug("Relationship is to PK value on parent object - it may not be changed. Skipping: "
+ metadata.getType().getName() + "." + attrRel.getParentAttributeName());
}
continue;
}
if (LOG.isDebugEnabled()) {
LOG.debug("Child Object has FK value set (" + attrRel.getChildAttributeName() + "="
+ childPropertyValue + "): using that");
}
wrap.setPropertyValue(attrRel.getParentAttributeName(), childPropertyValue);
}
}
}
} else { // non-updatable (reference-only) relationship
for (DataObjectAttributeRelationship attrRel : refAttrs) {
Object parentPropertyValue = wrap.getPropertyValueNullSafe(attrRel.getParentAttributeName());
if (parentPropertyValue != null && StringUtils.isNotBlank(parentPropertyValue.toString())) {
// Skip this property, it has already been set on the parent object
continue;
}
Object childPropertyValue = referenceWrap.getPropertyValueNullSafe(attrRel.getChildAttributeName());
// don't bother setting parent if it's not set itself
if (childPropertyValue == null || StringUtils.isBlank(childPropertyValue.toString())) {
continue;
}
if (LOG.isDebugEnabled()) {
LOG.debug("Child Object has FK value set (" + attrRel.getChildAttributeName() + "="
+ childPropertyValue + "): using that");
}
wrap.setPropertyValue(attrRel.getParentAttributeName(), childPropertyValue);
}
}
}
}
protected void linkCollections(DataObjectMetadata metadata, Object persistableObject, Set<Object> referenceSet) {
List<DataObjectCollection> collections = metadata.getCollections();
if (LOG.isDebugEnabled()) {
LOG.debug("Obtained collections for linking: " + collections);
}
for (DataObjectCollection collectionMetadata : collections) {
// We only process collections if they are being saved with the parent
if (!collectionMetadata.isSavedWithParent()) {
continue;
}
// get the actual reference object
String fieldName = collectionMetadata.getName();
DataObjectWrapper<?> parentObjectWrapper = getDataObjectService().wrap(persistableObject);
Collection<?> collection = (Collection<?>) parentObjectWrapper.getPropertyValue(fieldName);
if (collection == null) {
if (LOG.isDebugEnabled()) {
LOG.debug("Referenced collection for field " + fieldName + " is null, skipping");
}
continue;
} else if (referenceSet.contains(collection)) {
if (LOG.isDebugEnabled()) {
LOG.debug("We've previously linked the object assigned to " + fieldName + ", skipping");
}
continue;
}
List<DataObjectAttributeRelationship> collectionAttributeRelationships = collectionMetadata
.getAttributeRelationships();
// Need to iterate through the collection, setting FK values as needed and telling each child object to link
// itself
for (Object collectionItem : collection) {
// recursively link object
linkObjectsWithCircularReferenceCheck(collectionItem, referenceSet);
DataObjectWrapper<Object> collItemWrapper = getDataObjectService().wrap(collectionItem);
// Now - go through the keys relating the parent object to each child and set them so that they are
// linked properly
for (DataObjectAttributeRelationship rel : collectionAttributeRelationships) {
collItemWrapper.setPropertyValue(rel.getChildAttributeName(),
parentObjectWrapper.getPropertyValueNullSafe(rel.getParentAttributeName()));
}
}
}
}
}
| KULRICE-9649 / KULRICE-9100 : minor refactoring due to new length of logic in method
git-svn-id: 2a5d2b5a02908a0c4ba7967b726d8c4198d1b9ed@41316 7a7aa7f6-c479-11dc-97e2-85a2497f191d
| rice-framework/krad-data/src/main/java/org/kuali/rice/krad/data/provider/util/ReferenceLinker.java | KULRICE-9649 / KULRICE-9100 : minor refactoring due to new length of logic in method | <ide><path>ice-framework/krad-data/src/main/java/org/kuali/rice/krad/data/provider/util/ReferenceLinker.java
<ide> if (LOG.isDebugEnabled()) {
<ide> LOG.debug("Obtained relationships for linking: " + objectReferences);
<ide> }
<del> DataObjectWrapper<?> wrap = getDataObjectService().wrap(persistableObject);
<add> DataObjectWrapper<?> parentWrap = getDataObjectService().wrap(persistableObject);
<ide> for (DataObjectRelationship referenceDescriptor : objectReferences) {
<ide> // get the actual reference object
<ide> String fieldName = referenceDescriptor.getName();
<del> Object referenceObject = wrap.getPropertyValue(fieldName);
<add> Object childObject = parentWrap.getPropertyValue(fieldName);
<ide> boolean updatableRelationship = referenceDescriptor.isSavedWithParent();
<del> if (referenceObject == null) {
<add> if (childObject == null) {
<ide> if (LOG.isDebugEnabled()) {
<ide> LOG.debug("Referenced object for field " + fieldName + " is null, skipping");
<ide> }
<ide> continue;
<del> } else if (referenceSet.contains(referenceObject)) {
<add> } else if (referenceSet.contains(childObject)) {
<ide> if (LOG.isDebugEnabled()) {
<ide> LOG.debug("We've previously linked the object assigned to " + fieldName + ", skipping");
<ide> }
<ide> }
<ide>
<ide> // recursively link object
<del> linkObjectsWithCircularReferenceCheck(referenceObject, referenceSet);
<add> linkObjectsWithCircularReferenceCheck(childObject, referenceSet);
<ide>
<ide> // iterate through the keys for the reference object and set
<ide> // value
<ide> // (Since we can't effectively tell which one is the master.)
<ide>
<ide> // Go through all the attribute relationships to copy the key fields as appropriate
<del> DataObjectWrapper<?> referenceWrap = getDataObjectService().wrap(referenceObject);
<add> DataObjectWrapper<?> childWrap = getDataObjectService().wrap(childObject);
<ide> if (updatableRelationship) {
<del> DataObjectMetadata referenceMetadata = getMetadataRepository().getMetadata(referenceDescriptor.getRelatedType());
<del> List<String> childPkAttributes = referenceMetadata.getPrimaryKeyAttributeNames();
<del> List<String> parentPkAttributes = metadata.getPrimaryKeyAttributeNames();
<del> for (DataObjectAttributeRelationship attrRel : refAttrs) {
<del> Object parentPropertyValue = wrap.getPropertyValue(attrRel.getParentAttributeName());
<del> Object childPropertyValue = referenceWrap.getPropertyValueNullSafe(attrRel.getChildAttributeName());
<del>
<del> // if fk is set in main object, take value from there
<del> if (parentPropertyValue != null && StringUtils.isNotBlank(parentPropertyValue.toString())) {
<del> // if the child's value is a PK field then we don't want to set it
<del> // *unless* it's null, which we assume is an invalid situation
<del> // and indicates that it has not been set yet
<del> if (childPkAttributes.contains(attrRel.getChildAttributeName()) && childPropertyValue != null
<del> && StringUtils.isNotBlank(childPropertyValue.toString())) {
<del> if (LOG.isDebugEnabled()) {
<del> LOG.debug("Relationship is to PK value on child object - it may not be changed. Skipping: "
<del> + referenceDescriptor.getClass().getName()
<del> + "."
<del> + referenceDescriptor.getName() + "." + attrRel.getChildAttributeName());
<del> }
<del> continue;
<add> linkUpdatableRelationship(parentWrap, childWrap, refAttrs);
<add> } else { // non-updatable (reference-only) relationship
<add> linkNonUpdatableRelationship(parentWrap, childWrap, refAttrs);
<add> }
<add> }
<add> }
<add>
<add> protected void linkUpdatableRelationship(DataObjectWrapper<?> parentWrap, DataObjectWrapper<?> childWrap,
<add> List<DataObjectAttributeRelationship> refAttrs) {
<add> DataObjectMetadata referenceMetadata = childWrap.getMetadata();
<add> List<String> childPkAttributes = referenceMetadata.getPrimaryKeyAttributeNames();
<add> List<String> parentPkAttributes = parentWrap.getMetadata().getPrimaryKeyAttributeNames();
<add> for (DataObjectAttributeRelationship attrRel : refAttrs) {
<add> Object parentPropertyValue = parentWrap.getPropertyValue(attrRel.getParentAttributeName());
<add> Object childPropertyValue = childWrap.getPropertyValueNullSafe(attrRel.getChildAttributeName());
<add>
<add> // if fk is set in main object, take value from there
<add> if (parentPropertyValue != null && StringUtils.isNotBlank(parentPropertyValue.toString())) {
<add> // if the child's value is a PK field then we don't want to set it
<add> // *unless* it's null, which we assume is an invalid situation
<add> // and indicates that it has not been set yet
<add> if (childPkAttributes.contains(attrRel.getChildAttributeName()) && childPropertyValue != null
<add> && StringUtils.isNotBlank(childPropertyValue.toString())) {
<add> if (LOG.isDebugEnabled()) {
<add> LOG.debug("Relationship is to PK value on child object - it may not be changed. Skipping: "
<add> + childWrap.getWrappedClass().getName() + "." + attrRel.getChildAttributeName());
<add> }
<add> continue;
<add> }
<add> if (LOG.isDebugEnabled()) {
<add> LOG.debug("Parent Object has FK value set (" + attrRel.getParentAttributeName() + "="
<add> + parentPropertyValue + "): using that");
<add> }
<add> childWrap.setPropertyValue(attrRel.getChildAttributeName(), parentPropertyValue);
<add> } else {
<add> // The FK field on the parent is blank,
<add> // but the child has key values - so set the parent so they link properly
<add> if (childPropertyValue != null && StringUtils.isNotBlank(childPropertyValue.toString())) {
<add> if (parentPkAttributes.contains(attrRel.getParentAttributeName())) {
<add> if (LOG.isDebugEnabled()) {
<add> LOG.debug("Relationship is to PK value on parent object - it may not be changed. Skipping: "
<add> + parentWrap.getWrappedClass().getName() + "." + attrRel.getParentAttributeName());
<ide> }
<del> if (LOG.isDebugEnabled()) {
<del> LOG.debug("Parent Object has FK value set (" + attrRel.getParentAttributeName() + "="
<del> + parentPropertyValue + "): using that");
<del> }
<del> referenceWrap.setPropertyValue(attrRel.getChildAttributeName(), parentPropertyValue);
<del> } else {
<del> // The FK field on the parent is blank,
<del> // but the child has key values - so set the parent so they link properly
<del> if (childPropertyValue != null && StringUtils.isNotBlank(childPropertyValue.toString())) {
<del> if (parentPkAttributes.contains(attrRel.getParentAttributeName())) {
<del> if (LOG.isDebugEnabled()) {
<del> LOG.debug("Relationship is to PK value on parent object - it may not be changed. Skipping: "
<del> + metadata.getType().getName() + "." + attrRel.getParentAttributeName());
<del> }
<del> continue;
<del> }
<del> if (LOG.isDebugEnabled()) {
<del> LOG.debug("Child Object has FK value set (" + attrRel.getChildAttributeName() + "="
<del> + childPropertyValue + "): using that");
<del> }
<del> wrap.setPropertyValue(attrRel.getParentAttributeName(), childPropertyValue);
<del> }
<del> }
<del> }
<del> } else { // non-updatable (reference-only) relationship
<del> for (DataObjectAttributeRelationship attrRel : refAttrs) {
<del> Object parentPropertyValue = wrap.getPropertyValueNullSafe(attrRel.getParentAttributeName());
<del> if (parentPropertyValue != null && StringUtils.isNotBlank(parentPropertyValue.toString())) {
<del> // Skip this property, it has already been set on the parent object
<del> continue;
<del> }
<del> Object childPropertyValue = referenceWrap.getPropertyValueNullSafe(attrRel.getChildAttributeName());
<del> // don't bother setting parent if it's not set itself
<del> if (childPropertyValue == null || StringUtils.isBlank(childPropertyValue.toString())) {
<ide> continue;
<ide> }
<ide> if (LOG.isDebugEnabled()) {
<ide> LOG.debug("Child Object has FK value set (" + attrRel.getChildAttributeName() + "="
<ide> + childPropertyValue + "): using that");
<del> }
<del> wrap.setPropertyValue(attrRel.getParentAttributeName(), childPropertyValue);
<del> }
<del> }
<add> }
<add> parentWrap.setPropertyValue(attrRel.getParentAttributeName(), childPropertyValue);
<add> }
<add> }
<add> }
<add> }
<add>
<add> protected void linkNonUpdatableRelationship(DataObjectWrapper<?> parentWrap, DataObjectWrapper<?> childWrap,
<add> List<DataObjectAttributeRelationship> refAttrs) {
<add> for (DataObjectAttributeRelationship attrRel : refAttrs) {
<add> Object parentPropertyValue = parentWrap.getPropertyValueNullSafe(attrRel.getParentAttributeName());
<add> if (parentPropertyValue != null && StringUtils.isNotBlank(parentPropertyValue.toString())) {
<add> // Skip this property, it has already been set on the parent object
<add> continue;
<add> }
<add> Object childPropertyValue = childWrap.getPropertyValueNullSafe(attrRel.getChildAttributeName());
<add> // don't bother setting parent if it's not set itself
<add> if (childPropertyValue == null || StringUtils.isBlank(childPropertyValue.toString())) {
<add> continue;
<add> }
<add> if (LOG.isDebugEnabled()) {
<add> LOG.debug("Child Object has FK value set (" + attrRel.getChildAttributeName() + "="
<add> + childPropertyValue + "): using that");
<add> }
<add> parentWrap.setPropertyValue(attrRel.getParentAttributeName(), childPropertyValue);
<ide> }
<ide> }
<ide> |
|
Java | agpl-3.0 | 8a761b76e3b6933a3aa515a7481304d3b4c48a19 | 0 | akuz/akuz-java,akuz/akuz-java | package me.akuz.qf.data.imprt;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.TimeZone;
import java.util.regex.Pattern;
import me.akuz.core.DateUtils;
import me.akuz.core.FileUtils;
import me.akuz.core.Pair;
import me.akuz.core.PairComparator;
import me.akuz.core.SortOrder;
import me.akuz.qf.data.DateVolumeClose;
public final class YahooData {
private static final Pattern _csvExtensionPattern = Pattern.compile("\\.csv$", Pattern.CASE_INSENSITIVE);
public final static List<Pair<Double, Date>> loadClosePrices(String fileName, TimeZone timeZone, int closingHour) throws IOException, ParseException {
List<Pair<Double, Date>> prices = new ArrayList<Pair<Double,Date>>();
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
fmt.setTimeZone(timeZone);
List<String> lines = FileUtils.readEntireFileLines(fileName);
for (int i=1; i<lines.size(); i++) {
String line = lines.get(i).trim();
if (line.length() > 0) {
//2012-06-08,571.60,580.58,569.00,580.32,12395100,580.32
String[] parts = line.split(",");
if (parts.length != 7) {
throw new IOException("Incorrect format in line #" + (i+1) + " of file " + fileName);
}
Date timeZoneDate = fmt.parse(parts[0]);
Date priceDateTime = DateUtils.addHours(timeZoneDate, closingHour);
Double price = Double.parseDouble(parts[6]);
prices.add(new Pair<Double, Date>(price, priceDateTime));
}
}
if (prices.size() > 1) {
Collections.sort(prices, new PairComparator<Double, Date>(SortOrder.Asc));
}
return prices;
}
public final static List<DateVolumeClose> loadFileDateVolumeClose(String fileName, TimeZone timeZone, int closingHour) throws IOException, ParseException {
List<DateVolumeClose> list = new ArrayList<>();
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
fmt.setTimeZone(timeZone);
Scanner scanner = FileUtils.openScanner(fileName, "UTF-8");
try {
int lineNumber = 0;
while (scanner.hasNextLine()) {
lineNumber += 1;
final String line = scanner.nextLine().trim();
// first line is header
if (lineNumber == 1) {
continue;
}
if (line.length() > 0) {
//2012-06-08,571.60,580.58,569.00,580.32,12395100,580.32
String[] parts = line.split(",");
if (parts.length != 7) {
throw new IOException("Incorrect format in line #" + (lineNumber) + " of file " + fileName);
}
final Date timeZoneDate = fmt.parse(parts[0]);
final Date priceDateTime = DateUtils.addHours(timeZoneDate, closingHour);
final Double open = Double.parseDouble(parts[1]);
final Double close = Double.parseDouble(parts[4]);
final Integer volume = Integer.parseInt(parts[5]);
final Double adjClose = Double.parseDouble(parts[6]);
final Double adjOpen = open / close * adjClose;
final Integer adjVolume = (Integer)(int)(volume / adjClose * close);
list.add(new DateVolumeClose(priceDateTime, adjVolume, adjOpen)); // FIXME
}
}
} finally {
scanner.close();
}
if (list.size() > 1) {
Collections.sort(list);
}
return list;
}
public static final Map<String, List<DateVolumeClose>> loadDirDateVolumeClose(String dirPath, Set<String> ignoreTickers, TimeZone timeZone, int closingHour) throws IOException, ParseException {
Map<String, List<DateVolumeClose>> map = new HashMap<>();
List<File> files = FileUtils.getFiles(dirPath);
for (int i=0; i<files.size(); i++) {
File file = files.get(i);
String ticker = _csvExtensionPattern.matcher(file.getName()).replaceAll("");
if (ticker.startsWith(".")) {
continue;
}
if (ignoreTickers != null && ignoreTickers.contains(ticker)) {
continue;
}
if (map.containsKey(ticker)) {
throw new IOException("Duplicate data file for ticker " + ticker + " in dir " + dirPath);
}
List<DateVolumeClose> list = loadFileDateVolumeClose(file.getAbsolutePath(), timeZone, closingHour);
map.put(ticker, list);
}
return map;
}
}
| src/me/akuz/qf/data/imprt/YahooData.java | package me.akuz.qf.data.imprt;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.TimeZone;
import java.util.regex.Pattern;
import me.akuz.core.DateUtils;
import me.akuz.core.FileUtils;
import me.akuz.core.Pair;
import me.akuz.core.PairComparator;
import me.akuz.core.SortOrder;
import me.akuz.qf.data.DateVolumeClose;
public final class YahooData {
private static final Pattern _csvExtensionPattern = Pattern.compile("\\.csv$", Pattern.CASE_INSENSITIVE);
public final static List<Pair<Double, Date>> loadClosePrices(String fileName, TimeZone timeZone, int closingHour) throws IOException, ParseException {
List<Pair<Double, Date>> prices = new ArrayList<Pair<Double,Date>>();
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
fmt.setTimeZone(timeZone);
List<String> lines = FileUtils.readEntireFileLines(fileName);
for (int i=1; i<lines.size(); i++) {
String line = lines.get(i).trim();
if (line.length() > 0) {
//2012-06-08,571.60,580.58,569.00,580.32,12395100,580.32
String[] parts = line.split(",");
if (parts.length != 7) {
throw new IOException("Incorrect format in line #" + (i+1) + " of file " + fileName);
}
Date timeZoneDate = fmt.parse(parts[0]);
Date priceDateTime = DateUtils.addHours(timeZoneDate, closingHour);
Double price = Double.parseDouble(parts[6]);
prices.add(new Pair<Double, Date>(price, priceDateTime));
}
}
if (prices.size() > 1) {
Collections.sort(prices, new PairComparator<Double, Date>(SortOrder.Asc));
}
return prices;
}
public final static List<DateVolumeClose> loadFileDateVolumeClose(String fileName, TimeZone timeZone, int closingHour) throws IOException, ParseException {
List<DateVolumeClose> list = new ArrayList<>();
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
fmt.setTimeZone(timeZone);
Scanner scanner = FileUtils.openScanner(fileName, "UTF-8");
try {
int lineNumber = 0;
while (scanner.hasNextLine()) {
lineNumber += 1;
final String line = scanner.nextLine().trim();
// first line is header
if (lineNumber == 1) {
continue;
}
if (line.length() > 0) {
//2012-06-08,571.60,580.58,569.00,580.32,12395100,580.32
String[] parts = line.split(",");
if (parts.length != 7) {
throw new IOException("Incorrect format in line #" + (lineNumber) + " of file " + fileName);
}
final Date timeZoneDate = fmt.parse(parts[0]);
final Date priceDateTime = DateUtils.addHours(timeZoneDate, closingHour);
final Double close = Double.parseDouble(parts[4]);
final Integer volume = Integer.parseInt(parts[5]);
final Double adjClose = Double.parseDouble(parts[6]);
final Integer adjVolume = (Integer)(int)(volume / adjClose * close);
list.add(new DateVolumeClose(priceDateTime, adjVolume, adjClose));
}
}
} finally {
scanner.close();
}
if (list.size() > 1) {
Collections.sort(list);
}
return list;
}
public static final Map<String, List<DateVolumeClose>> loadDirDateVolumeClose(String dirPath, Set<String> ignoreTickers, TimeZone timeZone, int closingHour) throws IOException, ParseException {
Map<String, List<DateVolumeClose>> map = new HashMap<>();
List<File> files = FileUtils.getFiles(dirPath);
for (int i=0; i<files.size(); i++) {
File file = files.get(i);
String ticker = _csvExtensionPattern.matcher(file.getName()).replaceAll("");
if (ticker.startsWith(".")) {
continue;
}
if (ignoreTickers != null && ignoreTickers.contains(ticker)) {
continue;
}
if (map.containsKey(ticker)) {
throw new IOException("Duplicate data file for ticker " + ticker + " in dir " + dirPath);
}
List<DateVolumeClose> list = loadFileDateVolumeClose(file.getAbsolutePath(), timeZone, closingHour);
map.put(ticker, list);
}
return map;
}
}
| Temporarily loading open instead of close price... | src/me/akuz/qf/data/imprt/YahooData.java | Temporarily loading open instead of close price... | <ide><path>rc/me/akuz/qf/data/imprt/YahooData.java
<ide> }
<ide> final Date timeZoneDate = fmt.parse(parts[0]);
<ide> final Date priceDateTime = DateUtils.addHours(timeZoneDate, closingHour);
<add> final Double open = Double.parseDouble(parts[1]);
<ide> final Double close = Double.parseDouble(parts[4]);
<ide> final Integer volume = Integer.parseInt(parts[5]);
<ide> final Double adjClose = Double.parseDouble(parts[6]);
<add> final Double adjOpen = open / close * adjClose;
<ide> final Integer adjVolume = (Integer)(int)(volume / adjClose * close);
<del> list.add(new DateVolumeClose(priceDateTime, adjVolume, adjClose));
<add> list.add(new DateVolumeClose(priceDateTime, adjVolume, adjOpen)); // FIXME
<ide> }
<ide> }
<ide> } finally { |
|
Java | mit | e108fee346e851a89f38c7acf132913cd7fcc3b6 | 0 | uq-eresearch/dataspace,uq-eresearch/dataspace,uq-eresearch/dataspace,uq-eresearch/dataspace | package net.metadata.dataspace.data.model.version;
import net.metadata.dataspace.data.model.Record;
import net.metadata.dataspace.data.model.context.Publication;
import net.metadata.dataspace.data.model.context.Subject;
import net.metadata.dataspace.data.model.record.Activity;
import net.metadata.dataspace.data.model.record.Agent;
import net.metadata.dataspace.data.model.record.Collection;
import net.metadata.dataspace.data.model.record.Service;
import net.metadata.dataspace.data.model.types.CollectionType;
import org.hibernate.annotations.CollectionOfElements;
import org.hibernate.validator.NotNull;
import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;
import static javax.persistence.EnumType.STRING;
/**
* Author: alabri
* Date: 02/11/2010
* Time: 5:16:30 PM
*/
@Entity
public class CollectionVersion extends AbstractVersionEntity {
private static final long serialVersionUID = 1L;
@ManyToOne
private Collection parent;
@NotNull
@Enumerated(STRING)
private CollectionType type;
@NotNull
@Column(length = 4096)
private String rights;
@CollectionOfElements(fetch = FetchType.LAZY)
@Column(name = "element", length = 4096)
private Set<String> accessRights = new HashSet<String>();
@Column(length = 4096)
private String license;
@CollectionOfElements(fetch = FetchType.LAZY)
private Set<String> temporals = new HashSet<String>();
@CollectionOfElements(fetch = FetchType.LAZY)
private Set<String> geoRssPoints = new HashSet<String>();
@CollectionOfElements(fetch = FetchType.LAZY)
@Column(name = "element", length = 4096)
private Set<String> geoRssPolygons = new HashSet<String>();
@CollectionOfElements(fetch = FetchType.LAZY)
private Set<String> geoRssFeatureNames = new HashSet<String>();
@CollectionOfElements(fetch = FetchType.LAZY)
private Set<String> keywords = new HashSet<String>();
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinTable(name = "collections_creators")
private Set<Agent> creators = new HashSet<Agent>();
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinTable(name = "collection_publishers")
private Set<Agent> publishers = new HashSet<Agent>();
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinTable(name = "collections_is_output_of")
private Set<Activity> isOutputOf = new HashSet<Activity>();
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinTable(name = "collections_is_accessed_via")
private Set<Service> isAccessedVia = new HashSet<Service>();
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinTable(name = "collections_subjects")
private Set<Subject> subjects = new HashSet<Subject>();
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinTable(name = "collections_publications")
private Set<Publication> isReferencedBy = new HashSet<Publication>();
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinTable(name = "collections_relations")
private Set<Collection> relations = new HashSet<Collection>();
@CollectionOfElements(fetch = FetchType.LAZY)
private Set<String> alternatives = new HashSet<String>();
@CollectionOfElements(fetch = FetchType.LAZY)
private Set<String> pages = new HashSet<String>();
public CollectionVersion() {
}
@Override
public Collection getParent() {
return parent;
}
@Override
public void setParent(Record parent) {
this.parent = (Collection) parent;
}
public Set<Subject> getSubjects() {
return subjects;
}
public void setSubjects(Set<Subject> subjects) {
this.subjects = subjects;
}
public Set<Agent> getCreators() {
return creators;
}
public void setCreators(Set<Agent> creators) {
this.creators = creators;
}
public Set<Activity> getOutputOf() {
return isOutputOf;
}
public void setOutputOf(Set<Activity> outputOf) {
isOutputOf = outputOf;
}
public Set<Service> getAccessedVia() {
return isAccessedVia;
}
public void setAccessedVia(Set<Service> accessedVia) {
this.isAccessedVia = accessedVia;
}
public CollectionType getType() {
return type;
}
public void setType(CollectionType type) {
this.type = type;
}
public Set<Agent> getPublishers() {
return publishers;
}
public void setPublishers(Set<Agent> publishers) {
this.publishers = publishers;
}
public String getRights() {
return rights;
}
public void setRights(String rights) {
this.rights = rights;
}
public String getLicense() {
return license;
}
public void setLicense(String license) {
this.license = license;
}
public Set<Publication> getReferencedBy() {
return isReferencedBy;
}
public void setReferencedBy(Set<Publication> referencedBy) {
isReferencedBy = referencedBy;
}
public Set<Collection> getRelations() {
return relations;
}
public void setRelations(Set<Collection> relations) {
this.relations = relations;
}
public Set<String> getAccessRights() {
return accessRights;
}
public void setAccessRights(Set<String> accessRights) {
this.accessRights = accessRights;
}
public Set<String> getTemporals() {
return temporals;
}
public void setTemporals(Set<String> temporals) {
this.temporals = temporals;
}
public Set<String> getGeoRssPoints() {
return geoRssPoints;
}
public void setGeoRssPoints(Set<String> geoRssPoints) {
this.geoRssPoints = geoRssPoints;
}
public Set<String> getGeoRssPolygons() {
return geoRssPolygons;
}
public void setGeoRssPolygons(Set<String> geoRssBoxes) {
this.geoRssPolygons = geoRssBoxes;
}
public Set<String> getGeoRssFeatureNames() {
return geoRssFeatureNames;
}
public void setGeoRssFeatureNames(Set<String> geoRssFeatureNames) {
this.geoRssFeatureNames = geoRssFeatureNames;
}
public Set<String> getAlternatives() {
return alternatives;
}
public void setAlternatives(Set<String> alternatives) {
this.alternatives = alternatives;
}
public Set<String> getPages() {
return pages;
}
public void setPages(Set<String> pages) {
this.pages = pages;
}
public Set<String> getKeywords() {
return keywords;
}
public void setKeywords(Set<String> keywords) {
this.keywords = keywords;
}
}
| data-registry-webapp/src/main/java/net/metadata/dataspace/data/model/version/CollectionVersion.java | package net.metadata.dataspace.data.model.version;
import net.metadata.dataspace.data.model.Record;
import net.metadata.dataspace.data.model.context.Publication;
import net.metadata.dataspace.data.model.context.Subject;
import net.metadata.dataspace.data.model.record.Activity;
import net.metadata.dataspace.data.model.record.Agent;
import net.metadata.dataspace.data.model.record.Collection;
import net.metadata.dataspace.data.model.record.Service;
import net.metadata.dataspace.data.model.types.CollectionType;
import org.hibernate.annotations.CollectionOfElements;
import org.hibernate.validator.NotNull;
import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;
import static javax.persistence.EnumType.STRING;
/**
* Author: alabri
* Date: 02/11/2010
* Time: 5:16:30 PM
*/
@Entity
public class CollectionVersion extends AbstractVersionEntity {
private static final long serialVersionUID = 1L;
@ManyToOne
private Collection parent;
@NotNull
@Enumerated(STRING)
private CollectionType type;
@NotNull
@Column(length = 4096)
private String rights;
@CollectionOfElements(fetch = FetchType.LAZY)
private Set<String> accessRights = new HashSet<String>();
private String license;
@CollectionOfElements(fetch = FetchType.LAZY)
private Set<String> temporals = new HashSet<String>();
@CollectionOfElements(fetch = FetchType.LAZY)
private Set<String> geoRssPoints = new HashSet<String>();
@CollectionOfElements(fetch = FetchType.LAZY)
private Set<String> geoRssPolygons = new HashSet<String>();
@CollectionOfElements(fetch = FetchType.LAZY)
private Set<String> geoRssFeatureNames = new HashSet<String>();
@CollectionOfElements(fetch = FetchType.LAZY)
private Set<String> keywords = new HashSet<String>();
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinTable(name = "collections_creators")
private Set<Agent> creators = new HashSet<Agent>();
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinTable(name = "collection_publishers")
private Set<Agent> publishers = new HashSet<Agent>();
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinTable(name = "collections_is_output_of")
private Set<Activity> isOutputOf = new HashSet<Activity>();
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinTable(name = "collections_is_accessed_via")
private Set<Service> isAccessedVia = new HashSet<Service>();
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinTable(name = "collections_subjects")
private Set<Subject> subjects = new HashSet<Subject>();
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinTable(name = "collections_publications")
private Set<Publication> isReferencedBy = new HashSet<Publication>();
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinTable(name = "collections_relations")
private Set<Collection> relations = new HashSet<Collection>();
@CollectionOfElements(fetch = FetchType.LAZY)
private Set<String> alternatives = new HashSet<String>();
@CollectionOfElements(fetch = FetchType.LAZY)
private Set<String> pages = new HashSet<String>();
public CollectionVersion() {
}
@Override
public Collection getParent() {
return parent;
}
@Override
public void setParent(Record parent) {
this.parent = (Collection) parent;
}
public Set<Subject> getSubjects() {
return subjects;
}
public void setSubjects(Set<Subject> subjects) {
this.subjects = subjects;
}
public Set<Agent> getCreators() {
return creators;
}
public void setCreators(Set<Agent> creators) {
this.creators = creators;
}
public Set<Activity> getOutputOf() {
return isOutputOf;
}
public void setOutputOf(Set<Activity> outputOf) {
isOutputOf = outputOf;
}
public Set<Service> getAccessedVia() {
return isAccessedVia;
}
public void setAccessedVia(Set<Service> accessedVia) {
this.isAccessedVia = accessedVia;
}
public CollectionType getType() {
return type;
}
public void setType(CollectionType type) {
this.type = type;
}
public Set<Agent> getPublishers() {
return publishers;
}
public void setPublishers(Set<Agent> publishers) {
this.publishers = publishers;
}
public String getRights() {
return rights;
}
public void setRights(String rights) {
this.rights = rights;
}
public String getLicense() {
return license;
}
public void setLicense(String license) {
this.license = license;
}
public Set<Publication> getReferencedBy() {
return isReferencedBy;
}
public void setReferencedBy(Set<Publication> referencedBy) {
isReferencedBy = referencedBy;
}
public Set<Collection> getRelations() {
return relations;
}
public void setRelations(Set<Collection> relations) {
this.relations = relations;
}
public Set<String> getAccessRights() {
return accessRights;
}
public void setAccessRights(Set<String> accessRights) {
this.accessRights = accessRights;
}
public Set<String> getTemporals() {
return temporals;
}
public void setTemporals(Set<String> temporals) {
this.temporals = temporals;
}
public Set<String> getGeoRssPoints() {
return geoRssPoints;
}
public void setGeoRssPoints(Set<String> geoRssPoints) {
this.geoRssPoints = geoRssPoints;
}
public Set<String> getGeoRssPolygons() {
return geoRssPolygons;
}
public void setGeoRssPolygons(Set<String> geoRssBoxes) {
this.geoRssPolygons = geoRssBoxes;
}
public Set<String> getGeoRssFeatureNames() {
return geoRssFeatureNames;
}
public void setGeoRssFeatureNames(Set<String> geoRssFeatureNames) {
this.geoRssFeatureNames = geoRssFeatureNames;
}
public Set<String> getAlternatives() {
return alternatives;
}
public void setAlternatives(Set<String> alternatives) {
this.alternatives = alternatives;
}
public Set<String> getPages() {
return pages;
}
public void setPages(Set<String> pages) {
this.pages = pages;
}
public Set<String> getKeywords() {
return keywords;
}
public void setKeywords(Set<String> keywords) {
this.keywords = keywords;
}
}
| increased the size of accessrights
git-svn-id: c915320aed33221a6cc00b5c5fda1fe642ba3057@740 a06b0660-b68b-0410-9a37-e6c9a29c9ca9
| data-registry-webapp/src/main/java/net/metadata/dataspace/data/model/version/CollectionVersion.java | increased the size of accessrights | <ide><path>ata-registry-webapp/src/main/java/net/metadata/dataspace/data/model/version/CollectionVersion.java
<ide> private String rights;
<ide>
<ide> @CollectionOfElements(fetch = FetchType.LAZY)
<add> @Column(name = "element", length = 4096)
<ide> private Set<String> accessRights = new HashSet<String>();
<ide>
<add> @Column(length = 4096)
<ide> private String license;
<ide>
<ide> @CollectionOfElements(fetch = FetchType.LAZY)
<ide> private Set<String> geoRssPoints = new HashSet<String>();
<ide>
<ide> @CollectionOfElements(fetch = FetchType.LAZY)
<add> @Column(name = "element", length = 4096)
<ide> private Set<String> geoRssPolygons = new HashSet<String>();
<ide>
<ide> @CollectionOfElements(fetch = FetchType.LAZY) |
|
Java | apache-2.0 | ce2e338a3b36149d134cd1a0598c116ad99ffabc | 0 | orientechnologies/orientdb,orientechnologies/orientdb,orientechnologies/orientdb,orientechnologies/orientdb | /*
*
* * Copyright 2014 Orient Technologies LTD (info(at)orientechnologies.com)
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
* * For more information: http://www.orientechnologies.com
*
*/
package com.orientechnologies.orient.core.metadata.schema;
import com.orientechnologies.common.exception.OException;
import com.orientechnologies.common.listener.OProgressListener;
import com.orientechnologies.common.util.OArrays;
import com.orientechnologies.common.util.OCommonConst;
import com.orientechnologies.orient.core.annotation.OBeforeSerialization;
import com.orientechnologies.orient.core.command.OCommandResultListener;
import com.orientechnologies.orient.core.db.ODatabaseDocumentInternal;
import com.orientechnologies.orient.core.db.ODatabaseInternal;
import com.orientechnologies.orient.core.db.ODatabaseRecordThreadLocal;
import com.orientechnologies.orient.core.db.OScenarioThreadLocal;
import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.db.record.ORecordElement;
import com.orientechnologies.orient.core.exception.OSchemaException;
import com.orientechnologies.orient.core.exception.OSecurityAccessException;
import com.orientechnologies.orient.core.exception.OSecurityException;
import com.orientechnologies.orient.core.id.ORecordId;
import com.orientechnologies.orient.core.index.*;
import com.orientechnologies.orient.core.metadata.schema.clusterselection.OClusterSelectionStrategy;
import com.orientechnologies.orient.core.metadata.schema.clusterselection.ORoundRobinClusterSelectionStrategy;
import com.orientechnologies.orient.core.metadata.security.ORole;
import com.orientechnologies.orient.core.metadata.security.ORule;
import com.orientechnologies.orient.core.metadata.security.OSecurityShared;
import com.orientechnologies.orient.core.metadata.security.OSecurityUser;
import com.orientechnologies.orient.core.record.ORecord;
import com.orientechnologies.orient.core.record.ORecordInternal;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.serialization.serializer.record.ORecordSerializerFactory;
import com.orientechnologies.orient.core.serialization.serializer.record.string.ORecordSerializerSchemaAware2CSV;
import com.orientechnologies.orient.core.sharding.auto.OAutoShardingClusterSelectionStrategy;
import com.orientechnologies.orient.core.sql.OCommandSQL;
import com.orientechnologies.orient.core.sql.query.OSQLAsynchQuery;
import com.orientechnologies.orient.core.storage.*;
import com.orientechnologies.orient.core.storage.impl.local.OAbstractPaginatedStorage;
import com.orientechnologies.orient.core.type.ODocumentWrapper;
import com.orientechnologies.orient.core.type.ODocumentWrapperNoClass;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;
/**
* Schema Class implementation.
*
* @author Luca Garulli (l.garulli--at--orientechnologies.com)
*/
@SuppressWarnings("unchecked")
public class OClassImpl extends ODocumentWrapperNoClass implements OClass {
private static final long serialVersionUID = 1L;
private static final int NOT_EXISTENT_CLUSTER_ID = -1;
final OSchemaShared owner;
private final Map<String, OProperty> properties = new HashMap<String, OProperty>();
private int defaultClusterId = NOT_EXISTENT_CLUSTER_ID;
private String name;
private String description;
private int[] clusterIds;
private List<OClassImpl> superClasses = new ArrayList<OClassImpl>();
private int[] polymorphicClusterIds;
private List<OClass> subclasses;
private float overSize = 0f;
private String shortName;
private boolean strictMode = false; // @SINCE v1.0rc8
private boolean abstractClass = false; // @SINCE v1.2.0
private Map<String, String> customFields;
private volatile OClusterSelectionStrategy clusterSelection; // @SINCE 1.7
private volatile int hashCode;
private static Set<String> reserved = new HashSet<String>();
static {
// reserved.add("select");
reserved.add("traverse");
reserved.add("insert");
reserved.add("update");
reserved.add("delete");
reserved.add("from");
reserved.add("where");
reserved.add("skip");
reserved.add("limit");
reserved.add("timeout");
}
/**
* Constructor used in unmarshalling.
*/
protected OClassImpl(final OSchemaShared iOwner, final String iName) {
this(iOwner, new ODocument().setTrackingChanges(false), iName);
}
protected OClassImpl(final OSchemaShared iOwner, final String iName, final int[] iClusterIds) {
this(iOwner, iName);
setClusterIds(iClusterIds);
defaultClusterId = iClusterIds[0];
if (defaultClusterId == NOT_EXISTENT_CLUSTER_ID)
abstractClass = true;
if (abstractClass)
setPolymorphicClusterIds(OCommonConst.EMPTY_INT_ARRAY);
else
setPolymorphicClusterIds(iClusterIds);
clusterSelection = owner.getClusterSelectionFactory().newInstanceOfDefaultClass();
}
/**
* Constructor used in unmarshalling.
*/
protected OClassImpl(final OSchemaShared iOwner, final ODocument iDocument, final String iName) {
name = iName;
document = iDocument;
owner = iOwner;
}
public static int[] readableClusters(final ODatabaseDocument iDatabase, final int[] iClusterIds) {
List<Integer> listOfReadableIds = new ArrayList<Integer>();
boolean all = true;
for (int clusterId : iClusterIds) {
try {
final String clusterName = iDatabase.getClusterNameById(clusterId);
iDatabase.checkSecurity(ORule.ResourceGeneric.CLUSTER, ORole.PERMISSION_READ, clusterName);
listOfReadableIds.add(clusterId);
} catch (OSecurityAccessException securityException) {
all = false;
// if the cluster is inaccessible it's simply not processed in the list.add
}
}
if (all)
// JUST RETURN INPUT ARRAY (FASTER)
return iClusterIds;
final int[] readableClusterIds = new int[listOfReadableIds.size()];
int index = 0;
for (int clusterId : listOfReadableIds) {
readableClusterIds[index++] = clusterId;
}
return readableClusterIds;
}
@Override
public OClusterSelectionStrategy getClusterSelection() {
acquireSchemaReadLock();
try {
return clusterSelection;
} finally {
releaseSchemaReadLock();
}
}
@Override
public OClass setClusterSelection(final OClusterSelectionStrategy clusterSelection) {
return setClusterSelection(clusterSelection.getName());
}
@Override
public OClass setClusterSelection(final String value) {
getDatabase().checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
acquireSchemaWriteLock();
try {
final ODatabaseDocumentInternal database = getDatabase();
final OStorage storage = database.getStorage();
if (storage instanceof OStorageProxy) {
final String cmd = String.format("alter class %s clusterselection %s", name, value);
database.command(new OCommandSQL(cmd)).execute();
} else if (isDistributedCommand()) {
final String cmd = String.format("alter class %s clusterselection %s", name, value);
OCommandSQL commandSQL = new OCommandSQL(cmd);
commandSQL.addExcludedNode(((OAutoshardedStorage) storage).getNodeId());
database.command(commandSQL).execute();
setClusterSelectionInternal(value);
} else
setClusterSelectionInternal(value);
return this;
} finally {
releaseSchemaWriteLock();
}
}
@Override
public <RET extends ODocumentWrapper> RET reload() {
return (RET) owner.reload();
}
public String getCustom(final String iName) {
acquireSchemaReadLock();
try {
if (customFields == null)
return null;
return customFields.get(iName);
} finally {
releaseSchemaReadLock();
}
}
public OClassImpl setCustom(final String name, final String value) {
getDatabase().checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
acquireSchemaWriteLock();
try {
final ODatabaseDocumentInternal database = getDatabase();
final OStorage storage = database.getStorage();
if (storage instanceof OStorageProxy) {
final String cmd = String.format("alter class %s custom %s=%s", getName(), name, value);
database.command(new OCommandSQL(cmd)).execute();
} else if (isDistributedCommand()) {
final String cmd = String.format("alter class %s custom %s=%s", getName(), name, value);
final OCommandSQL commandSQL = new OCommandSQL(cmd);
commandSQL.addExcludedNode(((OAutoshardedStorage) storage).getNodeId());
database.command(commandSQL).execute();
setCustomInternal(name, value);
} else
setCustomInternal(name, value);
return this;
} finally {
releaseSchemaWriteLock();
}
}
public Map<String, String> getCustomInternal() {
acquireSchemaReadLock();
try {
if (customFields != null)
return Collections.unmodifiableMap(customFields);
return null;
} finally {
releaseSchemaReadLock();
}
}
public void removeCustom(final String name) {
setCustom(name, null);
}
public void clearCustom() {
getDatabase().checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
acquireSchemaWriteLock();
try {
final ODatabaseDocumentInternal database = getDatabase();
final OStorage storage = database.getStorage();
if (storage instanceof OStorageProxy) {
final String cmd = String.format("alter class %s custom clear", getName());
database.command(new OCommandSQL(cmd)).execute();
} else if (isDistributedCommand()) {
final String cmd = String.format("alter class %s custom clear", getName());
final OCommandSQL commandSQL = new OCommandSQL(cmd);
commandSQL.addExcludedNode(((OAutoshardedStorage) storage).getNodeId());
database.command(commandSQL).execute();
clearCustomInternal();
} else
clearCustomInternal();
} finally {
releaseSchemaWriteLock();
}
}
public Set<String> getCustomKeys() {
acquireSchemaReadLock();
try {
if (customFields != null)
return Collections.unmodifiableSet(customFields.keySet());
return new HashSet<String>();
} finally {
releaseSchemaReadLock();
}
}
@Override
public boolean hasClusterId(final int clusterId) {
return Arrays.binarySearch(clusterIds, clusterId) >= 0;
}
@Override
public boolean hasPolymorphicClusterId(final int clusterId) {
return Arrays.binarySearch(polymorphicClusterIds, clusterId) >= 0;
}
@Override
public OClass getSuperClass() {
acquireSchemaReadLock();
try {
return superClasses.isEmpty() ? null : superClasses.get(0);
} finally {
releaseSchemaReadLock();
}
}
@Override
public OClass setSuperClass(OClass iSuperClass) {
setSuperClasses(iSuperClass != null ? Arrays.asList(iSuperClass) : Collections.EMPTY_LIST);
return this;
}
public String getName() {
acquireSchemaReadLock();
try {
return name;
} finally {
releaseSchemaReadLock();
}
}
@Override
public List<OClass> getSuperClasses() {
acquireSchemaReadLock();
try {
return Collections.unmodifiableList((List<? extends OClass>) superClasses);
} finally {
releaseSchemaReadLock();
}
}
@Override
public boolean hasSuperClasses() {
acquireSchemaReadLock();
try {
return !superClasses.isEmpty();
} finally {
releaseSchemaReadLock();
}
}
@Override
public List<String> getSuperClassesNames() {
acquireSchemaReadLock();
try {
List<String> superClassesNames = new ArrayList<String>(superClasses.size());
for (OClassImpl superClass : superClasses) {
superClassesNames.add(superClass.getName());
}
return superClassesNames;
} finally {
releaseSchemaReadLock();
}
}
public OClass setSuperClassesByNames(List<String> classNames) {
if (classNames == null)
classNames = Collections.EMPTY_LIST;
final List<OClass> classes = new ArrayList<OClass>(classNames.size());
final OSchema schema = getDatabase().getMetadata().getSchema();
for (String className : classNames) {
classes.add(schema.getClass(className));
}
return setSuperClasses(classes);
}
@Override
public OClass setSuperClasses(final List<? extends OClass> classes) {
getDatabase().checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
acquireSchemaWriteLock();
try {
final ODatabaseDocumentInternal database = getDatabase();
final OStorage storage = database.getStorage();
final StringBuilder sb = new StringBuilder();
if (classes != null && classes.size() > 0) {
for (OClass superClass : classes) {
sb.append(superClass.getName()).append(',');
}
sb.deleteCharAt(sb.length() - 1);
} else
sb.append("null");
final String cmd = String.format("alter class %s superclasses %s", name, sb);
if (storage instanceof OStorageProxy) {
database.command(new OCommandSQL(cmd)).execute();
} else if (isDistributedCommand()) {
final OCommandSQL commandSQL = new OCommandSQL(cmd);
commandSQL.addExcludedNode(((OAutoshardedStorage) storage).getNodeId());
database.command(commandSQL).execute();
setSuperClassesInternal(classes);
} else
setSuperClassesInternal(classes);
} finally {
releaseSchemaWriteLock();
}
return this;
}
void setSuperClassesInternal(final List<? extends OClass> classes) {
acquireSchemaWriteLock();
try {
List<OClassImpl> newSuperClasses = new ArrayList<OClassImpl>();
OClassImpl cls;
for (OClass superClass : classes) {
if (superClass instanceof OClassAbstractDelegate)
cls = (OClassImpl) ((OClassAbstractDelegate) superClass).delegate;
else
cls = (OClassImpl) superClass;
if (newSuperClasses.contains(cls)) {
throw new OSchemaException("Duplicated superclass '" + cls.getName() + "'");
}
newSuperClasses.add(cls);
}
checkParametersConflict(newSuperClasses);
List<OClassImpl> toAddList = new ArrayList<OClassImpl>(newSuperClasses);
toAddList.removeAll(superClasses);
List<OClassImpl> toRemoveList = new ArrayList<OClassImpl>(superClasses);
toRemoveList.removeAll(newSuperClasses);
for (OClassImpl toRemove : toRemoveList) {
toRemove.removeBaseClassInternal(this);
}
for (OClassImpl addTo : toAddList) {
addTo.addBaseClass(this);
}
superClasses.clear();
superClasses.addAll(newSuperClasses);
} finally {
releaseSchemaWriteLock();
}
}
@Override
public OClass addSuperClass(final OClass superClass) {
getDatabase().checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
acquireSchemaWriteLock();
try {
final ODatabaseDocumentInternal database = getDatabase();
final OStorage storage = database.getStorage();
if (storage instanceof OStorageProxy) {
final String cmd = String.format("alter class %s superclass +%s", name, superClass != null ? superClass.getName() : null);
database.command(new OCommandSQL(cmd)).execute();
} else if (isDistributedCommand()) {
final String cmd = String.format("alter class %s superclass +%s", name, superClass != null ? superClass.getName() : null);
final OCommandSQL commandSQL = new OCommandSQL(cmd);
commandSQL.addExcludedNode(((OAutoshardedStorage) storage).getNodeId());
database.command(commandSQL).execute();
addSuperClassInternal(superClass);
} else
addSuperClassInternal(superClass);
} finally {
releaseSchemaWriteLock();
}
return this;
}
void addSuperClassInternal(final OClass superClass) {
acquireSchemaWriteLock();
try {
final OClassImpl cls;
if (superClass instanceof OClassAbstractDelegate)
cls = (OClassImpl) ((OClassAbstractDelegate) superClass).delegate;
else
cls = (OClassImpl) superClass;
if (cls != null) {
// CHECK THE USER HAS UPDATE PRIVILEGE AGAINST EXTENDING CLASS
final OSecurityUser user = getDatabase().getUser();
if (user != null)
user.allow(ORule.ResourceGeneric.CLASS, cls.getName(), ORole.PERMISSION_UPDATE);
if (superClasses.contains(superClass)) {
throw new OSchemaException(
"Class: '" + this.getName() + "' already has the class '" + superClass.getName() + "' as superclass");
}
cls.addBaseClass(this);
superClasses.add(cls);
}
} finally {
releaseSchemaWriteLock();
}
}
@Override
public OClass removeSuperClass(OClass superClass) {
getDatabase().checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
acquireSchemaWriteLock();
try {
final ODatabaseDocumentInternal database = getDatabase();
final OStorage storage = database.getStorage();
if (storage instanceof OStorageProxy) {
final String cmd = String.format("alter class %s superclass -%s", name, superClass != null ? superClass.getName() : null);
database.command(new OCommandSQL(cmd)).execute();
} else if (isDistributedCommand()) {
final String cmd = String.format("alter class %s superclass -%s", name, superClass != null ? superClass.getName() : null);
final OCommandSQL commandSQL = new OCommandSQL(cmd);
commandSQL.addExcludedNode(((OAutoshardedStorage) storage).getNodeId());
database.command(commandSQL).execute();
removeSuperClassInternal(superClass);
} else
removeSuperClassInternal(superClass);
} finally {
releaseSchemaWriteLock();
}
return this;
}
void removeSuperClassInternal(final OClass superClass) {
acquireSchemaWriteLock();
try {
final OClassImpl cls;
if (superClass instanceof OClassAbstractDelegate)
cls = (OClassImpl) ((OClassAbstractDelegate) superClass).delegate;
else
cls = (OClassImpl) superClass;
if (superClasses.contains(cls)) {
if (cls != null)
cls.removeBaseClassInternal(this);
superClasses.remove(superClass);
}
} finally {
releaseSchemaWriteLock();
}
}
public OClass setName(final String name) {
if (getName().equals(name))
return this;
getDatabase().checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
final Character wrongCharacter = OSchemaShared.checkClassNameIfValid(name);
OClass oClass = getDatabase().getMetadata().getSchema().getClass(name);
if (oClass != null) {
String error = String.format("Cannot rename class %s to %s. A Class with name %s exists", this.name, name, name);
throw new OSchemaException(error);
}
if (wrongCharacter != null)
throw new OSchemaException(
"Invalid class name found. Character '" + wrongCharacter + "' cannot be used in class name '" + name + "'");
acquireSchemaWriteLock();
try {
final ODatabaseDocumentInternal database = getDatabase();
final OStorage storage = database.getStorage();
if (storage instanceof OStorageProxy) {
final String cmd = String.format("alter class %s name %s", this.name, name);
database.command(new OCommandSQL(cmd)).execute();
} else if (isDistributedCommand()) {
final String cmd = String.format("alter class %s name %s", this.name, name);
final OCommandSQL commandSQL = new OCommandSQL(cmd);
commandSQL.addExcludedNode(((OAutoshardedStorage) storage).getNodeId());
database.command(commandSQL).execute();
setNameInternal(name);
} else
setNameInternal(name);
} finally {
releaseSchemaWriteLock();
}
return this;
}
public long getSize() {
acquireSchemaReadLock();
try {
long size = 0;
for (int clusterId : clusterIds)
size += getDatabase().getClusterRecordSizeById(clusterId);
return size;
} finally {
releaseSchemaReadLock();
}
}
public String getShortName() {
acquireSchemaReadLock();
try {
return shortName;
} finally {
releaseSchemaReadLock();
}
}
public OClass setShortName(String shortName) {
if (shortName != null) {
shortName = shortName.trim();
if (shortName.isEmpty())
shortName = null;
}
getDatabase().checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
acquireSchemaWriteLock();
try {
final ODatabaseDocumentInternal database = getDatabase();
final OStorage storage = database.getStorage();
if (storage instanceof OStorageProxy) {
final String cmd = String.format("alter class %s shortname %s", name, shortName);
database.command(new OCommandSQL(cmd)).execute();
} else if (isDistributedCommand()) {
final String cmd = String.format("alter class %s shortname %s", name, shortName);
final OCommandSQL commandSQL = new OCommandSQL(cmd);
commandSQL.addExcludedNode(((OAutoshardedStorage) storage).getNodeId());
database.command(commandSQL).execute();
setShortNameInternal(shortName);
} else
setShortNameInternal(shortName);
} finally {
releaseSchemaWriteLock();
}
return this;
}
public String getDescription() {
acquireSchemaReadLock();
try {
return description;
} finally {
releaseSchemaReadLock();
}
}
public OClass setDescription(String iDescription) {
if (iDescription != null) {
iDescription = iDescription.trim();
if (iDescription.isEmpty())
iDescription = null;
}
getDatabase().checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
acquireSchemaWriteLock();
try {
final ODatabaseDocumentInternal database = getDatabase();
final OStorage storage = database.getStorage();
if (storage instanceof OStorageProxy) {
final String cmd = String.format("alter class %s description %s", name, shortName);
database.command(new OCommandSQL(cmd)).execute();
} else if (isDistributedCommand()) {
final String cmd = String.format("alter class %s description %s", name, shortName);
final OCommandSQL commandSQL = new OCommandSQL(cmd);
commandSQL.addExcludedNode(((OAutoshardedStorage) storage).getNodeId());
database.command(commandSQL).execute();
setDescriptionInternal(iDescription);
} else
setDescriptionInternal(iDescription);
} finally {
releaseSchemaWriteLock();
}
return this;
}
public String getStreamableName() {
acquireSchemaReadLock();
try {
return shortName != null ? shortName : name;
} finally {
releaseSchemaReadLock();
}
}
public Collection<OProperty> declaredProperties() {
acquireSchemaReadLock();
try {
return Collections.unmodifiableCollection(properties.values());
} finally {
releaseSchemaReadLock();
}
}
public Map<String, OProperty> propertiesMap() {
getDatabase().checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_READ);
acquireSchemaReadLock();
try {
final Map<String, OProperty> props = new HashMap<String, OProperty>(20);
propertiesMap(props, true);
return props;
} finally {
releaseSchemaReadLock();
}
}
private void propertiesMap(Map<String, OProperty> propertiesMap, boolean keepCase) {
for (OProperty p : properties.values()) {
String propName = p.getName();
if (!keepCase)
propName = propName.toLowerCase();
if (!propertiesMap.containsKey(propName))
propertiesMap.put(propName, p);
}
for (OClassImpl superClass : superClasses) {
superClass.propertiesMap(propertiesMap, keepCase);
}
}
public Collection<OProperty> properties() {
getDatabase().checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_READ);
acquireSchemaReadLock();
try {
final Collection<OProperty> props = new ArrayList<OProperty>();
properties(props);
return props;
} finally {
releaseSchemaReadLock();
}
}
private void properties(Collection<OProperty> properties) {
properties.addAll(this.properties.values());
for (OClassImpl superClass : superClasses) {
superClass.properties(properties);
}
}
public void getIndexedProperties(Collection<OProperty> indexedProperties) {
for (OProperty p : properties.values())
if (areIndexed(p.getName()))
indexedProperties.add(p);
for (OClassImpl superClass : superClasses) {
superClass.getIndexedProperties(indexedProperties);
}
}
@Override
public Collection<OProperty> getIndexedProperties() {
getDatabase().checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_READ);
acquireSchemaReadLock();
try {
Collection<OProperty> indexedProps = new HashSet<OProperty>();
getIndexedProperties(indexedProps);
return indexedProps;
} finally {
releaseSchemaReadLock();
}
}
public OProperty getProperty(String propertyName) {
acquireSchemaReadLock();
try {
propertyName = propertyName.toLowerCase();
OProperty p = properties.get(propertyName);
if (p != null)
return p;
for (int i = 0; i < superClasses.size() && p == null; i++) {
p = superClasses.get(i).getProperty(propertyName);
}
return p;
} finally {
releaseSchemaReadLock();
}
}
public OProperty createProperty(final String iPropertyName, final OType iType) {
return addProperty(iPropertyName, iType, null, null, false);
}
public OProperty createProperty(final String iPropertyName, final OType iType, final OClass iLinkedClass) {
if (iLinkedClass == null)
throw new OSchemaException("Missing linked class");
return addProperty(iPropertyName, iType, null, iLinkedClass, false);
}
public OProperty createProperty(final String iPropertyName, final OType iType, final OClass iLinkedClass, final boolean unsafe) {
if (iLinkedClass == null)
throw new OSchemaException("Missing linked class");
return addProperty(iPropertyName, iType, null, iLinkedClass, unsafe);
}
public OProperty createProperty(final String iPropertyName, final OType iType, final OType iLinkedType) {
return addProperty(iPropertyName, iType, iLinkedType, null, false);
}
public OProperty createProperty(final String iPropertyName, final OType iType, final OType iLinkedType, final boolean unsafe) {
return addProperty(iPropertyName, iType, iLinkedType, null, unsafe);
}
@Override
public boolean existsProperty(String propertyName) {
acquireSchemaReadLock();
try {
propertyName = propertyName.toLowerCase();
boolean result = properties.containsKey(propertyName);
if (result)
return true;
for (OClassImpl superClass : superClasses) {
result = superClass.existsProperty(propertyName);
if (result)
return true;
}
return false;
} finally {
releaseSchemaReadLock();
}
}
public void dropProperty(final String propertyName) {
if (getDatabase().getTransaction().isActive())
throw new IllegalStateException("Cannot drop a property inside a transaction");
getDatabase().checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_DELETE);
final String lowerName = propertyName.toLowerCase();
acquireSchemaWriteLock();
try {
if (!properties.containsKey(lowerName))
throw new OSchemaException("Property '" + propertyName + "' not found in class " + name + "'");
final ODatabaseDocumentInternal database = getDatabase();
final OStorage storage = database.getStorage();
if (storage instanceof OStorageProxy) {
database.command(new OCommandSQL("drop property " + name + '.' + propertyName)).execute();
} else if (isDistributedCommand()) {
final OCommandSQL commandSQL = new OCommandSQL("drop property " + name + '.' + propertyName);
commandSQL.addExcludedNode(((OAutoshardedStorage) storage).getNodeId());
database.command(commandSQL).execute();
dropPropertyInternal(propertyName);
} else
dropPropertyInternal(propertyName);
} finally {
releaseSchemaWriteLock();
}
}
@Override
public void fromStream() {
subclasses = null;
superClasses.clear();
name = document.field("name");
if (document.containsField("shortName"))
shortName = document.field("shortName");
else
shortName = null;
if (document.containsField("description"))
description = document.field("description");
else
description = null;
defaultClusterId = document.field("defaultClusterId");
if (document.containsField("strictMode"))
strictMode = document.field("strictMode");
else
strictMode = false;
if (document.containsField("abstract"))
abstractClass = document.field("abstract");
else
abstractClass = false;
if (document.field("overSize") != null)
overSize = document.field("overSize");
else
overSize = 0f;
final Object cc = document.field("clusterIds");
if (cc instanceof Collection<?>) {
final Collection<Integer> coll = document.field("clusterIds");
clusterIds = new int[coll.size()];
int i = 0;
for (final Integer item : coll)
clusterIds[i++] = item;
} else
clusterIds = (int[]) cc;
Arrays.sort(clusterIds);
if (clusterIds.length == 1 && clusterIds[0] == -1)
setPolymorphicClusterIds(OCommonConst.EMPTY_INT_ARRAY);
else
setPolymorphicClusterIds(clusterIds);
// READ PROPERTIES
OPropertyImpl prop;
final Map<String, OProperty> newProperties = new HashMap<String, OProperty>();
final Collection<ODocument> storedProperties = document.field("properties");
if (storedProperties != null)
for (ODocument p : storedProperties) {
prop = new OPropertyImpl(this, p);
prop.fromStream();
if (properties.containsKey(prop.getName())) {
prop = (OPropertyImpl) properties.get(prop.getName().toLowerCase());
prop.fromStream(p);
}
newProperties.put(prop.getName().toLowerCase(), prop);
}
properties.clear();
properties.putAll(newProperties);
customFields = document.field("customFields", OType.EMBEDDEDMAP);
clusterSelection = owner.getClusterSelectionFactory().getStrategy((String) document.field("clusterSelection"));
}
@Override
@OBeforeSerialization
public ODocument toStream() {
document.setInternalStatus(ORecordElement.STATUS.UNMARSHALLING);
try {
document.field("name", name);
document.field("shortName", shortName);
document.field("description", description);
document.field("defaultClusterId", defaultClusterId);
document.field("clusterIds", clusterIds);
document.field("clusterSelection", clusterSelection.getName());
document.field("overSize", overSize);
document.field("strictMode", strictMode);
document.field("abstract", abstractClass);
final Set<ODocument> props = new LinkedHashSet<ODocument>();
for (final OProperty p : properties.values()) {
props.add(((OPropertyImpl) p).toStream());
}
document.field("properties", props, OType.EMBEDDEDSET);
if (superClasses.isEmpty()) {
// Single super class is deprecated!
document.field("superClass", null, OType.STRING);
document.field("superClasses", null, OType.EMBEDDEDLIST);
} else {
// Single super class is deprecated!
document.field("superClass", superClasses.get(0).getName(), OType.STRING);
List<String> superClassesNames = new ArrayList<String>();
for (OClassImpl superClass : superClasses) {
superClassesNames.add(superClass.getName());
}
document.field("superClasses", superClassesNames, OType.EMBEDDEDLIST);
}
document.field("customFields", customFields != null && customFields.size() > 0 ? customFields : null, OType.EMBEDDEDMAP);
} finally {
document.setInternalStatus(ORecordElement.STATUS.LOADED);
}
return document;
}
@Override
public int getClusterForNewInstance(final ODocument doc) {
acquireSchemaReadLock();
try {
return clusterSelection.getCluster(this, doc);
} finally {
releaseSchemaReadLock();
}
}
public int getDefaultClusterId() {
acquireSchemaReadLock();
try {
return defaultClusterId;
} finally {
releaseSchemaReadLock();
}
}
public void setDefaultClusterId(final int defaultClusterId) {
acquireSchemaWriteLock();
try {
checkEmbedded();
this.defaultClusterId = defaultClusterId;
} finally {
releaseSchemaWriteLock();
}
}
public int[] getClusterIds() {
acquireSchemaReadLock();
try {
return clusterIds;
} finally {
releaseSchemaReadLock();
}
}
public int[] getPolymorphicClusterIds() {
acquireSchemaReadLock();
try {
return polymorphicClusterIds;
} finally {
releaseSchemaReadLock();
}
}
private void setPolymorphicClusterIds(final int[] iClusterIds) {
polymorphicClusterIds = iClusterIds;
Arrays.sort(polymorphicClusterIds);
}
public void renameProperty(final String iOldName, final String iNewName) {
final OProperty p = properties.remove(iOldName.toLowerCase());
if (p != null)
properties.put(iNewName.toLowerCase(), p);
}
public OClass addClusterId(final int clusterId) {
getDatabase().checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
if (isAbstract()) {
throw new OSchemaException("Impossible to associate a cluster to an abstract class class");
}
acquireSchemaWriteLock();
try {
final ODatabaseDocumentInternal database = getDatabase();
final OStorage storage = database.getStorage();
if (storage instanceof OStorageProxy) {
final String cmd = String.format("alter class %s addcluster %d", name, clusterId);
database.command(new OCommandSQL(cmd)).execute();
} else if (isDistributedCommand()) {
final String cmd = String.format("alter class %s addcluster %d", name, clusterId);
final OCommandSQL commandSQL = new OCommandSQL(cmd);
commandSQL.addExcludedNode(((OAutoshardedStorage) storage).getNodeId());
database.command(commandSQL).execute();
addClusterIdInternal(clusterId);
} else
addClusterIdInternal(clusterId);
} finally {
releaseSchemaWriteLock();
}
return this;
}
public static OClass addClusters(final OClass cls, final int iClusters) {
final String clusterBase = cls.getName().toLowerCase() + "_";
for (int i = 1; i < iClusters; ++i) {
cls.addCluster(clusterBase + i);
}
return cls;
}
@Override
public OClass addCluster(final String clusterNameOrId) {
getDatabase().checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
if (isAbstract()) {
throw new OSchemaException("Impossible to associate a cluster to an abstract class class");
}
acquireSchemaWriteLock();
try {
final ODatabaseDocumentInternal database = getDatabase();
final OStorage storage = database.getStorage();
if (storage instanceof OStorageProxy) {
final String cmd = String.format("alter class `%s` addcluster `%s`", name, clusterNameOrId);
database.command(new OCommandSQL(cmd)).execute();
} else if (isDistributedCommand()) {
final int clusterId = createClusterIfNeeded(clusterNameOrId);
addClusterIdInternal(clusterId);
final String cmd = String.format("alter class `%s` addcluster `%s`", name, clusterNameOrId);
final OCommandSQL commandSQL = new OCommandSQL(cmd);
commandSQL.addExcludedNode(((OAutoshardedStorage) storage).getNodeId());
database.command(commandSQL).execute();
} else {
final int clusterId = createClusterIfNeeded(clusterNameOrId);
addClusterIdInternal(clusterId);
}
} finally {
releaseSchemaWriteLock();
}
return this;
}
public OClass removeClusterId(final int clusterId) {
getDatabase().checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
acquireSchemaWriteLock();
try {
final ODatabaseDocumentInternal database = getDatabase();
final OStorage storage = database.getStorage();
if (storage instanceof OStorageProxy) {
final String cmd = String.format("alter class %s removecluster %d", name, clusterId);
database.command(new OCommandSQL(cmd)).execute();
} else if (isDistributedCommand()) {
final String cmd = String.format("alter class %s removecluster %d", name, clusterId);
final OCommandSQL commandSQL = new OCommandSQL(cmd);
commandSQL.addExcludedNode(((OAutoshardedStorage) storage).getNodeId());
database.command(commandSQL).execute();
removeClusterIdInternal(clusterId);
} else
removeClusterIdInternal(clusterId);
} finally {
releaseSchemaWriteLock();
}
return this;
}
public Collection<OClass> getSubclasses() {
acquireSchemaReadLock();
try {
if (subclasses == null || subclasses.size() == 0)
return Collections.emptyList();
return Collections.unmodifiableCollection(subclasses);
} finally {
releaseSchemaReadLock();
}
}
public Collection<OClass> getAllSubclasses() {
acquireSchemaReadLock();
try {
final Set<OClass> set = new HashSet<OClass>();
if (subclasses != null) {
set.addAll(subclasses);
for (OClass c : subclasses)
set.addAll(c.getAllSubclasses());
}
return set;
} finally {
releaseSchemaReadLock();
}
}
public Collection<OClass> getBaseClasses() {
return getSubclasses();
}
public Collection<OClass> getAllBaseClasses() {
return getAllSubclasses();
}
@Override
public Collection<OClass> getAllSuperClasses() {
Set<OClass> ret = new HashSet<OClass>();
getAllSuperClasses(ret);
return ret;
}
private void getAllSuperClasses(Set<OClass> set) {
set.addAll(superClasses);
for (OClassImpl superClass : superClasses) {
superClass.getAllSuperClasses(set);
}
}
OClass removeBaseClassInternal(final OClass baseClass) {
acquireSchemaWriteLock();
try {
checkEmbedded();
if (subclasses == null)
return this;
if (subclasses.remove(baseClass))
removePolymorphicClusterIds((OClassImpl) baseClass);
return this;
} finally {
releaseSchemaWriteLock();
}
}
public float getOverSize() {
acquireSchemaReadLock();
try {
if (overSize > 0)
// CUSTOM OVERSIZE SET
return overSize;
// NO OVERSIZE by default
float maxOverSize = 0;
float thisOverSize;
for (OClassImpl superClass : superClasses) {
thisOverSize = superClass.getOverSize();
if (thisOverSize > maxOverSize)
maxOverSize = thisOverSize;
}
return maxOverSize;
} finally {
releaseSchemaReadLock();
}
}
public OClass setOverSize(final float overSize) {
getDatabase().checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
acquireSchemaWriteLock();
try {
final ODatabaseDocumentInternal database = getDatabase();
final OStorage storage = database.getStorage();
if (storage instanceof OStorageProxy) {
// FORMAT FLOAT LOCALE AGNOSTIC
final String cmd = String.format("alter class %s oversize %s", name, new Float(overSize).toString());
database.command(new OCommandSQL(cmd)).execute();
} else if (isDistributedCommand()) {
// FORMAT FLOAT LOCALE AGNOSTIC
final String cmd = String.format("alter class %s oversize %s", name, new Float(overSize).toString());
final OCommandSQL commandSQL = new OCommandSQL(cmd);
commandSQL.addExcludedNode(((OAutoshardedStorage) storage).getNodeId());
database.command(commandSQL).execute();
setOverSizeInternal(overSize);
} else
setOverSizeInternal(overSize);
} finally {
releaseSchemaWriteLock();
}
return this;
}
@Override
public float getClassOverSize() {
acquireSchemaReadLock();
try {
return overSize;
} finally {
releaseSchemaReadLock();
}
}
public boolean isAbstract() {
acquireSchemaReadLock();
try {
return abstractClass;
} finally {
releaseSchemaReadLock();
}
}
public OClass setAbstract(boolean isAbstract) {
getDatabase().checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
acquireSchemaWriteLock();
try {
final ODatabaseDocumentInternal database = getDatabase();
final OStorage storage = database.getStorage();
if (storage instanceof OStorageProxy) {
final String cmd = String.format("alter class %s abstract %s", name, isAbstract);
database.command(new OCommandSQL(cmd)).execute();
} else if (isDistributedCommand()) {
final String cmd = String.format("alter class %s abstract %s", name, isAbstract);
final OCommandSQL commandSQL = new OCommandSQL(cmd);
commandSQL.addExcludedNode(((OAutoshardedStorage) storage).getNodeId());
database.command(commandSQL).execute();
setAbstractInternal(isAbstract);
} else
setAbstractInternal(isAbstract);
} finally {
releaseSchemaWriteLock();
}
return this;
}
public boolean isStrictMode() {
acquireSchemaReadLock();
try {
return strictMode;
} finally {
releaseSchemaReadLock();
}
}
public OClass setStrictMode(final boolean isStrict) {
getDatabase().checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
acquireSchemaWriteLock();
try {
final ODatabaseDocumentInternal database = getDatabase();
final OStorage storage = database.getStorage();
if (storage instanceof OStorageProxy) {
final String cmd = String.format("alter class %s strictmode %s", name, isStrict);
database.command(new OCommandSQL(cmd)).execute();
} else if (isDistributedCommand()) {
final String cmd = String.format("alter class %s strictmode %s", name, isStrict);
final OCommandSQL commandSQL = new OCommandSQL(cmd);
commandSQL.addExcludedNode(((OAutoshardedStorage) storage).getNodeId());
database.command(commandSQL).execute();
setStrictModeInternal(isStrict);
} else
setStrictModeInternal(isStrict);
} finally {
releaseSchemaWriteLock();
}
return this;
}
@Override
public String toString() {
acquireSchemaReadLock();
try {
return name;
} finally {
releaseSchemaReadLock();
}
}
@Override
public boolean equals(Object obj) {
acquireSchemaReadLock();
try {
if (this == obj)
return true;
if (obj == null)
return false;
if (!OClass.class.isAssignableFrom(obj.getClass()))
return false;
final OClass other = (OClass) obj;
if (name == null) {
if (other.getName() != null)
return false;
} else if (!name.equals(other.getName()))
return false;
return true;
} finally {
releaseSchemaReadLock();
}
}
@Override
public int hashCode() {
int sh = hashCode;
if (sh != 0)
return sh;
acquireSchemaReadLock();
try {
sh = hashCode;
if (sh != 0)
return sh;
calculateHashCode();
return hashCode;
} finally {
releaseSchemaReadLock();
}
}
public int compareTo(final OClass o) {
acquireSchemaReadLock();
try {
return name.compareTo(o.getName());
} finally {
releaseSchemaReadLock();
}
}
public long count() {
return count(true);
}
public long count(final boolean isPolymorphic) {
acquireSchemaReadLock();
try {
if (isPolymorphic)
return getDatabase().countClusterElements(readableClusters(getDatabase(), polymorphicClusterIds));
return getDatabase().countClusterElements(readableClusters(getDatabase(), clusterIds));
} finally {
releaseSchemaReadLock();
}
}
/**
* Truncates all the clusters the class uses.
*
* @throws IOException
*/
public void truncate() throws IOException {
getDatabase().checkSecurity(ORule.ResourceGeneric.CLASS, ORole.PERMISSION_UPDATE);
if (isSubClassOf(OSecurityShared.RESTRICTED_CLASSNAME)) {
throw new OSecurityException(
"Class '" + getName() + "' cannot be truncated because has record level security enabled (extends '"
+ OSecurityShared.RESTRICTED_CLASSNAME + "')");
}
final OStorage storage = getDatabase().getStorage();
acquireSchemaReadLock();
try {
for (int id : clusterIds)
storage.getClusterById(id).truncate();
for (OIndex<?> index : getClassIndexes())
index.clear();
Set<OIndex<?>> superclassIndexes = new HashSet<OIndex<?>>();
superclassIndexes.addAll(getIndexes());
superclassIndexes.removeAll(getClassIndexes());
for (OIndex index : superclassIndexes) {
index.rebuild();
}
} finally {
releaseSchemaReadLock();
}
}
/**
* Check if the current instance extends specified schema class.
*
* @param iClassName
* of class that should be checked
* @return Returns true if the current instance extends the passed schema class (iClass)
* @see #isSuperClassOf(OClass)
*/
public boolean isSubClassOf(final String iClassName) {
acquireSchemaReadLock();
try {
if (iClassName == null)
return false;
if (iClassName.equalsIgnoreCase(getName()) || iClassName.equalsIgnoreCase(getShortName()))
return true;
for (OClassImpl superClass : superClasses) {
if (superClass.isSubClassOf(iClassName))
return true;
}
return false;
} finally {
releaseSchemaReadLock();
}
}
/**
* Check if the current instance extends specified schema class.
*
* @param clazz
* to check
* @return true if the current instance extends the passed schema class (iClass)
* @see #isSuperClassOf(OClass)
*/
public boolean isSubClassOf(final OClass clazz) {
acquireSchemaReadLock();
try {
if (clazz == null)
return false;
if (equals(clazz))
return true;
for (OClassImpl superClass : superClasses) {
if (superClass.isSubClassOf(clazz))
return true;
}
return false;
} finally {
releaseSchemaReadLock();
}
}
/**
* Returns true if the passed schema class (iClass) extends the current instance.
*
* @param clazz
* to check
* @return Returns true if the passed schema class extends the current instance
* @see #isSubClassOf(OClass)
*/
public boolean isSuperClassOf(final OClass clazz) {
return clazz != null && clazz.isSubClassOf(this);
}
public Object get(final ATTRIBUTES iAttribute) {
if (iAttribute == null)
throw new IllegalArgumentException("attribute is null");
switch (iAttribute) {
case NAME:
return getName();
case SHORTNAME:
return getShortName();
case SUPERCLASS:
return getSuperClass();
case SUPERCLASSES:
return getSuperClasses();
case OVERSIZE:
return getOverSize();
case STRICTMODE:
return isStrictMode();
case ABSTRACT:
return isAbstract();
case CLUSTERSELECTION:
return getClusterSelection();
case CUSTOM:
return getCustomInternal();
case DESCRIPTION:
return getDescription();
}
throw new IllegalArgumentException("Cannot find attribute '" + iAttribute + "'");
}
public OClass set(final ATTRIBUTES attribute, final Object iValue) {
if (attribute == null)
throw new IllegalArgumentException("attribute is null");
final String stringValue = iValue != null ? iValue.toString() : null;
final boolean isNull = stringValue == null || stringValue.equalsIgnoreCase("NULL");
switch (attribute) {
case NAME:
setName(stringValue);
break;
case SHORTNAME:
setShortName(stringValue);
break;
case SUPERCLASS:
if (stringValue == null)
throw new IllegalArgumentException("Superclass is null");
if (stringValue.startsWith("+")) {
addSuperClass(getDatabase().getMetadata().getSchema().getClass(stringValue.substring(1)));
} else if (stringValue.startsWith("-")) {
removeSuperClass(getDatabase().getMetadata().getSchema().getClass(stringValue.substring(1)));
} else {
setSuperClass(getDatabase().getMetadata().getSchema().getClass(stringValue));
}
break;
case SUPERCLASSES:
setSuperClassesByNames(stringValue != null ? Arrays.asList(stringValue.split(",\\s*")) : null);
break;
case OVERSIZE:
setOverSize(Float.parseFloat(stringValue));
break;
case STRICTMODE:
setStrictMode(Boolean.parseBoolean(stringValue));
break;
case ABSTRACT:
setAbstract(Boolean.parseBoolean(stringValue));
break;
case ADDCLUSTER: {
addCluster(stringValue);
break;
}
case REMOVECLUSTER:
int clId = getClusterId(stringValue);
if (clId == NOT_EXISTENT_CLUSTER_ID)
throw new IllegalArgumentException("Cluster id '" + stringValue + "' cannot be removed");
removeClusterId(clId);
break;
case CLUSTERSELECTION:
setClusterSelection(stringValue);
break;
case CUSTOM:
int indx = stringValue != null ? stringValue.indexOf('=') : -1;
if (indx < 0) {
if (isNull || "clear".equalsIgnoreCase(stringValue)) {
clearCustom();
} else
throw new IllegalArgumentException("Syntax error: expected <name> = <value> or clear, instead found: " + iValue);
} else {
String customName = stringValue.substring(0, indx).trim();
String customValue = stringValue.substring(indx + 1).trim();
if (customValue.isEmpty())
removeCustom(customName);
else
setCustom(customName, customValue);
}
break;
case DESCRIPTION:
setDescription(stringValue);
break;
case ENCRYPTION:
setEncryption(stringValue);
break;
}
return this;
}
public OClassImpl setEncryption(final String iValue) {
getDatabase().checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
acquireSchemaWriteLock();
try {
final ODatabaseDocumentInternal database = getDatabase();
final OStorage storage = database.getStorage();
if (storage instanceof OStorageProxy) {
final String cmd = String.format("alter class %s encryption %s", name, iValue);
database.command(new OCommandSQL(cmd)).execute();
} else if (isDistributedCommand()) {
final String cmd = String.format("alter class %s encryption %s", name, iValue);
final OCommandSQL commandSQL = new OCommandSQL(cmd);
commandSQL.addExcludedNode(((OAutoshardedStorage) storage).getNodeId());
database.command(commandSQL).execute();
setEncryptionInternal(iValue);
} else
setEncryptionInternal(iValue);
} finally {
releaseSchemaWriteLock();
}
return this;
}
protected void setEncryptionInternal(final String iValue) {
for (int cl : getClusterIds()) {
final OCluster c = getDatabase().getStorage().getClusterById(cl);
if (c != null)
try {
c.set(OCluster.ATTRIBUTES.ENCRYPTION, iValue);
} catch (IOException e) {
}
}
}
public OPropertyImpl addPropertyInternal(final String name, final OType type, final OType linkedType, final OClass linkedClass,
final boolean unsafe) {
if (name == null || name.length() == 0)
throw new OSchemaException("Found property name null");
final Character wrongCharacter = OSchemaShared.checkFieldNameIfValid(name);
if (wrongCharacter != null)
throw new OSchemaException("Invalid property name '" + name + "'. Character '" + wrongCharacter + "' cannot be used");
if (!unsafe)
checkPersistentPropertyType(getDatabase(), name, type);
final String lowerName = name.toLowerCase();
final OPropertyImpl prop;
// This check are doubled becouse used by sql commands
if (linkedType != null)
OPropertyImpl.checkLinkTypeSupport(type);
if (linkedClass != null)
OPropertyImpl.checkSupportLinkedClass(type);
acquireSchemaWriteLock();
try {
checkEmbedded();
if (properties.containsKey(lowerName))
throw new OSchemaException("Class '" + this.name + "' already has property '" + name + "'");
OGlobalProperty global = owner.findOrCreateGlobalProperty(name, type);
prop = new OPropertyImpl(this, global);
properties.put(lowerName, prop);
if (linkedType != null)
prop.setLinkedTypeInternal(linkedType);
else if (linkedClass != null)
prop.setLinkedClassInternal(linkedClass);
} finally {
releaseSchemaWriteLock();
}
if (prop != null && !unsafe)
fireDatabaseMigration(getDatabase(), name, type);
return prop;
}
public OIndex<?> createIndex(final String iName, final INDEX_TYPE iType, final String... fields) {
return createIndex(iName, iType.name(), fields);
}
public OIndex<?> createIndex(final String iName, final String iType, final String... fields) {
return createIndex(iName, iType, null, null, fields);
}
public OIndex<?> createIndex(final String iName, final INDEX_TYPE iType, final OProgressListener iProgressListener,
final String... fields) {
return createIndex(iName, iType.name(), iProgressListener, null, fields);
}
public OIndex<?> createIndex(String iName, String iType, OProgressListener iProgressListener, ODocument metadata,
String... fields) {
return createIndex(iName, iType, iProgressListener, metadata, null, fields);
}
public OIndex<?> createIndex(final String name, String type, final OProgressListener progressListener, ODocument metadata,
String algorithm, final String... fields) {
if (type == null)
throw new IllegalArgumentException("Index type is null");
type = type.toUpperCase();
if (fields.length == 0) {
throw new OIndexException("List of fields to index cannot be empty.");
}
final OIndexDefinition indexDefinition;
acquireSchemaReadLock();
try {
for (final String fieldToIndex : fields) {
final String fieldName = OIndexDefinitionFactory.extractFieldName(fieldToIndex);
if (!fieldName.equals("@rid") && !existsProperty(fieldName))
throw new OIndexException("Index with name : '" + name + "' cannot be created on class '" + this.name
+ "' because field '" + fieldName + "' is absent in class definition.");
}
indexDefinition = OIndexDefinitionFactory.createIndexDefinition(this, Arrays.asList(fields), extractFieldTypes(fields), null,
type, algorithm);
} finally {
releaseSchemaReadLock();
}
return getDatabase().getMetadata().getIndexManager().createIndex(name, type, indexDefinition, polymorphicClusterIds,
progressListener, metadata, algorithm);
}
public boolean areIndexed(final String... fields) {
return areIndexed(Arrays.asList(fields));
}
public boolean areIndexed(final Collection<String> fields) {
final OIndexManager indexManager = getDatabase().getMetadata().getIndexManager();
acquireSchemaReadLock();
try {
final boolean currentClassResult = indexManager.areIndexed(name, fields);
if (currentClassResult)
return true;
for (OClassImpl superClass : superClasses) {
if (superClass.areIndexed(fields))
return true;
}
return false;
} finally {
releaseSchemaReadLock();
}
}
public Set<OIndex<?>> getInvolvedIndexes(final String... fields) {
return getInvolvedIndexes(Arrays.asList(fields));
}
public Set<OIndex<?>> getInvolvedIndexes(final Collection<String> fields) {
acquireSchemaReadLock();
try {
final Set<OIndex<?>> result = new HashSet<OIndex<?>>(getClassInvolvedIndexes(fields));
for (OClassImpl superClass : superClasses) {
result.addAll(superClass.getInvolvedIndexes(fields));
}
return result;
} finally {
releaseSchemaReadLock();
}
}
public Set<OIndex<?>> getClassInvolvedIndexes(final Collection<String> fields) {
final OIndexManager indexManager = getDatabase().getMetadata().getIndexManager();
acquireSchemaReadLock();
try {
return indexManager.getClassInvolvedIndexes(name, fields);
} finally {
releaseSchemaReadLock();
}
}
public Set<OIndex<?>> getClassInvolvedIndexes(final String... fields) {
return getClassInvolvedIndexes(Arrays.asList(fields));
}
public OIndex<?> getClassIndex(final String name) {
acquireSchemaReadLock();
try {
return getDatabase().getMetadata().getIndexManager().getClassIndex(this.name, name);
} finally {
releaseSchemaReadLock();
}
}
public Set<OIndex<?>> getClassIndexes() {
acquireSchemaReadLock();
try {
final OIndexManagerProxy idxManager = getDatabase().getMetadata().getIndexManager();
if (idxManager == null)
return new HashSet<OIndex<?>>();
return idxManager.getClassIndexes(name);
} finally {
releaseSchemaReadLock();
}
}
@Override
public void getClassIndexes(final Collection<OIndex<?>> indexes) {
acquireSchemaReadLock();
try {
final OIndexManagerProxy idxManager = getDatabase().getMetadata().getIndexManager();
if (idxManager == null)
return;
idxManager.getClassIndexes(name, indexes);
} finally {
releaseSchemaReadLock();
}
}
@Override
public OIndex<?> getAutoShardingIndex() {
final ODatabaseDocumentInternal db = ODatabaseRecordThreadLocal.INSTANCE.getIfDefined();
return db != null ? db.getMetadata().getIndexManager().getClassAutoShardingIndex(name) : null;
}
public void onPostIndexManagement() {
final OIndex<?> autoShardingIndex = getAutoShardingIndex();
if (autoShardingIndex != null) {
// OVERRIDE CLUSTER SELECTION
setClusterSelectionInternal(new OAutoShardingClusterSelectionStrategy(this, autoShardingIndex));
} else if (clusterSelection instanceof OAutoShardingClusterSelectionStrategy)
// REMOVE AUTO SHARDING CLUSTER SELECTION
setClusterSelectionInternal(new ORoundRobinClusterSelectionStrategy());
}
@Override
public void getIndexes(final Collection<OIndex<?>> indexes) {
acquireSchemaReadLock();
try {
getClassIndexes(indexes);
for (OClass superClass : superClasses) {
superClass.getIndexes(indexes);
}
} finally {
releaseSchemaReadLock();
}
}
public Set<OIndex<?>> getIndexes() {
Set<OIndex<?>> indexes = new HashSet<OIndex<?>>();
getIndexes(indexes);
return indexes;
}
public void acquireSchemaReadLock() {
owner.acquireSchemaReadLock();
}
public void releaseSchemaReadLock() {
owner.releaseSchemaReadLock();
}
public void acquireSchemaWriteLock() {
owner.acquireSchemaWriteLock();
}
public void releaseSchemaWriteLock() {
releaseSchemaWriteLock(true);
}
public void releaseSchemaWriteLock(final boolean iSave) {
calculateHashCode();
owner.releaseSchemaWriteLock(iSave);
}
public void checkEmbedded() {
owner.checkEmbedded(getDatabase().getStorage().getUnderlying().getUnderlying());
}
public void setClusterSelectionInternal(final String clusterSelection) {
// AVOID TO CHECK THIS IN LOCK TO AVOID RE-GENERATION OF IMMUTABLE SCHEMAS
if (this.clusterSelection.getName().equals(clusterSelection))
// NO CHANGES
return;
acquireSchemaWriteLock();
try {
checkEmbedded();
this.clusterSelection = owner.getClusterSelectionFactory().newInstance(clusterSelection);
} finally {
releaseSchemaWriteLock();
}
}
public void setClusterSelectionInternal(final OClusterSelectionStrategy iClusterSelection) {
// AVOID TO CHECK THIS IN LOCK TO AVOID RE-GENERATION OF IMMUTABLE SCHEMAS
if (this.clusterSelection.getName().equals(iClusterSelection.getName()))
// NO CHANGES
return;
acquireSchemaWriteLock();
try {
checkEmbedded();
this.clusterSelection = iClusterSelection;
} finally {
releaseSchemaWriteLock(false);
}
}
public void fireDatabaseMigration(final ODatabaseDocument database, final String propertyName, final OType type) {
final boolean strictSQL = ((ODatabaseInternal) database).getStorage().getConfiguration().isStrictSql();
database.query(new OSQLAsynchQuery<Object>("select from " + getEscapedName(name, strictSQL) + " where "
+ getEscapedName(propertyName, strictSQL) + ".type() <> \"" + type.name() + "\"", new OCommandResultListener() {
@Override
public boolean result(Object iRecord) {
final ODocument record = ((OIdentifiable) iRecord).getRecord();
record.field(propertyName, record.field(propertyName), type);
database.save(record);
return true;
}
@Override
public void end() {
}
@Override
public Object getResult() {
return null;
}
}));
}
public void firePropertyNameMigration(final ODatabaseDocument database, final String propertyName, final String newPropertyName,
final OType type) {
final boolean strictSQL = ((ODatabaseInternal) database).getStorage().getConfiguration().isStrictSql();
database.query(new OSQLAsynchQuery<Object>(
"select from " + getEscapedName(name, strictSQL) + " where " + getEscapedName(propertyName, strictSQL) + " is not null ",
new OCommandResultListener() {
@Override
public boolean result(Object iRecord) {
final ODocument record = ((OIdentifiable) iRecord).getRecord();
record.setFieldType(propertyName, type);
record.field(newPropertyName, record.field(propertyName), type);
database.save(record);
return true;
}
@Override
public void end() {
}
@Override
public Object getResult() {
return null;
}
}));
}
public void checkPersistentPropertyType(final ODatabaseInternal<ORecord> database, final String propertyName, final OType type) {
final boolean strictSQL = database.getStorage().getConfiguration().isStrictSql();
final StringBuilder builder = new StringBuilder(256);
builder.append("select count(*) from ");
builder.append(getEscapedName(name, strictSQL));
builder.append(" where ");
builder.append(getEscapedName(propertyName, strictSQL));
builder.append(".type() not in [");
final Iterator<OType> cur = type.getCastable().iterator();
while (cur.hasNext()) {
builder.append('"').append(cur.next().name()).append('"');
if (cur.hasNext())
builder.append(",");
}
builder.append("] and ").append(getEscapedName(propertyName, strictSQL)).append(" is not null ");
if (type.isMultiValue())
builder.append(" and ").append(getEscapedName(propertyName, strictSQL)).append(".size() <> 0 limit 1");
final List<ODocument> res = database.command(new OCommandSQL(builder.toString())).execute();
if (((Long) res.get(0).field("count")) > 0)
throw new OSchemaException("The database contains some schema-less data in the property '" + name + "." + propertyName
+ "' that is not compatible with the type " + type + ". Fix those records and change the schema again");
}
protected String getEscapedName(final String iName, final boolean iStrictSQL) {
if (iStrictSQL)
// ESCAPE NAME
return "`" + iName + "`";
return iName;
}
public OSchemaShared getOwner() {
return owner;
}
private void calculateHashCode() {
int result = super.hashCode();
result = 31 * result + (name != null ? name.hashCode() : 0);
hashCode = result;
}
private void setOverSizeInternal(final float overSize) {
getDatabase().checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
acquireSchemaWriteLock();
try {
checkEmbedded();
this.overSize = overSize;
} finally {
releaseSchemaWriteLock();
}
}
private void setCustomInternal(final String name, final String value) {
acquireSchemaWriteLock();
try {
checkEmbedded();
if (customFields == null)
customFields = new HashMap<String, String>();
if (value == null || "null".equalsIgnoreCase(value))
customFields.remove(name);
else
customFields.put(name, value);
} finally {
releaseSchemaWriteLock();
}
}
private void clearCustomInternal() {
acquireSchemaWriteLock();
try {
checkEmbedded();
customFields = null;
} finally {
releaseSchemaWriteLock();
}
}
private void setNameInternal(final String name) {
getDatabase().checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
acquireSchemaWriteLock();
try {
checkEmbedded();
final String oldName = this.name;
owner.changeClassName(this.name, name, this);
this.name = name;
ODatabaseDocumentInternal database = getDatabase();
final OStorage storage = database.getStorage();
if (!database.getStorageVersions().classesAreDetectedByClusterId()) {
for (int clusterId : clusterIds) {
long[] range = storage.getClusterDataRange(clusterId);
OPhysicalPosition[] positions = storage.ceilingPhysicalPositions(clusterId, new OPhysicalPosition(range[0]));
do {
for (OPhysicalPosition position : positions) {
final ORecordId identity = new ORecordId(clusterId, position.clusterPosition);
final ORawBuffer record = storage.readRecord(identity, null, true, null).getResult();
if (record.recordType == ODocument.RECORD_TYPE) {
final ORecordSerializerSchemaAware2CSV serializer = (ORecordSerializerSchemaAware2CSV) ORecordSerializerFactory
.instance().getFormat(ORecordSerializerSchemaAware2CSV.NAME);
String persName = new String(record.buffer, "UTF-8");
if (serializer.getClassName(persName).equalsIgnoreCase(name)) {
final ODocument document = new ODocument();
document.setLazyLoad(false);
document.fromStream(record.buffer);
ORecordInternal.setVersion(document, record.version);
ORecordInternal.setIdentity(document, identity);
document.setClassName(name);
document.setDirty();
document.save();
}
}
if (positions.length > 0)
positions = storage.higherPhysicalPositions(clusterId, positions[positions.length - 1]);
}
} while (positions.length > 0);
}
}
renameCluster(oldName, this.name);
} catch (UnsupportedEncodingException e) {
throw OException.wrapException(new OSchemaException("Error reading schema"), e);
} finally {
releaseSchemaWriteLock();
}
}
private void renameCluster(String oldName, String newName) {
oldName = oldName.toLowerCase();
newName = newName.toLowerCase();
final ODatabaseDocumentInternal database = getDatabase();
final OStorage storage = database.getStorage();
if (storage.getClusterIdByName(newName) != -1)
return;
final int clusterId = storage.getClusterIdByName(oldName);
if (clusterId == -1)
return;
if (!hasClusterId(clusterId))
return;
database.command(new OCommandSQL("alter cluster " + oldName + " name " + newName)).execute();
}
private void setShortNameInternal(final String iShortName) {
getDatabase().checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
acquireSchemaWriteLock();
try {
checkEmbedded();
String oldName = null;
if (this.shortName != null)
oldName = this.shortName;
owner.changeClassName(oldName, iShortName, this);
this.shortName = iShortName;
} finally {
releaseSchemaWriteLock();
}
}
private void setDescriptionInternal(final String iDescription) {
acquireSchemaWriteLock();
try {
checkEmbedded();
this.description = iDescription;
} finally {
releaseSchemaWriteLock();
}
}
private void dropPropertyInternal(final String iPropertyName) {
if (getDatabase().getTransaction().isActive())
throw new IllegalStateException("Cannot drop a property inside a transaction");
getDatabase().checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_DELETE);
acquireSchemaWriteLock();
try {
checkEmbedded();
final OProperty prop = properties.remove(iPropertyName.toLowerCase());
if (prop == null)
throw new OSchemaException("Property '" + iPropertyName + "' not found in class " + name + "'");
} finally {
releaseSchemaWriteLock();
}
}
private int createClusterIfNeeded(String nameOrId) {
final String[] parts = nameOrId.split(" ");
int clId = getClusterId(parts[0]);
if (clId == NOT_EXISTENT_CLUSTER_ID) {
if (!parts[0].isEmpty() && Character.isDigit(parts[0].charAt(0)))
try {
clId = Integer.parseInt(parts[0]);
throw new IllegalArgumentException("Cluster id '" + clId + "' cannot be added");
} catch (NumberFormatException e) {
clId = getDatabase().addCluster(parts[0]);
}
else
clId = getDatabase().addCluster(parts[0]);
}
return clId;
}
private OClass addClusterIdInternal(final int clusterId) {
acquireSchemaWriteLock();
try {
checkEmbedded();
owner.checkClusterCanBeAdded(clusterId, this);
for (int currId : clusterIds)
if (currId == clusterId)
// ALREADY ADDED
return this;
clusterIds = OArrays.copyOf(clusterIds, clusterIds.length + 1);
clusterIds[clusterIds.length - 1] = clusterId;
Arrays.sort(clusterIds);
addPolymorphicClusterId(clusterId);
if (defaultClusterId == NOT_EXISTENT_CLUSTER_ID)
defaultClusterId = clusterId;
owner.addClusterForClass(clusterId, this);
return this;
} finally {
releaseSchemaWriteLock();
}
}
private void addPolymorphicClusterId(int clusterId) {
if (Arrays.binarySearch(polymorphicClusterIds, clusterId) >= 0)
return;
polymorphicClusterIds = OArrays.copyOf(polymorphicClusterIds, polymorphicClusterIds.length + 1);
polymorphicClusterIds[polymorphicClusterIds.length - 1] = clusterId;
Arrays.sort(polymorphicClusterIds);
addClusterIdToIndexes(clusterId);
for (OClassImpl superClass : superClasses) {
superClass.addPolymorphicClusterId(clusterId);
}
}
private OClass removeClusterIdInternal(final int clusterToRemove) {
acquireSchemaWriteLock();
try {
checkEmbedded();
boolean found = false;
for (int clusterId : clusterIds) {
if (clusterId == clusterToRemove) {
found = true;
break;
}
}
if (found) {
final int[] newClusterIds = new int[clusterIds.length - 1];
for (int i = 0, k = 0; i < clusterIds.length; ++i) {
if (clusterIds[i] == clusterToRemove)
// JUMP IT
continue;
newClusterIds[k] = clusterIds[i];
k++;
}
clusterIds = newClusterIds;
removePolymorphicClusterId(clusterToRemove);
}
if (defaultClusterId == clusterToRemove) {
if (clusterIds.length >= 1)
defaultClusterId = clusterIds[0];
else
defaultClusterId = NOT_EXISTENT_CLUSTER_ID;
}
owner.removeClusterForClass(clusterToRemove, this);
} finally {
releaseSchemaWriteLock();
}
return this;
}
private void setAbstractInternal(final boolean isAbstract) {
getDatabase().checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
acquireSchemaWriteLock();
try {
if (isAbstract) {
// SWITCH TO ABSTRACT
if (defaultClusterId != NOT_EXISTENT_CLUSTER_ID) {
// CHECK
if (count() > 0)
throw new IllegalStateException("Cannot set the class as abstract because contains records.");
tryDropCluster(defaultClusterId);
for (int clusterId : getClusterIds()) {
tryDropCluster(clusterId);
removePolymorphicClusterId(clusterId);
owner.removeClusterForClass(clusterId, this);
}
setClusterIds(new int[] { NOT_EXISTENT_CLUSTER_ID });
defaultClusterId = NOT_EXISTENT_CLUSTER_ID;
}
} else {
if (!abstractClass)
return;
int clusterId = getDatabase().getClusterIdByName(name);
if (clusterId == -1)
clusterId = getDatabase().addCluster(name);
this.defaultClusterId = clusterId;
this.clusterIds[0] = this.defaultClusterId;
}
this.abstractClass = isAbstract;
} finally {
releaseSchemaWriteLock();
}
}
private void setStrictModeInternal(final boolean iStrict) {
getDatabase().checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
acquireSchemaWriteLock();
try {
checkEmbedded();
this.strictMode = iStrict;
} finally {
releaseSchemaWriteLock();
}
}
private OProperty addProperty(final String propertyName, final OType type, final OType linkedType, final OClass linkedClass,
final boolean unsafe) {
if (type == null)
throw new OSchemaException("Property type not defined.");
if (propertyName == null || propertyName.length() == 0)
throw new OSchemaException("Property name is null or empty");
if (getDatabase().getStorage().getConfiguration().isStrictSql()) {
validatePropertyName(propertyName);
}
if (getDatabase().getTransaction().isActive())
throw new OSchemaException("Cannot create property '" + propertyName + "' inside a transaction");
final ODatabaseDocumentInternal database = getDatabase();
database.checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
if (linkedType != null)
OPropertyImpl.checkLinkTypeSupport(type);
if (linkedClass != null)
OPropertyImpl.checkSupportLinkedClass(type);
OProperty property = null;
acquireSchemaWriteLock();
try {
final StringBuilder cmd = new StringBuilder("create property ");
// CLASS.PROPERTY NAME
if (getDatabase().getStorage().getConfiguration().isStrictSql())
cmd.append('`');
cmd.append(name);
if (getDatabase().getStorage().getConfiguration().isStrictSql())
cmd.append('`');
cmd.append('.');
if (getDatabase().getStorage().getConfiguration().isStrictSql())
cmd.append('`');
cmd.append(propertyName);
if (getDatabase().getStorage().getConfiguration().isStrictSql())
cmd.append('`');
// TYPE
cmd.append(' ');
cmd.append(type.name);
if (linkedType != null) {
// TYPE
cmd.append(' ');
cmd.append(linkedType.name);
} else if (linkedClass != null) {
// TYPE
cmd.append(' ');
if (getDatabase().getStorage().getConfiguration().isStrictSql())
cmd.append('`');
cmd.append(linkedClass.getName());
if (getDatabase().getStorage().getConfiguration().isStrictSql())
cmd.append('`');
}
if (unsafe)
cmd.append(" unsafe ");
final OStorage storage = database.getStorage();
if (storage instanceof OStorageProxy) {
database.command(new OCommandSQL(cmd.toString())).execute();
reload();
return getProperty(propertyName);
} else if (isDistributedCommand()) {
final OCommandSQL commandSQL = new OCommandSQL(cmd.toString());
commandSQL.addExcludedNode(((OAutoshardedStorage) storage).getNodeId());
database.command(commandSQL).execute();
property = addPropertyInternal(propertyName, type, linkedType, linkedClass, unsafe);
} else
property = addPropertyInternal(propertyName, type, linkedType, linkedClass, unsafe);
} finally {
releaseSchemaWriteLock();
}
return property;
}
private void validatePropertyName(final String propertyName) {
}
private int getClusterId(final String stringValue) {
int clId;
if (!stringValue.isEmpty() && Character.isDigit(stringValue.charAt(0)))
try {
clId = Integer.parseInt(stringValue);
} catch (NumberFormatException e) {
clId = getDatabase().getClusterIdByName(stringValue);
}
else
clId = getDatabase().getClusterIdByName(stringValue);
return clId;
}
private void addClusterIdToIndexes(int iId) {
if (getDatabase().getStorage().getUnderlying() instanceof OAbstractPaginatedStorage) {
final String clusterName = getDatabase().getClusterNameById(iId);
final List<String> indexesToAdd = new ArrayList<String>();
for (OIndex<?> index : getIndexes())
indexesToAdd.add(index.getName());
final OIndexManager indexManager = getDatabase().getMetadata().getIndexManager();
for (String indexName : indexesToAdd)
indexManager.addClusterToIndex(clusterName, indexName);
}
}
/**
* Adds a base class to the current one. It adds also the base class cluster ids to the polymorphic cluster ids array.
*
* @param iBaseClass
* The base class to add.
*/
private OClass addBaseClass(final OClassImpl iBaseClass) {
checkRecursion(iBaseClass);
checkParametersConflict(iBaseClass);
if (subclasses == null)
subclasses = new ArrayList<OClass>();
if (subclasses.contains(iBaseClass))
return this;
subclasses.add(iBaseClass);
addPolymorphicClusterIdsWithInheritance(iBaseClass);
return this;
}
private void checkParametersConflict(final OClass baseClass) {
final Collection<OProperty> baseClassProperties = baseClass.properties();
for (OProperty property : baseClassProperties) {
OProperty thisProperty = getProperty(property.getName());
if (thisProperty != null && !thisProperty.getType().equals(property.getType())) {
throw new OSchemaException("Cannot add base class '" + baseClass.getName() + "', because of property conflict: '"
+ thisProperty + "' vs '" + property + "'");
}
}
}
private void checkParametersConflict(List<OClassImpl> classes) {
final Map<String, OProperty> commulative = new HashMap<String, OProperty>();
final Map<String, OProperty> properties = new HashMap<String, OProperty>();
for (OClassImpl superClass : classes) {
superClass.propertiesMap(properties, false);
for (Map.Entry<String, OProperty> entry : properties.entrySet()) {
if (commulative.containsKey(entry.getKey())) {
final String property = entry.getKey();
final OProperty existingProperty = commulative.get(property);
if (!existingProperty.getType().equals(entry.getValue().getType())) {
throw new OSchemaException("Properties conflict detected: '" + existingProperty + "] vs [" + entry.getValue() + "]");
}
}
}
commulative.putAll(properties);
properties.clear();
}
}
private void checkRecursion(final OClass baseClass) {
if (isSubClassOf(baseClass)) {
throw new OSchemaException("Cannot add base class '" + baseClass.getName() + "', because of recursion");
}
}
private void removePolymorphicClusterIds(final OClassImpl iBaseClass) {
for (final int clusterId : iBaseClass.polymorphicClusterIds)
removePolymorphicClusterId(clusterId);
}
private void removePolymorphicClusterId(final int clusterId) {
final int index = Arrays.binarySearch(polymorphicClusterIds, clusterId);
if (index < 0)
return;
if (index < polymorphicClusterIds.length - 1)
System.arraycopy(polymorphicClusterIds, index + 1, polymorphicClusterIds, index, polymorphicClusterIds.length - (index + 1));
polymorphicClusterIds = Arrays.copyOf(polymorphicClusterIds, polymorphicClusterIds.length - 1);
removeClusterFromIndexes(clusterId);
for (OClassImpl superClass : superClasses) {
superClass.removePolymorphicClusterId(clusterId);
}
}
private void removeClusterFromIndexes(final int iId) {
if (getDatabase().getStorage().getUnderlying() instanceof OAbstractPaginatedStorage) {
final String clusterName = getDatabase().getClusterNameById(iId);
final List<String> indexesToRemove = new ArrayList<String>();
for (final OIndex<?> index : getIndexes())
indexesToRemove.add(index.getName());
final OIndexManager indexManager = getDatabase().getMetadata().getIndexManager();
for (final String indexName : indexesToRemove)
indexManager.removeClusterFromIndex(clusterName, indexName);
}
}
private void tryDropCluster(final int defaultClusterId) {
if (name.toLowerCase().equals(getDatabase().getClusterNameById(defaultClusterId))) {
// DROP THE DEFAULT CLUSTER CALLED WITH THE SAME NAME ONLY IF EMPTY
if (getDatabase().getClusterRecordSizeById(defaultClusterId) == 0)
getDatabase().dropCluster(defaultClusterId, true);
}
}
private ODatabaseDocumentInternal getDatabase() {
return ODatabaseRecordThreadLocal.INSTANCE.get();
}
/**
* Add different cluster id to the "polymorphic cluster ids" array.
*/
private void addPolymorphicClusterIds(final OClassImpl iBaseClass) {
boolean found;
for (int i : iBaseClass.polymorphicClusterIds) {
found = false;
for (int k : polymorphicClusterIds) {
if (i == k) {
found = true;
break;
}
}
if (!found) {
int[] oldClusterId = polymorphicClusterIds;
// ADD IT
polymorphicClusterIds = OArrays.copyOf(polymorphicClusterIds, polymorphicClusterIds.length + 1);
polymorphicClusterIds[polymorphicClusterIds.length - 1] = i;
Arrays.sort(polymorphicClusterIds);
try {
addClusterIdToIndexes(i);
} catch (Exception e) {
polymorphicClusterIds = oldClusterId;
}
}
}
}
private void addPolymorphicClusterIdsWithInheritance(final OClassImpl iBaseClass) {
addPolymorphicClusterIds(iBaseClass);
for (OClassImpl superClass : superClasses) {
superClass.addPolymorphicClusterIdsWithInheritance(iBaseClass);
}
}
public List<OType> extractFieldTypes(final String[] fieldNames) {
final List<OType> types = new ArrayList<OType>(fieldNames.length);
for (String fieldName : fieldNames) {
if (!fieldName.equals("@rid"))
types.add(getProperty(OIndexDefinitionFactory.extractFieldName(fieldName).toLowerCase()).getType());
else
types.add(OType.LINK);
}
return types;
}
private OClass setClusterIds(final int[] iClusterIds) {
clusterIds = iClusterIds;
Arrays.sort(clusterIds);
return this;
}
private boolean isDistributedCommand() {
return getDatabase().getStorage() instanceof OAutoshardedStorage
&& OScenarioThreadLocal.INSTANCE.get() != OScenarioThreadLocal.RUN_MODE.RUNNING_DISTRIBUTED;
}
}
| core/src/main/java/com/orientechnologies/orient/core/metadata/schema/OClassImpl.java | /*
*
* * Copyright 2014 Orient Technologies LTD (info(at)orientechnologies.com)
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
* * For more information: http://www.orientechnologies.com
*
*/
package com.orientechnologies.orient.core.metadata.schema;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;
import com.orientechnologies.common.exception.OException;
import com.orientechnologies.common.listener.OProgressListener;
import com.orientechnologies.common.util.OArrays;
import com.orientechnologies.common.util.OCommonConst;
import com.orientechnologies.orient.core.annotation.OBeforeSerialization;
import com.orientechnologies.orient.core.command.OCommandResultListener;
import com.orientechnologies.orient.core.db.ODatabaseDocumentInternal;
import com.orientechnologies.orient.core.db.ODatabaseInternal;
import com.orientechnologies.orient.core.db.ODatabaseRecordThreadLocal;
import com.orientechnologies.orient.core.db.OScenarioThreadLocal;
import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.db.record.ORecordElement;
import com.orientechnologies.orient.core.exception.OSchemaException;
import com.orientechnologies.orient.core.exception.OSecurityAccessException;
import com.orientechnologies.orient.core.exception.OSecurityException;
import com.orientechnologies.orient.core.id.ORecordId;
import com.orientechnologies.orient.core.index.*;
import com.orientechnologies.orient.core.metadata.schema.clusterselection.OClusterSelectionStrategy;
import com.orientechnologies.orient.core.metadata.schema.clusterselection.ORoundRobinClusterSelectionStrategy;
import com.orientechnologies.orient.core.metadata.security.ORole;
import com.orientechnologies.orient.core.metadata.security.ORule;
import com.orientechnologies.orient.core.metadata.security.OSecurityShared;
import com.orientechnologies.orient.core.metadata.security.OSecurityUser;
import com.orientechnologies.orient.core.record.ORecord;
import com.orientechnologies.orient.core.record.ORecordInternal;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.serialization.serializer.record.ORecordSerializerFactory;
import com.orientechnologies.orient.core.serialization.serializer.record.string.ORecordSerializerSchemaAware2CSV;
import com.orientechnologies.orient.core.sharding.auto.OAutoShardingClusterSelectionStrategy;
import com.orientechnologies.orient.core.sql.OCommandSQL;
import com.orientechnologies.orient.core.sql.query.OSQLAsynchQuery;
import com.orientechnologies.orient.core.storage.*;
import com.orientechnologies.orient.core.storage.impl.local.OAbstractPaginatedStorage;
import com.orientechnologies.orient.core.type.ODocumentWrapper;
import com.orientechnologies.orient.core.type.ODocumentWrapperNoClass;
/**
* Schema Class implementation.
*
* @author Luca Garulli (l.garulli--at--orientechnologies.com)
*/
@SuppressWarnings("unchecked")
public class OClassImpl extends ODocumentWrapperNoClass implements OClass {
private static final long serialVersionUID = 1L;
private static final int NOT_EXISTENT_CLUSTER_ID = -1;
final OSchemaShared owner;
private final Map<String, OProperty> properties = new HashMap<String, OProperty>();
private int defaultClusterId = NOT_EXISTENT_CLUSTER_ID;
private String name;
private String description;
private int[] clusterIds;
private List<OClassImpl> superClasses = new ArrayList<OClassImpl>();
private int[] polymorphicClusterIds;
private List<OClass> subclasses;
private float overSize = 0f;
private String shortName;
private boolean strictMode = false; // @SINCE v1.0rc8
private boolean abstractClass = false; // @SINCE v1.2.0
private Map<String, String> customFields;
private volatile OClusterSelectionStrategy clusterSelection; // @SINCE 1.7
private volatile int hashCode;
private static Set<String> reserved = new HashSet<String>();
static {
// reserved.add("select");
reserved.add("traverse");
reserved.add("insert");
reserved.add("update");
reserved.add("delete");
reserved.add("from");
reserved.add("where");
reserved.add("skip");
reserved.add("limit");
reserved.add("timeout");
}
/**
* Constructor used in unmarshalling.
*/
protected OClassImpl(final OSchemaShared iOwner, final String iName) {
this(iOwner, new ODocument().setTrackingChanges(false), iName);
}
protected OClassImpl(final OSchemaShared iOwner, final String iName, final int[] iClusterIds) {
this(iOwner, iName);
setClusterIds(iClusterIds);
defaultClusterId = iClusterIds[0];
if (defaultClusterId == NOT_EXISTENT_CLUSTER_ID)
abstractClass = true;
if (abstractClass)
setPolymorphicClusterIds(OCommonConst.EMPTY_INT_ARRAY);
else
setPolymorphicClusterIds(iClusterIds);
clusterSelection = owner.getClusterSelectionFactory().newInstanceOfDefaultClass();
}
/**
* Constructor used in unmarshalling.
*/
protected OClassImpl(final OSchemaShared iOwner, final ODocument iDocument, final String iName) {
name = iName;
document = iDocument;
owner = iOwner;
}
public static int[] readableClusters(final ODatabaseDocument iDatabase, final int[] iClusterIds) {
List<Integer> listOfReadableIds = new ArrayList<Integer>();
boolean all = true;
for (int clusterId : iClusterIds) {
try {
final String clusterName = iDatabase.getClusterNameById(clusterId);
iDatabase.checkSecurity(ORule.ResourceGeneric.CLUSTER, ORole.PERMISSION_READ, clusterName);
listOfReadableIds.add(clusterId);
} catch (OSecurityAccessException securityException) {
all = false;
// if the cluster is inaccessible it's simply not processed in the list.add
}
}
if (all)
// JUST RETURN INPUT ARRAY (FASTER)
return iClusterIds;
final int[] readableClusterIds = new int[listOfReadableIds.size()];
int index = 0;
for (int clusterId : listOfReadableIds) {
readableClusterIds[index++] = clusterId;
}
return readableClusterIds;
}
@Override
public OClusterSelectionStrategy getClusterSelection() {
acquireSchemaReadLock();
try {
return clusterSelection;
} finally {
releaseSchemaReadLock();
}
}
@Override
public OClass setClusterSelection(final OClusterSelectionStrategy clusterSelection) {
return setClusterSelection(clusterSelection.getName());
}
@Override
public OClass setClusterSelection(final String value) {
getDatabase().checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
acquireSchemaWriteLock();
try {
final ODatabaseDocumentInternal database = getDatabase();
final OStorage storage = database.getStorage();
if (storage instanceof OStorageProxy) {
final String cmd = String.format("alter class %s clusterselection %s", name, value);
database.command(new OCommandSQL(cmd)).execute();
} else if (isDistributedCommand()) {
final String cmd = String.format("alter class %s clusterselection %s", name, value);
OCommandSQL commandSQL = new OCommandSQL(cmd);
commandSQL.addExcludedNode(((OAutoshardedStorage) storage).getNodeId());
database.command(commandSQL).execute();
setClusterSelectionInternal(value);
} else
setClusterSelectionInternal(value);
return this;
} finally {
releaseSchemaWriteLock();
}
}
@Override
public <RET extends ODocumentWrapper> RET reload() {
return (RET) owner.reload();
}
public String getCustom(final String iName) {
acquireSchemaReadLock();
try {
if (customFields == null)
return null;
return customFields.get(iName);
} finally {
releaseSchemaReadLock();
}
}
public OClassImpl setCustom(final String name, final String value) {
getDatabase().checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
acquireSchemaWriteLock();
try {
final ODatabaseDocumentInternal database = getDatabase();
final OStorage storage = database.getStorage();
if (storage instanceof OStorageProxy) {
final String cmd = String.format("alter class %s custom %s=%s", getName(), name, value);
database.command(new OCommandSQL(cmd)).execute();
} else if (isDistributedCommand()) {
final String cmd = String.format("alter class %s custom %s=%s", getName(), name, value);
final OCommandSQL commandSQL = new OCommandSQL(cmd);
commandSQL.addExcludedNode(((OAutoshardedStorage) storage).getNodeId());
database.command(commandSQL).execute();
setCustomInternal(name, value);
} else
setCustomInternal(name, value);
return this;
} finally {
releaseSchemaWriteLock();
}
}
public Map<String, String> getCustomInternal() {
acquireSchemaReadLock();
try {
if (customFields != null)
return Collections.unmodifiableMap(customFields);
return null;
} finally {
releaseSchemaReadLock();
}
}
public void removeCustom(final String name) {
setCustom(name, null);
}
public void clearCustom() {
getDatabase().checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
acquireSchemaWriteLock();
try {
final ODatabaseDocumentInternal database = getDatabase();
final OStorage storage = database.getStorage();
if (storage instanceof OStorageProxy) {
final String cmd = String.format("alter class %s custom clear", getName());
database.command(new OCommandSQL(cmd)).execute();
} else if (isDistributedCommand()) {
final String cmd = String.format("alter class %s custom clear", getName());
final OCommandSQL commandSQL = new OCommandSQL(cmd);
commandSQL.addExcludedNode(((OAutoshardedStorage) storage).getNodeId());
database.command(commandSQL).execute();
clearCustomInternal();
} else
clearCustomInternal();
} finally {
releaseSchemaWriteLock();
}
}
public Set<String> getCustomKeys() {
acquireSchemaReadLock();
try {
if (customFields != null)
return Collections.unmodifiableSet(customFields.keySet());
return new HashSet<String>();
} finally {
releaseSchemaReadLock();
}
}
@Override
public boolean hasClusterId(final int clusterId) {
return Arrays.binarySearch(clusterIds, clusterId) >= 0;
}
@Override
public boolean hasPolymorphicClusterId(final int clusterId) {
return Arrays.binarySearch(polymorphicClusterIds, clusterId) >= 0;
}
@Override
public OClass getSuperClass() {
acquireSchemaReadLock();
try {
return superClasses.isEmpty() ? null : superClasses.get(0);
} finally {
releaseSchemaReadLock();
}
}
@Override
public OClass setSuperClass(OClass iSuperClass) {
setSuperClasses(iSuperClass != null ? Arrays.asList(iSuperClass) : Collections.EMPTY_LIST);
return this;
}
public String getName() {
acquireSchemaReadLock();
try {
return name;
} finally {
releaseSchemaReadLock();
}
}
@Override
public List<OClass> getSuperClasses() {
acquireSchemaReadLock();
try {
return Collections.unmodifiableList((List<? extends OClass>) superClasses);
} finally {
releaseSchemaReadLock();
}
}
@Override
public boolean hasSuperClasses() {
acquireSchemaReadLock();
try {
return !superClasses.isEmpty();
} finally {
releaseSchemaReadLock();
}
}
@Override
public List<String> getSuperClassesNames() {
acquireSchemaReadLock();
try {
List<String> superClassesNames = new ArrayList<String>(superClasses.size());
for (OClassImpl superClass : superClasses) {
superClassesNames.add(superClass.getName());
}
return superClassesNames;
} finally {
releaseSchemaReadLock();
}
}
public OClass setSuperClassesByNames(List<String> classNames) {
if (classNames == null)
classNames = Collections.EMPTY_LIST;
final List<OClass> classes = new ArrayList<OClass>(classNames.size());
final OSchema schema = getDatabase().getMetadata().getSchema();
for (String className : classNames) {
classes.add(schema.getClass(className));
}
return setSuperClasses(classes);
}
@Override
public OClass setSuperClasses(final List<? extends OClass> classes) {
getDatabase().checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
acquireSchemaWriteLock();
try {
final ODatabaseDocumentInternal database = getDatabase();
final OStorage storage = database.getStorage();
final StringBuilder sb = new StringBuilder();
if (classes != null && classes.size() > 0) {
for (OClass superClass : classes) {
sb.append(superClass.getName()).append(',');
}
sb.deleteCharAt(sb.length() - 1);
} else
sb.append("null");
final String cmd = String.format("alter class %s superclasses %s", name, sb);
if (storage instanceof OStorageProxy) {
database.command(new OCommandSQL(cmd)).execute();
} else if (isDistributedCommand()) {
final OCommandSQL commandSQL = new OCommandSQL(cmd);
commandSQL.addExcludedNode(((OAutoshardedStorage) storage).getNodeId());
database.command(commandSQL).execute();
setSuperClassesInternal(classes);
} else
setSuperClassesInternal(classes);
} finally {
releaseSchemaWriteLock();
}
return this;
}
void setSuperClassesInternal(final List<? extends OClass> classes) {
acquireSchemaWriteLock();
try {
List<OClassImpl> newSuperClasses = new ArrayList<OClassImpl>();
OClassImpl cls;
for (OClass superClass : classes) {
if (superClass instanceof OClassAbstractDelegate)
cls = (OClassImpl) ((OClassAbstractDelegate) superClass).delegate;
else
cls = (OClassImpl) superClass;
if (newSuperClasses.contains(cls)) {
throw new OSchemaException("Duplicated superclass '" + cls.getName() + "'");
}
newSuperClasses.add(cls);
}
checkParametersConflict(newSuperClasses);
List<OClassImpl> toAddList = new ArrayList<OClassImpl>(newSuperClasses);
toAddList.removeAll(superClasses);
List<OClassImpl> toRemoveList = new ArrayList<OClassImpl>(superClasses);
toRemoveList.removeAll(newSuperClasses);
for (OClassImpl toRemove : toRemoveList) {
toRemove.removeBaseClassInternal(this);
}
for (OClassImpl addTo : toAddList) {
addTo.addBaseClass(this);
}
superClasses.clear();
superClasses.addAll(newSuperClasses);
} finally {
releaseSchemaWriteLock();
}
}
@Override
public OClass addSuperClass(final OClass superClass) {
getDatabase().checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
acquireSchemaWriteLock();
try {
final ODatabaseDocumentInternal database = getDatabase();
final OStorage storage = database.getStorage();
if (storage instanceof OStorageProxy) {
final String cmd = String.format("alter class %s superclass +%s", name, superClass != null ? superClass.getName() : null);
database.command(new OCommandSQL(cmd)).execute();
} else if (isDistributedCommand()) {
final String cmd = String.format("alter class %s superclass +%s", name, superClass != null ? superClass.getName() : null);
final OCommandSQL commandSQL = new OCommandSQL(cmd);
commandSQL.addExcludedNode(((OAutoshardedStorage) storage).getNodeId());
database.command(commandSQL).execute();
addSuperClassInternal(superClass);
} else
addSuperClassInternal(superClass);
} finally {
releaseSchemaWriteLock();
}
return this;
}
void addSuperClassInternal(final OClass superClass) {
acquireSchemaWriteLock();
try {
final OClassImpl cls;
if (superClass instanceof OClassAbstractDelegate)
cls = (OClassImpl) ((OClassAbstractDelegate) superClass).delegate;
else
cls = (OClassImpl) superClass;
if (cls != null) {
// CHECK THE USER HAS UPDATE PRIVILEGE AGAINST EXTENDING CLASS
final OSecurityUser user = getDatabase().getUser();
if (user != null)
user.allow(ORule.ResourceGeneric.CLASS, cls.getName(), ORole.PERMISSION_UPDATE);
if (superClasses.contains(superClass)) {
throw new OSchemaException(
"Class: '" + this.getName() + "' already has the class '" + superClass.getName() + "' as superclass");
}
cls.addBaseClass(this);
superClasses.add(cls);
}
} finally {
releaseSchemaWriteLock();
}
}
@Override
public OClass removeSuperClass(OClass superClass) {
getDatabase().checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
acquireSchemaWriteLock();
try {
final ODatabaseDocumentInternal database = getDatabase();
final OStorage storage = database.getStorage();
if (storage instanceof OStorageProxy) {
final String cmd = String.format("alter class %s superclass -%s", name, superClass != null ? superClass.getName() : null);
database.command(new OCommandSQL(cmd)).execute();
} else if (isDistributedCommand()) {
final String cmd = String.format("alter class %s superclass -%s", name, superClass != null ? superClass.getName() : null);
final OCommandSQL commandSQL = new OCommandSQL(cmd);
commandSQL.addExcludedNode(((OAutoshardedStorage) storage).getNodeId());
database.command(commandSQL).execute();
removeSuperClassInternal(superClass);
} else
removeSuperClassInternal(superClass);
} finally {
releaseSchemaWriteLock();
}
return this;
}
void removeSuperClassInternal(final OClass superClass) {
acquireSchemaWriteLock();
try {
final OClassImpl cls;
if (superClass instanceof OClassAbstractDelegate)
cls = (OClassImpl) ((OClassAbstractDelegate) superClass).delegate;
else
cls = (OClassImpl) superClass;
if (superClasses.contains(cls)) {
if (cls != null)
cls.removeBaseClassInternal(this);
superClasses.remove(superClass);
}
} finally {
releaseSchemaWriteLock();
}
}
public OClass setName(final String name) {
if (getName().equals(name))
return this;
getDatabase().checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
final Character wrongCharacter = OSchemaShared.checkClassNameIfValid(name);
OClass oClass = getDatabase().getMetadata().getSchema().getClass(name);
if (oClass != null) {
String error = String.format("Cannot rename class %s to %s. A Class with name %s exists", this.name, name, name);
throw new OSchemaException(error);
}
if (wrongCharacter != null)
throw new OSchemaException(
"Invalid class name found. Character '" + wrongCharacter + "' cannot be used in class name '" + name + "'");
acquireSchemaWriteLock();
try {
final ODatabaseDocumentInternal database = getDatabase();
final OStorage storage = database.getStorage();
if (storage instanceof OStorageProxy) {
final String cmd = String.format("alter class %s name %s", this.name, name);
database.command(new OCommandSQL(cmd)).execute();
} else if (isDistributedCommand()) {
final String cmd = String.format("alter class %s name %s", this.name, name);
final OCommandSQL commandSQL = new OCommandSQL(cmd);
commandSQL.addExcludedNode(((OAutoshardedStorage) storage).getNodeId());
database.command(commandSQL).execute();
setNameInternal(name);
} else
setNameInternal(name);
} finally {
releaseSchemaWriteLock();
}
return this;
}
public long getSize() {
acquireSchemaReadLock();
try {
long size = 0;
for (int clusterId : clusterIds)
size += getDatabase().getClusterRecordSizeById(clusterId);
return size;
} finally {
releaseSchemaReadLock();
}
}
public String getShortName() {
acquireSchemaReadLock();
try {
return shortName;
} finally {
releaseSchemaReadLock();
}
}
public OClass setShortName(String shortName) {
if (shortName != null) {
shortName = shortName.trim();
if (shortName.isEmpty())
shortName = null;
}
getDatabase().checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
acquireSchemaWriteLock();
try {
final ODatabaseDocumentInternal database = getDatabase();
final OStorage storage = database.getStorage();
if (storage instanceof OStorageProxy) {
final String cmd = String.format("alter class %s shortname %s", name, shortName);
database.command(new OCommandSQL(cmd)).execute();
} else if (isDistributedCommand()) {
final String cmd = String.format("alter class %s shortname %s", name, shortName);
final OCommandSQL commandSQL = new OCommandSQL(cmd);
commandSQL.addExcludedNode(((OAutoshardedStorage) storage).getNodeId());
database.command(commandSQL).execute();
setShortNameInternal(shortName);
} else
setShortNameInternal(shortName);
} finally {
releaseSchemaWriteLock();
}
return this;
}
public String getDescription() {
acquireSchemaReadLock();
try {
return description;
} finally {
releaseSchemaReadLock();
}
}
public OClass setDescription(String iDescription) {
if (iDescription != null) {
iDescription = iDescription.trim();
if (iDescription.isEmpty())
iDescription = null;
}
getDatabase().checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
acquireSchemaWriteLock();
try {
final ODatabaseDocumentInternal database = getDatabase();
final OStorage storage = database.getStorage();
if (storage instanceof OStorageProxy) {
final String cmd = String.format("alter class %s description %s", name, shortName);
database.command(new OCommandSQL(cmd)).execute();
} else if (isDistributedCommand()) {
final String cmd = String.format("alter class %s description %s", name, shortName);
final OCommandSQL commandSQL = new OCommandSQL(cmd);
commandSQL.addExcludedNode(((OAutoshardedStorage) storage).getNodeId());
database.command(commandSQL).execute();
setDescriptionInternal(iDescription);
} else
setDescriptionInternal(iDescription);
} finally {
releaseSchemaWriteLock();
}
return this;
}
public String getStreamableName() {
acquireSchemaReadLock();
try {
return shortName != null ? shortName : name;
} finally {
releaseSchemaReadLock();
}
}
public Collection<OProperty> declaredProperties() {
acquireSchemaReadLock();
try {
return Collections.unmodifiableCollection(properties.values());
} finally {
releaseSchemaReadLock();
}
}
public Map<String, OProperty> propertiesMap() {
getDatabase().checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_READ);
acquireSchemaReadLock();
try {
final Map<String, OProperty> props = new HashMap<String, OProperty>(20);
propertiesMap(props, true);
return props;
} finally {
releaseSchemaReadLock();
}
}
private void propertiesMap(Map<String, OProperty> propertiesMap, boolean keepCase) {
for (OProperty p : properties.values()) {
String propName = p.getName();
if (!keepCase)
propName = propName.toLowerCase();
if (!propertiesMap.containsKey(propName))
propertiesMap.put(propName, p);
}
for (OClassImpl superClass : superClasses) {
superClass.propertiesMap(propertiesMap, keepCase);
}
}
public Collection<OProperty> properties() {
getDatabase().checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_READ);
acquireSchemaReadLock();
try {
final Collection<OProperty> props = new ArrayList<OProperty>();
properties(props);
return props;
} finally {
releaseSchemaReadLock();
}
}
private void properties(Collection<OProperty> properties) {
properties.addAll(this.properties.values());
for (OClassImpl superClass : superClasses) {
superClass.properties(properties);
}
}
public void getIndexedProperties(Collection<OProperty> indexedProperties) {
for (OProperty p : properties.values())
if (areIndexed(p.getName()))
indexedProperties.add(p);
for (OClassImpl superClass : superClasses) {
superClass.getIndexedProperties(indexedProperties);
}
}
@Override
public Collection<OProperty> getIndexedProperties() {
getDatabase().checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_READ);
acquireSchemaReadLock();
try {
Collection<OProperty> indexedProps = new HashSet<OProperty>();
getIndexedProperties(indexedProps);
return indexedProps;
} finally {
releaseSchemaReadLock();
}
}
public OProperty getProperty(String propertyName) {
acquireSchemaReadLock();
try {
propertyName = propertyName.toLowerCase();
OProperty p = properties.get(propertyName);
if (p != null)
return p;
for (int i = 0; i < superClasses.size() && p == null; i++) {
p = superClasses.get(i).getProperty(propertyName);
}
return p;
} finally {
releaseSchemaReadLock();
}
}
public OProperty createProperty(final String iPropertyName, final OType iType) {
return addProperty(iPropertyName, iType, null, null, false);
}
public OProperty createProperty(final String iPropertyName, final OType iType, final OClass iLinkedClass) {
if (iLinkedClass == null)
throw new OSchemaException("Missing linked class");
return addProperty(iPropertyName, iType, null, iLinkedClass, false);
}
public OProperty createProperty(final String iPropertyName, final OType iType, final OClass iLinkedClass, final boolean unsafe) {
if (iLinkedClass == null)
throw new OSchemaException("Missing linked class");
return addProperty(iPropertyName, iType, null, iLinkedClass, unsafe);
}
public OProperty createProperty(final String iPropertyName, final OType iType, final OType iLinkedType) {
return addProperty(iPropertyName, iType, iLinkedType, null, false);
}
public OProperty createProperty(final String iPropertyName, final OType iType, final OType iLinkedType, final boolean unsafe) {
return addProperty(iPropertyName, iType, iLinkedType, null, unsafe);
}
@Override
public boolean existsProperty(String propertyName) {
acquireSchemaReadLock();
try {
propertyName = propertyName.toLowerCase();
boolean result = properties.containsKey(propertyName);
if (result)
return true;
for (OClassImpl superClass : superClasses) {
result = superClass.existsProperty(propertyName);
if (result)
return true;
}
return false;
} finally {
releaseSchemaReadLock();
}
}
public void dropProperty(final String propertyName) {
if (getDatabase().getTransaction().isActive())
throw new IllegalStateException("Cannot drop a property inside a transaction");
getDatabase().checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_DELETE);
final String lowerName = propertyName.toLowerCase();
acquireSchemaWriteLock();
try {
if (!properties.containsKey(lowerName))
throw new OSchemaException("Property '" + propertyName + "' not found in class " + name + "'");
final ODatabaseDocumentInternal database = getDatabase();
final OStorage storage = database.getStorage();
if (storage instanceof OStorageProxy) {
database.command(new OCommandSQL("drop property " + name + '.' + propertyName)).execute();
} else if (isDistributedCommand()) {
final OCommandSQL commandSQL = new OCommandSQL("drop property " + name + '.' + propertyName);
commandSQL.addExcludedNode(((OAutoshardedStorage) storage).getNodeId());
database.command(commandSQL).execute();
dropPropertyInternal(propertyName);
} else
dropPropertyInternal(propertyName);
} finally {
releaseSchemaWriteLock();
}
}
@Override
public void fromStream() {
subclasses = null;
superClasses.clear();
name = document.field("name");
if (document.containsField("shortName"))
shortName = document.field("shortName");
else
shortName = null;
if (document.containsField("description"))
description = document.field("description");
else
description = null;
defaultClusterId = document.field("defaultClusterId");
if (document.containsField("strictMode"))
strictMode = document.field("strictMode");
else
strictMode = false;
if (document.containsField("abstract"))
abstractClass = document.field("abstract");
else
abstractClass = false;
if (document.field("overSize") != null)
overSize = document.field("overSize");
else
overSize = 0f;
final Object cc = document.field("clusterIds");
if (cc instanceof Collection<?>) {
final Collection<Integer> coll = document.field("clusterIds");
clusterIds = new int[coll.size()];
int i = 0;
for (final Integer item : coll)
clusterIds[i++] = item;
} else
clusterIds = (int[]) cc;
Arrays.sort(clusterIds);
if (clusterIds.length == 1 && clusterIds[0] == -1)
setPolymorphicClusterIds(OCommonConst.EMPTY_INT_ARRAY);
else
setPolymorphicClusterIds(clusterIds);
// READ PROPERTIES
OPropertyImpl prop;
final Map<String, OProperty> newProperties = new HashMap<String, OProperty>();
final Collection<ODocument> storedProperties = document.field("properties");
if (storedProperties != null)
for (ODocument p : storedProperties) {
prop = new OPropertyImpl(this, p);
prop.fromStream();
if (properties.containsKey(prop.getName())) {
prop = (OPropertyImpl) properties.get(prop.getName().toLowerCase());
prop.fromStream(p);
}
newProperties.put(prop.getName().toLowerCase(), prop);
}
properties.clear();
properties.putAll(newProperties);
customFields = document.field("customFields", OType.EMBEDDEDMAP);
clusterSelection = owner.getClusterSelectionFactory().getStrategy((String) document.field("clusterSelection"));
}
@Override
@OBeforeSerialization
public ODocument toStream() {
document.setInternalStatus(ORecordElement.STATUS.UNMARSHALLING);
try {
document.field("name", name);
document.field("shortName", shortName);
document.field("description", description);
document.field("defaultClusterId", defaultClusterId);
document.field("clusterIds", clusterIds);
document.field("clusterSelection", clusterSelection.getName());
document.field("overSize", overSize);
document.field("strictMode", strictMode);
document.field("abstract", abstractClass);
final Set<ODocument> props = new LinkedHashSet<ODocument>();
for (final OProperty p : properties.values()) {
props.add(((OPropertyImpl) p).toStream());
}
document.field("properties", props, OType.EMBEDDEDSET);
if (superClasses.isEmpty()) {
// Single super class is deprecated!
document.field("superClass", null, OType.STRING);
document.field("superClasses", null, OType.EMBEDDEDLIST);
} else {
// Single super class is deprecated!
document.field("superClass", superClasses.get(0).getName(), OType.STRING);
List<String> superClassesNames = new ArrayList<String>();
for (OClassImpl superClass : superClasses) {
superClassesNames.add(superClass.getName());
}
document.field("superClasses", superClassesNames, OType.EMBEDDEDLIST);
}
document.field("customFields", customFields != null && customFields.size() > 0 ? customFields : null, OType.EMBEDDEDMAP);
} finally {
document.setInternalStatus(ORecordElement.STATUS.LOADED);
}
return document;
}
@Override
public int getClusterForNewInstance(final ODocument doc) {
acquireSchemaReadLock();
try {
return clusterSelection.getCluster(this, doc);
} finally {
releaseSchemaReadLock();
}
}
public int getDefaultClusterId() {
acquireSchemaReadLock();
try {
return defaultClusterId;
} finally {
releaseSchemaReadLock();
}
}
public void setDefaultClusterId(final int defaultClusterId) {
acquireSchemaWriteLock();
try {
checkEmbedded();
this.defaultClusterId = defaultClusterId;
} finally {
releaseSchemaWriteLock();
}
}
public int[] getClusterIds() {
acquireSchemaReadLock();
try {
return clusterIds;
} finally {
releaseSchemaReadLock();
}
}
public int[] getPolymorphicClusterIds() {
acquireSchemaReadLock();
try {
return polymorphicClusterIds;
} finally {
releaseSchemaReadLock();
}
}
private void setPolymorphicClusterIds(final int[] iClusterIds) {
polymorphicClusterIds = iClusterIds;
Arrays.sort(polymorphicClusterIds);
}
public void renameProperty(final String iOldName, final String iNewName) {
final OProperty p = properties.remove(iOldName.toLowerCase());
if (p != null)
properties.put(iNewName.toLowerCase(), p);
}
public OClass addClusterId(final int clusterId) {
getDatabase().checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
if (isAbstract()) {
throw new OSchemaException("Impossible to associate a cluster to an abstract class class");
}
acquireSchemaWriteLock();
try {
final ODatabaseDocumentInternal database = getDatabase();
final OStorage storage = database.getStorage();
if (storage instanceof OStorageProxy) {
final String cmd = String.format("alter class %s addcluster %d", name, clusterId);
database.command(new OCommandSQL(cmd)).execute();
} else if (isDistributedCommand()) {
final String cmd = String.format("alter class %s addcluster %d", name, clusterId);
final OCommandSQL commandSQL = new OCommandSQL(cmd);
commandSQL.addExcludedNode(((OAutoshardedStorage) storage).getNodeId());
database.command(commandSQL).execute();
addClusterIdInternal(clusterId);
} else
addClusterIdInternal(clusterId);
} finally {
releaseSchemaWriteLock();
}
return this;
}
public static OClass addClusters(final OClass cls, final int iClusters) {
final String clusterBase = cls.getName().toLowerCase() + "_";
for (int i = 1; i < iClusters; ++i) {
cls.addCluster(clusterBase + i);
}
return cls;
}
@Override
public OClass addCluster(final String clusterNameOrId) {
getDatabase().checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
if (isAbstract()) {
throw new OSchemaException("Impossible to associate a cluster to an abstract class class");
}
acquireSchemaWriteLock();
try {
final ODatabaseDocumentInternal database = getDatabase();
final OStorage storage = database.getStorage();
if (storage instanceof OStorageProxy) {
final String cmd = String.format("alter class `%s` addcluster `%s`", name, clusterNameOrId);
database.command(new OCommandSQL(cmd)).execute();
} else if (isDistributedCommand()) {
final int clusterId = createClusterIfNeeded(clusterNameOrId);
addClusterIdInternal(clusterId);
final String cmd = String.format("alter class `%s` addcluster `%s`", name, clusterNameOrId);
final OCommandSQL commandSQL = new OCommandSQL(cmd);
commandSQL.addExcludedNode(((OAutoshardedStorage) storage).getNodeId());
database.command(commandSQL).execute();
} else {
final int clusterId = createClusterIfNeeded(clusterNameOrId);
addClusterIdInternal(clusterId);
}
} finally {
releaseSchemaWriteLock();
}
return this;
}
public OClass removeClusterId(final int clusterId) {
getDatabase().checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
acquireSchemaWriteLock();
try {
final ODatabaseDocumentInternal database = getDatabase();
final OStorage storage = database.getStorage();
if (storage instanceof OStorageProxy) {
final String cmd = String.format("alter class %s removecluster %d", name, clusterId);
database.command(new OCommandSQL(cmd)).execute();
} else if (isDistributedCommand()) {
final String cmd = String.format("alter class %s removecluster %d", name, clusterId);
final OCommandSQL commandSQL = new OCommandSQL(cmd);
commandSQL.addExcludedNode(((OAutoshardedStorage) storage).getNodeId());
database.command(commandSQL).execute();
removeClusterIdInternal(clusterId);
} else
removeClusterIdInternal(clusterId);
} finally {
releaseSchemaWriteLock();
}
return this;
}
public Collection<OClass> getSubclasses() {
acquireSchemaReadLock();
try {
if (subclasses == null || subclasses.size() == 0)
return Collections.emptyList();
return Collections.unmodifiableCollection(subclasses);
} finally {
releaseSchemaReadLock();
}
}
public Collection<OClass> getAllSubclasses() {
acquireSchemaReadLock();
try {
final Set<OClass> set = new HashSet<OClass>();
if (subclasses != null) {
set.addAll(subclasses);
for (OClass c : subclasses)
set.addAll(c.getAllSubclasses());
}
return set;
} finally {
releaseSchemaReadLock();
}
}
public Collection<OClass> getBaseClasses() {
return getSubclasses();
}
public Collection<OClass> getAllBaseClasses() {
return getAllSubclasses();
}
@Override
public Collection<OClass> getAllSuperClasses() {
Set<OClass> ret = new HashSet<OClass>();
getAllSuperClasses(ret);
return ret;
}
private void getAllSuperClasses(Set<OClass> set) {
set.addAll(superClasses);
for (OClassImpl superClass : superClasses) {
superClass.getAllSuperClasses(set);
}
}
OClass removeBaseClassInternal(final OClass baseClass) {
acquireSchemaWriteLock();
try {
checkEmbedded();
if (subclasses == null)
return this;
if (subclasses.remove(baseClass))
removePolymorphicClusterIds((OClassImpl) baseClass);
return this;
} finally {
releaseSchemaWriteLock();
}
}
public float getOverSize() {
acquireSchemaReadLock();
try {
if (overSize > 0)
// CUSTOM OVERSIZE SET
return overSize;
// NO OVERSIZE by default
float maxOverSize = 0;
float thisOverSize;
for (OClassImpl superClass : superClasses) {
thisOverSize = superClass.getOverSize();
if (thisOverSize > maxOverSize)
maxOverSize = thisOverSize;
}
return maxOverSize;
} finally {
releaseSchemaReadLock();
}
}
public OClass setOverSize(final float overSize) {
getDatabase().checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
acquireSchemaWriteLock();
try {
final ODatabaseDocumentInternal database = getDatabase();
final OStorage storage = database.getStorage();
if (storage instanceof OStorageProxy) {
// FORMAT FLOAT LOCALE AGNOSTIC
final String cmd = String.format("alter class %s oversize %s", name, new Float(overSize).toString());
database.command(new OCommandSQL(cmd)).execute();
} else if (isDistributedCommand()) {
// FORMAT FLOAT LOCALE AGNOSTIC
final String cmd = String.format("alter class %s oversize %s", name, new Float(overSize).toString());
final OCommandSQL commandSQL = new OCommandSQL(cmd);
commandSQL.addExcludedNode(((OAutoshardedStorage) storage).getNodeId());
database.command(commandSQL).execute();
setOverSizeInternal(overSize);
} else
setOverSizeInternal(overSize);
} finally {
releaseSchemaWriteLock();
}
return this;
}
@Override
public float getClassOverSize() {
acquireSchemaReadLock();
try {
return overSize;
} finally {
releaseSchemaReadLock();
}
}
public boolean isAbstract() {
acquireSchemaReadLock();
try {
return abstractClass;
} finally {
releaseSchemaReadLock();
}
}
public OClass setAbstract(boolean isAbstract) {
getDatabase().checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
acquireSchemaWriteLock();
try {
final ODatabaseDocumentInternal database = getDatabase();
final OStorage storage = database.getStorage();
if (storage instanceof OStorageProxy) {
final String cmd = String.format("alter class %s abstract %s", name, isAbstract);
database.command(new OCommandSQL(cmd)).execute();
} else if (isDistributedCommand()) {
final String cmd = String.format("alter class %s abstract %s", name, isAbstract);
final OCommandSQL commandSQL = new OCommandSQL(cmd);
commandSQL.addExcludedNode(((OAutoshardedStorage) storage).getNodeId());
database.command(commandSQL).execute();
setAbstractInternal(isAbstract);
} else
setAbstractInternal(isAbstract);
} finally {
releaseSchemaWriteLock();
}
return this;
}
public boolean isStrictMode() {
acquireSchemaReadLock();
try {
return strictMode;
} finally {
releaseSchemaReadLock();
}
}
public OClass setStrictMode(final boolean isStrict) {
getDatabase().checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
acquireSchemaWriteLock();
try {
final ODatabaseDocumentInternal database = getDatabase();
final OStorage storage = database.getStorage();
if (storage instanceof OStorageProxy) {
final String cmd = String.format("alter class %s strictmode %s", name, isStrict);
database.command(new OCommandSQL(cmd)).execute();
} else if (isDistributedCommand()) {
final String cmd = String.format("alter class %s strictmode %s", name, isStrict);
final OCommandSQL commandSQL = new OCommandSQL(cmd);
commandSQL.addExcludedNode(((OAutoshardedStorage) storage).getNodeId());
database.command(commandSQL).execute();
setStrictModeInternal(isStrict);
} else
setStrictModeInternal(isStrict);
} finally {
releaseSchemaWriteLock();
}
return this;
}
@Override
public String toString() {
acquireSchemaReadLock();
try {
return name;
} finally {
releaseSchemaReadLock();
}
}
@Override
public boolean equals(Object obj) {
acquireSchemaReadLock();
try {
if (this == obj)
return true;
if (obj == null)
return false;
if (!OClass.class.isAssignableFrom(obj.getClass()))
return false;
final OClass other = (OClass) obj;
if (name == null) {
if (other.getName() != null)
return false;
} else if (!name.equals(other.getName()))
return false;
return true;
} finally {
releaseSchemaReadLock();
}
}
@Override
public int hashCode() {
int sh = hashCode;
if (sh != 0)
return sh;
acquireSchemaReadLock();
try {
sh = hashCode;
if (sh != 0)
return sh;
calculateHashCode();
return hashCode;
} finally {
releaseSchemaReadLock();
}
}
public int compareTo(final OClass o) {
acquireSchemaReadLock();
try {
return name.compareTo(o.getName());
} finally {
releaseSchemaReadLock();
}
}
public long count() {
return count(true);
}
public long count(final boolean isPolymorphic) {
acquireSchemaReadLock();
try {
if (isPolymorphic)
return getDatabase().countClusterElements(readableClusters(getDatabase(), polymorphicClusterIds));
return getDatabase().countClusterElements(readableClusters(getDatabase(), clusterIds));
} finally {
releaseSchemaReadLock();
}
}
/**
* Truncates all the clusters the class uses.
*
* @throws IOException
*/
public void truncate() throws IOException {
getDatabase().checkSecurity(ORule.ResourceGeneric.CLASS, ORole.PERMISSION_UPDATE);
if (isSubClassOf(OSecurityShared.RESTRICTED_CLASSNAME)) {
throw new OSecurityException(
"Class '" + getName() + "' cannot be truncated because has record level security enabled (extends '"
+ OSecurityShared.RESTRICTED_CLASSNAME + "')");
}
final OStorage storage = getDatabase().getStorage();
acquireSchemaReadLock();
try {
for (int id : clusterIds)
storage.getClusterById(id).truncate();
for (OIndex<?> index : getClassIndexes())
index.clear();
Set<OIndex<?>> superclassIndexes = new HashSet<OIndex<?>>();
superclassIndexes.addAll(getIndexes());
superclassIndexes.removeAll(getClassIndexes());
for (OIndex index : superclassIndexes) {
index.rebuild();
}
} finally {
releaseSchemaReadLock();
}
}
/**
* Check if the current instance extends specified schema class.
*
* @param iClassName of class that should be checked
* @return Returns true if the current instance extends the passed schema class (iClass)
* @see #isSuperClassOf(OClass)
*/
public boolean isSubClassOf(final String iClassName) {
acquireSchemaReadLock();
try {
if (iClassName == null)
return false;
if (iClassName.equalsIgnoreCase(getName()) || iClassName.equalsIgnoreCase(getShortName()))
return true;
for (OClassImpl superClass : superClasses) {
if (superClass.isSubClassOf(iClassName))
return true;
}
return false;
} finally {
releaseSchemaReadLock();
}
}
/**
* Check if the current instance extends specified schema class.
*
* @param clazz to check
* @return true if the current instance extends the passed schema class (iClass)
* @see #isSuperClassOf(OClass)
*/
public boolean isSubClassOf(final OClass clazz) {
acquireSchemaReadLock();
try {
if (clazz == null)
return false;
if (equals(clazz))
return true;
for (OClassImpl superClass : superClasses) {
if (superClass.isSubClassOf(clazz))
return true;
}
return false;
} finally {
releaseSchemaReadLock();
}
}
/**
* Returns true if the passed schema class (iClass) extends the current instance.
*
* @param clazz to check
* @return Returns true if the passed schema class extends the current instance
* @see #isSubClassOf(OClass)
*/
public boolean isSuperClassOf(final OClass clazz) {
return clazz != null && clazz.isSubClassOf(this);
}
public Object get(final ATTRIBUTES iAttribute) {
if (iAttribute == null)
throw new IllegalArgumentException("attribute is null");
switch (iAttribute) {
case NAME:
return getName();
case SHORTNAME:
return getShortName();
case SUPERCLASS:
return getSuperClass();
case SUPERCLASSES:
return getSuperClasses();
case OVERSIZE:
return getOverSize();
case STRICTMODE:
return isStrictMode();
case ABSTRACT:
return isAbstract();
case CLUSTERSELECTION:
return getClusterSelection();
case CUSTOM:
return getCustomInternal();
case DESCRIPTION:
return getDescription();
}
throw new IllegalArgumentException("Cannot find attribute '" + iAttribute + "'");
}
public OClass set(final ATTRIBUTES attribute, final Object iValue) {
if (attribute == null)
throw new IllegalArgumentException("attribute is null");
final String stringValue = iValue != null ? iValue.toString() : null;
final boolean isNull = stringValue == null || stringValue.equalsIgnoreCase("NULL");
switch (attribute) {
case NAME:
setName(stringValue);
break;
case SHORTNAME:
setShortName(stringValue);
break;
case SUPERCLASS:
if (stringValue == null)
throw new IllegalArgumentException("Superclass is null");
if (stringValue.startsWith("+")) {
addSuperClass(getDatabase().getMetadata().getSchema().getClass(stringValue.substring(1)));
} else if (stringValue.startsWith("-")) {
removeSuperClass(getDatabase().getMetadata().getSchema().getClass(stringValue.substring(1)));
} else {
setSuperClass(getDatabase().getMetadata().getSchema().getClass(stringValue));
}
break;
case SUPERCLASSES:
setSuperClassesByNames(stringValue != null ? Arrays.asList(stringValue.split(",\\s*")) : null);
break;
case OVERSIZE:
setOverSize(Float.parseFloat(stringValue));
break;
case STRICTMODE:
setStrictMode(Boolean.parseBoolean(stringValue));
break;
case ABSTRACT:
setAbstract(Boolean.parseBoolean(stringValue));
break;
case ADDCLUSTER: {
addCluster(stringValue);
break;
}
case REMOVECLUSTER:
int clId = getClusterId(stringValue);
if (clId == NOT_EXISTENT_CLUSTER_ID)
throw new IllegalArgumentException("Cluster id '" + stringValue + "' cannot be removed");
removeClusterId(clId);
break;
case CLUSTERSELECTION:
setClusterSelection(stringValue);
break;
case CUSTOM:
int indx = stringValue != null ? stringValue.indexOf('=') : -1;
if (indx < 0) {
if (isNull || "clear".equalsIgnoreCase(stringValue)) {
clearCustom();
} else
throw new IllegalArgumentException("Syntax error: expected <name> = <value> or clear, instead found: " + iValue);
} else {
String customName = stringValue.substring(0, indx).trim();
String customValue = stringValue.substring(indx + 1).trim();
if (customValue.isEmpty())
removeCustom(customName);
else
setCustom(customName, customValue);
}
break;
case DESCRIPTION:
setDescription(stringValue);
break;
case ENCRYPTION:
setEncryption(stringValue);
break;
}
return this;
}
public OClassImpl setEncryption(final String iValue) {
getDatabase().checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
acquireSchemaWriteLock();
try {
final ODatabaseDocumentInternal database = getDatabase();
final OStorage storage = database.getStorage();
if (storage instanceof OStorageProxy) {
final String cmd = String.format("alter class %s encryption %s", name, iValue);
database.command(new OCommandSQL(cmd)).execute();
} else if (isDistributedCommand()) {
final String cmd = String.format("alter class %s encryption %s", name, iValue);
final OCommandSQL commandSQL = new OCommandSQL(cmd);
commandSQL.addExcludedNode(((OAutoshardedStorage) storage).getNodeId());
database.command(commandSQL).execute();
setEncryptionInternal(iValue);
} else
setEncryptionInternal(iValue);
} finally {
releaseSchemaWriteLock();
}
return this;
}
protected void setEncryptionInternal(final String iValue) {
for (int cl : getClusterIds()) {
final OCluster c = getDatabase().getStorage().getClusterById(cl);
if (c != null)
try {
c.set(OCluster.ATTRIBUTES.ENCRYPTION, iValue);
} catch (IOException e) {
}
}
}
public OPropertyImpl addPropertyInternal(final String name, final OType type, final OType linkedType, final OClass linkedClass,
final boolean unsafe) {
if (name == null || name.length() == 0)
throw new OSchemaException("Found property name null");
final Character wrongCharacter = OSchemaShared.checkFieldNameIfValid(name);
if (wrongCharacter != null)
throw new OSchemaException("Invalid property name '" + name + "'. Character '" + wrongCharacter + "' cannot be used");
if (!unsafe)
checkPersistentPropertyType(getDatabase(), name, type);
final String lowerName = name.toLowerCase();
final OPropertyImpl prop;
// This check are doubled becouse used by sql commands
if (linkedType != null)
OPropertyImpl.checkLinkTypeSupport(type);
if (linkedClass != null)
OPropertyImpl.checkSupportLinkedClass(type);
acquireSchemaWriteLock();
try {
checkEmbedded();
if (properties.containsKey(lowerName))
throw new OSchemaException("Class '" + this.name + "' already has property '" + name + "'");
OGlobalProperty global = owner.findOrCreateGlobalProperty(name, type);
prop = new OPropertyImpl(this, global);
properties.put(lowerName, prop);
if (linkedType != null)
prop.setLinkedTypeInternal(linkedType);
else if (linkedClass != null)
prop.setLinkedClassInternal(linkedClass);
} finally {
releaseSchemaWriteLock();
}
if (prop != null && !unsafe)
fireDatabaseMigration(getDatabase(), name, type);
return prop;
}
public OIndex<?> createIndex(final String iName, final INDEX_TYPE iType, final String... fields) {
return createIndex(iName, iType.name(), fields);
}
public OIndex<?> createIndex(final String iName, final String iType, final String... fields) {
return createIndex(iName, iType, null, null, fields);
}
public OIndex<?> createIndex(final String iName, final INDEX_TYPE iType, final OProgressListener iProgressListener,
final String... fields) {
return createIndex(iName, iType.name(), iProgressListener, null, fields);
}
public OIndex<?> createIndex(String iName, String iType, OProgressListener iProgressListener, ODocument metadata,
String... fields) {
return createIndex(iName, iType, iProgressListener, metadata, null, fields);
}
public OIndex<?> createIndex(final String name, String type, final OProgressListener progressListener, ODocument metadata,
String algorithm, final String... fields) {
if (type == null)
throw new IllegalArgumentException("Index type is null");
type = type.toUpperCase();
if (fields.length == 0) {
throw new OIndexException("List of fields to index cannot be empty.");
}
final OIndexDefinition indexDefinition;
acquireSchemaReadLock();
try {
for (final String fieldToIndex : fields) {
final String fieldName = OIndexDefinitionFactory.extractFieldName(fieldToIndex);
if (!fieldName.equals("@rid") && !existsProperty(fieldName))
throw new OIndexException("Index with name : '" + name + "' cannot be created on class '" + this.name
+ "' because field '" + fieldName + "' is absent in class definition.");
}
indexDefinition = OIndexDefinitionFactory.createIndexDefinition(this, Arrays.asList(fields), extractFieldTypes(fields), null,
type, algorithm);
} finally {
releaseSchemaReadLock();
}
return getDatabase().getMetadata().getIndexManager().createIndex(name, type, indexDefinition, polymorphicClusterIds,
progressListener, metadata, algorithm);
}
public boolean areIndexed(final String... fields) {
return areIndexed(Arrays.asList(fields));
}
public boolean areIndexed(final Collection<String> fields) {
final OIndexManager indexManager = getDatabase().getMetadata().getIndexManager();
acquireSchemaReadLock();
try {
final boolean currentClassResult = indexManager.areIndexed(name, fields);
if (currentClassResult)
return true;
for (OClassImpl superClass : superClasses) {
if (superClass.areIndexed(fields))
return true;
}
return false;
} finally {
releaseSchemaReadLock();
}
}
public Set<OIndex<?>> getInvolvedIndexes(final String... fields) {
return getInvolvedIndexes(Arrays.asList(fields));
}
public Set<OIndex<?>> getInvolvedIndexes(final Collection<String> fields) {
acquireSchemaReadLock();
try {
final Set<OIndex<?>> result = new HashSet<OIndex<?>>(getClassInvolvedIndexes(fields));
for (OClassImpl superClass : superClasses) {
result.addAll(superClass.getInvolvedIndexes(fields));
}
return result;
} finally {
releaseSchemaReadLock();
}
}
public Set<OIndex<?>> getClassInvolvedIndexes(final Collection<String> fields) {
final OIndexManager indexManager = getDatabase().getMetadata().getIndexManager();
acquireSchemaReadLock();
try {
return indexManager.getClassInvolvedIndexes(name, fields);
} finally {
releaseSchemaReadLock();
}
}
public Set<OIndex<?>> getClassInvolvedIndexes(final String... fields) {
return getClassInvolvedIndexes(Arrays.asList(fields));
}
public OIndex<?> getClassIndex(final String name) {
acquireSchemaReadLock();
try {
return getDatabase().getMetadata().getIndexManager().getClassIndex(this.name, name);
} finally {
releaseSchemaReadLock();
}
}
public Set<OIndex<?>> getClassIndexes() {
acquireSchemaReadLock();
try {
final OIndexManagerProxy idxManager = getDatabase().getMetadata().getIndexManager();
if (idxManager == null)
return new HashSet<OIndex<?>>();
return idxManager.getClassIndexes(name);
} finally {
releaseSchemaReadLock();
}
}
@Override
public void getClassIndexes(final Collection<OIndex<?>> indexes) {
acquireSchemaReadLock();
try {
final OIndexManagerProxy idxManager = getDatabase().getMetadata().getIndexManager();
if (idxManager == null)
return;
idxManager.getClassIndexes(name, indexes);
} finally {
releaseSchemaReadLock();
}
}
@Override
public OIndex<?> getAutoShardingIndex() {
final ODatabaseDocumentInternal db = ODatabaseRecordThreadLocal.INSTANCE.getIfDefined();
return db != null ? db.getMetadata().getIndexManager().getClassAutoShardingIndex(name) : null;
}
public void onPostIndexManagement() {
final OIndex<?> autoShardingIndex = getAutoShardingIndex();
if (autoShardingIndex != null) {
// OVERRIDE CLUSTER SELECTION
setClusterSelectionInternal(new OAutoShardingClusterSelectionStrategy(this, autoShardingIndex));
} else if (clusterSelection instanceof OAutoShardingClusterSelectionStrategy)
// REMOVE AUTO SHARDING CLUSTER SELECTION
setClusterSelectionInternal(new ORoundRobinClusterSelectionStrategy());
}
@Override
public void getIndexes(final Collection<OIndex<?>> indexes) {
acquireSchemaReadLock();
try {
getClassIndexes(indexes);
for (OClass superClass : superClasses) {
superClass.getIndexes(indexes);
}
} finally {
releaseSchemaReadLock();
}
}
public Set<OIndex<?>> getIndexes() {
Set<OIndex<?>> indexes = new HashSet<OIndex<?>>();
getIndexes(indexes);
return indexes;
}
public void acquireSchemaReadLock() {
owner.acquireSchemaReadLock();
}
public void releaseSchemaReadLock() {
owner.releaseSchemaReadLock();
}
public void acquireSchemaWriteLock() {
owner.acquireSchemaWriteLock();
}
public void releaseSchemaWriteLock() {
releaseSchemaWriteLock(true);
}
public void releaseSchemaWriteLock(final boolean iSave) {
calculateHashCode();
owner.releaseSchemaWriteLock(iSave);
}
public void checkEmbedded() {
owner.checkEmbedded(getDatabase().getStorage().getUnderlying().getUnderlying());
}
public void setClusterSelectionInternal(final String clusterSelection) {
// AVOID TO CHECK THIS IN LOCK TO AVOID RE-GENERATION OF IMMUTABLE SCHEMAS
if (this.clusterSelection.getName().equals(clusterSelection))
// NO CHANGES
return;
acquireSchemaWriteLock();
try {
checkEmbedded();
this.clusterSelection = owner.getClusterSelectionFactory().newInstance(clusterSelection);
} finally {
releaseSchemaWriteLock();
}
}
public void setClusterSelectionInternal(final OClusterSelectionStrategy iClusterSelection) {
// AVOID TO CHECK THIS IN LOCK TO AVOID RE-GENERATION OF IMMUTABLE SCHEMAS
if (this.clusterSelection.getName().equals(iClusterSelection.getName()))
// NO CHANGES
return;
acquireSchemaWriteLock();
try {
checkEmbedded();
this.clusterSelection = iClusterSelection;
} finally {
releaseSchemaWriteLock(false);
}
}
public void fireDatabaseMigration(final ODatabaseDocument database, final String propertyName, final OType type) {
final boolean strictSQL = ((ODatabaseInternal) database).getStorage().getConfiguration().isStrictSql();
database.query(new OSQLAsynchQuery<Object>("select from " + getEscapedName(name, strictSQL) + " where "
+ getEscapedName(propertyName, strictSQL) + ".type() <> \"" + type.name() + "\"", new OCommandResultListener() {
@Override
public boolean result(Object iRecord) {
final ODocument record = ((OIdentifiable) iRecord).getRecord();
record.field(propertyName, record.field(propertyName), type);
database.save(record);
return true;
}
@Override
public void end() {
}
@Override
public Object getResult() {
return null;
}
}));
}
public void firePropertyNameMigration(final ODatabaseDocument database, final String propertyName, final String newPropertyName,
final OType type) {
final boolean strictSQL = ((ODatabaseInternal) database).getStorage().getConfiguration().isStrictSql();
database.query(new OSQLAsynchQuery<Object>(
"select from " + getEscapedName(name, strictSQL) + " where " + getEscapedName(propertyName, strictSQL) + " is not null ",
new OCommandResultListener() {
@Override
public boolean result(Object iRecord) {
final ODocument record = ((OIdentifiable) iRecord).getRecord();
record.setFieldType(propertyName, type);
record.field(newPropertyName, record.field(propertyName), type);
database.save(record);
return true;
}
@Override
public void end() {
}
@Override
public Object getResult() {
return null;
}
}));
}
public void checkPersistentPropertyType(final ODatabaseInternal<ORecord> database, final String propertyName, final OType type) {
final boolean strictSQL = database.getStorage().getConfiguration().isStrictSql();
final StringBuilder builder = new StringBuilder(256);
builder.append("select count(*) from ");
builder.append(getEscapedName(name, strictSQL));
builder.append(" where ");
builder.append(getEscapedName(propertyName, strictSQL));
builder.append(".type() not in [");
final Iterator<OType> cur = type.getCastable().iterator();
while (cur.hasNext()) {
builder.append('"').append(cur.next().name()).append('"');
if (cur.hasNext())
builder.append(",");
}
builder.append("] and ").append(getEscapedName(propertyName, strictSQL)).append(" is not null ");
if (type.isMultiValue())
builder.append(" and ").append(getEscapedName(propertyName, strictSQL)).append(".size() <> 0 limit 1");
final List<ODocument> res = database.command(new OCommandSQL(builder.toString())).execute();
if (((Long) res.get(0).field("count")) > 0)
throw new OSchemaException("The database contains some schema-less data in the property '" + name + "." + propertyName
+ "' that is not compatible with the type " + type + ". Fix those records and change the schema again");
}
protected String getEscapedName(final String iName, final boolean iStrictSQL) {
if (iStrictSQL)
// ESCAPE NAME
return "`" + iName + "`";
return iName;
}
public OSchemaShared getOwner() {
return owner;
}
private void calculateHashCode() {
int result = super.hashCode();
result = 31 * result + (name != null ? name.hashCode() : 0);
hashCode = result;
}
private void setOverSizeInternal(final float overSize) {
getDatabase().checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
acquireSchemaWriteLock();
try {
checkEmbedded();
this.overSize = overSize;
} finally {
releaseSchemaWriteLock();
}
}
private void setCustomInternal(final String name, final String value) {
acquireSchemaWriteLock();
try {
checkEmbedded();
if (customFields == null)
customFields = new HashMap<String, String>();
if (value == null || "null".equalsIgnoreCase(value))
customFields.remove(name);
else
customFields.put(name, value);
} finally {
releaseSchemaWriteLock();
}
}
private void clearCustomInternal() {
acquireSchemaWriteLock();
try {
checkEmbedded();
customFields = null;
} finally {
releaseSchemaWriteLock();
}
}
private void setNameInternal(final String name) {
getDatabase().checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
acquireSchemaWriteLock();
try {
checkEmbedded();
final String oldName = this.name;
owner.changeClassName(this.name, name, this);
this.name = name;
ODatabaseDocumentInternal database = getDatabase();
final OStorage storage = database.getStorage();
if (!database.getStorageVersions().classesAreDetectedByClusterId()) {
for (int clusterId : clusterIds) {
long[] range = storage.getClusterDataRange(clusterId);
OPhysicalPosition[] positions = storage.ceilingPhysicalPositions(clusterId, new OPhysicalPosition(range[0]));
do {
for (OPhysicalPosition position : positions) {
final ORecordId identity = new ORecordId(clusterId, position.clusterPosition);
final ORawBuffer record = storage.readRecord(identity, null, true, null).getResult();
if (record.recordType == ODocument.RECORD_TYPE) {
final ORecordSerializerSchemaAware2CSV serializer = (ORecordSerializerSchemaAware2CSV) ORecordSerializerFactory
.instance().getFormat(ORecordSerializerSchemaAware2CSV.NAME);
String persName = new String(record.buffer, "UTF-8");
if (serializer.getClassName(persName).equalsIgnoreCase(name)) {
final ODocument document = new ODocument();
document.setLazyLoad(false);
document.fromStream(record.buffer);
ORecordInternal.setVersion(document, record.version);
ORecordInternal.setIdentity(document, identity);
document.setClassName(name);
document.setDirty();
document.save();
}
}
if (positions.length > 0)
positions = storage.higherPhysicalPositions(clusterId, positions[positions.length - 1]);
}
} while (positions.length > 0);
}
}
renameCluster(oldName, this.name);
} catch (UnsupportedEncodingException e) {
throw OException.wrapException(new OSchemaException("Error reading schema"), e);
} finally {
releaseSchemaWriteLock();
}
}
private void renameCluster(String oldName, String newName) {
oldName = oldName.toLowerCase();
newName = newName.toLowerCase();
final ODatabaseDocumentInternal database = getDatabase();
final OStorage storage = database.getStorage();
if (storage.getClusterIdByName(newName) != -1)
return;
final int clusterId = storage.getClusterIdByName(oldName);
if (clusterId == -1)
return;
if (!hasClusterId(clusterId))
return;
database.command(new OCommandSQL("alter cluster " + oldName + " name " + newName)).execute();
}
private void setShortNameInternal(final String iShortName) {
getDatabase().checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
acquireSchemaWriteLock();
try {
checkEmbedded();
String oldName = null;
if (this.shortName != null)
oldName = this.shortName;
owner.changeClassName(oldName, iShortName, this);
this.shortName = iShortName;
} finally {
releaseSchemaWriteLock();
}
}
private void setDescriptionInternal(final String iDescription) {
acquireSchemaWriteLock();
try {
checkEmbedded();
this.description = iDescription;
} finally {
releaseSchemaWriteLock();
}
}
private void dropPropertyInternal(final String iPropertyName) {
if (getDatabase().getTransaction().isActive())
throw new IllegalStateException("Cannot drop a property inside a transaction");
getDatabase().checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_DELETE);
acquireSchemaWriteLock();
try {
checkEmbedded();
final OProperty prop = properties.remove(iPropertyName.toLowerCase());
if (prop == null)
throw new OSchemaException("Property '" + iPropertyName + "' not found in class " + name + "'");
} finally {
releaseSchemaWriteLock();
}
}
private int createClusterIfNeeded(String nameOrId) {
final String[] parts = nameOrId.split(" ");
int clId = getClusterId(parts[0]);
if (clId == NOT_EXISTENT_CLUSTER_ID) {
try {
clId = Integer.parseInt(parts[0]);
throw new IllegalArgumentException("Cluster id '" + clId + "' cannot be added");
} catch (NumberFormatException e) {
clId = getDatabase().addCluster(parts[0]);
}
}
return clId;
}
private OClass addClusterIdInternal(final int clusterId) {
acquireSchemaWriteLock();
try {
checkEmbedded();
owner.checkClusterCanBeAdded(clusterId, this);
for (int currId : clusterIds)
if (currId == clusterId)
// ALREADY ADDED
return this;
clusterIds = OArrays.copyOf(clusterIds, clusterIds.length + 1);
clusterIds[clusterIds.length - 1] = clusterId;
Arrays.sort(clusterIds);
addPolymorphicClusterId(clusterId);
if (defaultClusterId == NOT_EXISTENT_CLUSTER_ID)
defaultClusterId = clusterId;
owner.addClusterForClass(clusterId, this);
return this;
} finally {
releaseSchemaWriteLock();
}
}
private void addPolymorphicClusterId(int clusterId) {
if (Arrays.binarySearch(polymorphicClusterIds, clusterId) >= 0)
return;
polymorphicClusterIds = OArrays.copyOf(polymorphicClusterIds, polymorphicClusterIds.length + 1);
polymorphicClusterIds[polymorphicClusterIds.length - 1] = clusterId;
Arrays.sort(polymorphicClusterIds);
addClusterIdToIndexes(clusterId);
for (OClassImpl superClass : superClasses) {
superClass.addPolymorphicClusterId(clusterId);
}
}
private OClass removeClusterIdInternal(final int clusterToRemove) {
acquireSchemaWriteLock();
try {
checkEmbedded();
boolean found = false;
for (int clusterId : clusterIds) {
if (clusterId == clusterToRemove) {
found = true;
break;
}
}
if (found) {
final int[] newClusterIds = new int[clusterIds.length - 1];
for (int i = 0, k = 0; i < clusterIds.length; ++i) {
if (clusterIds[i] == clusterToRemove)
// JUMP IT
continue;
newClusterIds[k] = clusterIds[i];
k++;
}
clusterIds = newClusterIds;
removePolymorphicClusterId(clusterToRemove);
}
if (defaultClusterId == clusterToRemove) {
if (clusterIds.length >= 1)
defaultClusterId = clusterIds[0];
else
defaultClusterId = NOT_EXISTENT_CLUSTER_ID;
}
owner.removeClusterForClass(clusterToRemove, this);
} finally {
releaseSchemaWriteLock();
}
return this;
}
private void setAbstractInternal(final boolean isAbstract) {
getDatabase().checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
acquireSchemaWriteLock();
try {
if (isAbstract) {
// SWITCH TO ABSTRACT
if (defaultClusterId != NOT_EXISTENT_CLUSTER_ID) {
// CHECK
if (count() > 0)
throw new IllegalStateException("Cannot set the class as abstract because contains records.");
tryDropCluster(defaultClusterId);
for (int clusterId : getClusterIds()) {
tryDropCluster(clusterId);
removePolymorphicClusterId(clusterId);
owner.removeClusterForClass(clusterId, this);
}
setClusterIds(new int[] { NOT_EXISTENT_CLUSTER_ID });
defaultClusterId = NOT_EXISTENT_CLUSTER_ID;
}
} else {
if (!abstractClass)
return;
int clusterId = getDatabase().getClusterIdByName(name);
if (clusterId == -1)
clusterId = getDatabase().addCluster(name);
this.defaultClusterId = clusterId;
this.clusterIds[0] = this.defaultClusterId;
}
this.abstractClass = isAbstract;
} finally {
releaseSchemaWriteLock();
}
}
private void setStrictModeInternal(final boolean iStrict) {
getDatabase().checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
acquireSchemaWriteLock();
try {
checkEmbedded();
this.strictMode = iStrict;
} finally {
releaseSchemaWriteLock();
}
}
private OProperty addProperty(final String propertyName, final OType type, final OType linkedType, final OClass linkedClass,
final boolean unsafe) {
if (type == null)
throw new OSchemaException("Property type not defined.");
if (propertyName == null || propertyName.length() == 0)
throw new OSchemaException("Property name is null or empty");
if (getDatabase().getStorage().getConfiguration().isStrictSql()) {
validatePropertyName(propertyName);
}
if (getDatabase().getTransaction().isActive())
throw new OSchemaException("Cannot create property '" + propertyName + "' inside a transaction");
final ODatabaseDocumentInternal database = getDatabase();
database.checkSecurity(ORule.ResourceGeneric.SCHEMA, ORole.PERMISSION_UPDATE);
if (linkedType != null)
OPropertyImpl.checkLinkTypeSupport(type);
if (linkedClass != null)
OPropertyImpl.checkSupportLinkedClass(type);
OProperty property = null;
acquireSchemaWriteLock();
try {
final StringBuilder cmd = new StringBuilder("create property ");
// CLASS.PROPERTY NAME
if (getDatabase().getStorage().getConfiguration().isStrictSql())
cmd.append('`');
cmd.append(name);
if (getDatabase().getStorage().getConfiguration().isStrictSql())
cmd.append('`');
cmd.append('.');
if (getDatabase().getStorage().getConfiguration().isStrictSql())
cmd.append('`');
cmd.append(propertyName);
if (getDatabase().getStorage().getConfiguration().isStrictSql())
cmd.append('`');
// TYPE
cmd.append(' ');
cmd.append(type.name);
if (linkedType != null) {
// TYPE
cmd.append(' ');
cmd.append(linkedType.name);
} else if (linkedClass != null) {
// TYPE
cmd.append(' ');
if (getDatabase().getStorage().getConfiguration().isStrictSql())
cmd.append('`');
cmd.append(linkedClass.getName());
if (getDatabase().getStorage().getConfiguration().isStrictSql())
cmd.append('`');
}
if (unsafe)
cmd.append(" unsafe ");
final OStorage storage = database.getStorage();
if (storage instanceof OStorageProxy) {
database.command(new OCommandSQL(cmd.toString())).execute();
reload();
return getProperty(propertyName);
} else if (isDistributedCommand()) {
final OCommandSQL commandSQL = new OCommandSQL(cmd.toString());
commandSQL.addExcludedNode(((OAutoshardedStorage) storage).getNodeId());
database.command(commandSQL).execute();
property = addPropertyInternal(propertyName, type, linkedType, linkedClass, unsafe);
} else
property = addPropertyInternal(propertyName, type, linkedType, linkedClass, unsafe);
} finally {
releaseSchemaWriteLock();
}
return property;
}
private void validatePropertyName(final String propertyName) {
}
private int getClusterId(final String stringValue) {
int clId;
try {
clId = Integer.parseInt(stringValue);
} catch (NumberFormatException e) {
clId = getDatabase().getClusterIdByName(stringValue);
}
return clId;
}
private void addClusterIdToIndexes(int iId) {
if (getDatabase().getStorage().getUnderlying() instanceof OAbstractPaginatedStorage) {
final String clusterName = getDatabase().getClusterNameById(iId);
final List<String> indexesToAdd = new ArrayList<String>();
for (OIndex<?> index : getIndexes())
indexesToAdd.add(index.getName());
final OIndexManager indexManager = getDatabase().getMetadata().getIndexManager();
for (String indexName : indexesToAdd)
indexManager.addClusterToIndex(clusterName, indexName);
}
}
/**
* Adds a base class to the current one. It adds also the base class cluster ids to the polymorphic cluster ids array.
*
* @param iBaseClass The base class to add.
*/
private OClass addBaseClass(final OClassImpl iBaseClass) {
checkRecursion(iBaseClass);
checkParametersConflict(iBaseClass);
if (subclasses == null)
subclasses = new ArrayList<OClass>();
if (subclasses.contains(iBaseClass))
return this;
subclasses.add(iBaseClass);
addPolymorphicClusterIdsWithInheritance(iBaseClass);
return this;
}
private void checkParametersConflict(final OClass baseClass) {
final Collection<OProperty> baseClassProperties = baseClass.properties();
for (OProperty property : baseClassProperties) {
OProperty thisProperty = getProperty(property.getName());
if (thisProperty != null && !thisProperty.getType().equals(property.getType())) {
throw new OSchemaException("Cannot add base class '" + baseClass.getName() + "', because of property conflict: '"
+ thisProperty + "' vs '" + property + "'");
}
}
}
private void checkParametersConflict(List<OClassImpl> classes) {
final Map<String, OProperty> commulative = new HashMap<String, OProperty>();
final Map<String, OProperty> properties = new HashMap<String, OProperty>();
for (OClassImpl superClass : classes) {
superClass.propertiesMap(properties, false);
for (Map.Entry<String, OProperty> entry : properties.entrySet()) {
if (commulative.containsKey(entry.getKey())) {
final String property = entry.getKey();
final OProperty existingProperty = commulative.get(property);
if (!existingProperty.getType().equals(entry.getValue().getType())) {
throw new OSchemaException("Properties conflict detected: '" + existingProperty + "] vs [" + entry.getValue() + "]");
}
}
}
commulative.putAll(properties);
properties.clear();
}
}
private void checkRecursion(final OClass baseClass) {
if (isSubClassOf(baseClass)) {
throw new OSchemaException("Cannot add base class '" + baseClass.getName() + "', because of recursion");
}
}
private void removePolymorphicClusterIds(final OClassImpl iBaseClass) {
for (final int clusterId : iBaseClass.polymorphicClusterIds)
removePolymorphicClusterId(clusterId);
}
private void removePolymorphicClusterId(final int clusterId) {
final int index = Arrays.binarySearch(polymorphicClusterIds, clusterId);
if (index < 0)
return;
if (index < polymorphicClusterIds.length - 1)
System.arraycopy(polymorphicClusterIds, index + 1, polymorphicClusterIds, index, polymorphicClusterIds.length - (index + 1));
polymorphicClusterIds = Arrays.copyOf(polymorphicClusterIds, polymorphicClusterIds.length - 1);
removeClusterFromIndexes(clusterId);
for (OClassImpl superClass : superClasses) {
superClass.removePolymorphicClusterId(clusterId);
}
}
private void removeClusterFromIndexes(final int iId) {
if (getDatabase().getStorage().getUnderlying() instanceof OAbstractPaginatedStorage) {
final String clusterName = getDatabase().getClusterNameById(iId);
final List<String> indexesToRemove = new ArrayList<String>();
for (final OIndex<?> index : getIndexes())
indexesToRemove.add(index.getName());
final OIndexManager indexManager = getDatabase().getMetadata().getIndexManager();
for (final String indexName : indexesToRemove)
indexManager.removeClusterFromIndex(clusterName, indexName);
}
}
private void tryDropCluster(final int defaultClusterId) {
if (name.toLowerCase().equals(getDatabase().getClusterNameById(defaultClusterId))) {
// DROP THE DEFAULT CLUSTER CALLED WITH THE SAME NAME ONLY IF EMPTY
if (getDatabase().getClusterRecordSizeById(defaultClusterId) == 0)
getDatabase().dropCluster(defaultClusterId, true);
}
}
private ODatabaseDocumentInternal getDatabase() {
return ODatabaseRecordThreadLocal.INSTANCE.get();
}
/**
* Add different cluster id to the "polymorphic cluster ids" array.
*/
private void addPolymorphicClusterIds(final OClassImpl iBaseClass) {
boolean found;
for (int i : iBaseClass.polymorphicClusterIds) {
found = false;
for (int k : polymorphicClusterIds) {
if (i == k) {
found = true;
break;
}
}
if (!found) {
int[] oldClusterId = polymorphicClusterIds;
// ADD IT
polymorphicClusterIds = OArrays.copyOf(polymorphicClusterIds, polymorphicClusterIds.length + 1);
polymorphicClusterIds[polymorphicClusterIds.length - 1] = i;
Arrays.sort(polymorphicClusterIds);
try {
addClusterIdToIndexes(i);
} catch (Exception e) {
polymorphicClusterIds = oldClusterId;
}
}
}
}
private void addPolymorphicClusterIdsWithInheritance(final OClassImpl iBaseClass) {
addPolymorphicClusterIds(iBaseClass);
for (OClassImpl superClass : superClasses) {
superClass.addPolymorphicClusterIdsWithInheritance(iBaseClass);
}
}
public List<OType> extractFieldTypes(final String[] fieldNames) {
final List<OType> types = new ArrayList<OType>(fieldNames.length);
for (String fieldName : fieldNames) {
if (!fieldName.equals("@rid"))
types.add(getProperty(OIndexDefinitionFactory.extractFieldName(fieldName).toLowerCase()).getType());
else
types.add(OType.LINK);
}
return types;
}
private OClass setClusterIds(final int[] iClusterIds) {
clusterIds = iClusterIds;
Arrays.sort(clusterIds);
return this;
}
private boolean isDistributedCommand() {
return getDatabase().getStorage() instanceof OAutoshardedStorage
&& OScenarioThreadLocal.INSTANCE.get() != OScenarioThreadLocal.RUN_MODE.RUNNING_DISTRIBUTED;
}
}
| Improved performance by avoiding unnecessary NumberFormatException
| core/src/main/java/com/orientechnologies/orient/core/metadata/schema/OClassImpl.java | Improved performance by avoiding unnecessary NumberFormatException | <ide><path>ore/src/main/java/com/orientechnologies/orient/core/metadata/schema/OClassImpl.java
<ide> *
<ide> */
<ide> package com.orientechnologies.orient.core.metadata.schema;
<del>
<del>import java.io.IOException;
<del>import java.io.UnsupportedEncodingException;
<del>import java.util.*;
<ide>
<ide> import com.orientechnologies.common.exception.OException;
<ide> import com.orientechnologies.common.listener.OProgressListener;
<ide> import com.orientechnologies.orient.core.type.ODocumentWrapper;
<ide> import com.orientechnologies.orient.core.type.ODocumentWrapperNoClass;
<ide>
<add>import java.io.IOException;
<add>import java.io.UnsupportedEncodingException;
<add>import java.util.*;
<add>
<ide> /**
<ide> * Schema Class implementation.
<ide> *
<ide> */
<ide> @SuppressWarnings("unchecked")
<ide> public class OClassImpl extends ODocumentWrapperNoClass implements OClass {
<del> private static final long serialVersionUID = 1L;
<del> private static final int NOT_EXISTENT_CLUSTER_ID = -1;
<del> final OSchemaShared owner;
<del> private final Map<String, OProperty> properties = new HashMap<String, OProperty>();
<del> private int defaultClusterId = NOT_EXISTENT_CLUSTER_ID;
<del> private String name;
<del> private String description;
<del> private int[] clusterIds;
<del> private List<OClassImpl> superClasses = new ArrayList<OClassImpl>();
<del> private int[] polymorphicClusterIds;
<del> private List<OClass> subclasses;
<del> private float overSize = 0f;
<del> private String shortName;
<del> private boolean strictMode = false; // @SINCE v1.0rc8
<del> private boolean abstractClass = false; // @SINCE v1.2.0
<del> private Map<String, String> customFields;
<add> private static final long serialVersionUID = 1L;
<add> private static final int NOT_EXISTENT_CLUSTER_ID = -1;
<add> final OSchemaShared owner;
<add> private final Map<String, OProperty> properties = new HashMap<String, OProperty>();
<add> private int defaultClusterId = NOT_EXISTENT_CLUSTER_ID;
<add> private String name;
<add> private String description;
<add> private int[] clusterIds;
<add> private List<OClassImpl> superClasses = new ArrayList<OClassImpl>();
<add> private int[] polymorphicClusterIds;
<add> private List<OClass> subclasses;
<add> private float overSize = 0f;
<add> private String shortName;
<add> private boolean strictMode = false; // @SINCE v1.0rc8
<add> private boolean abstractClass = false; // @SINCE v1.2.0
<add> private Map<String, String> customFields;
<ide> private volatile OClusterSelectionStrategy clusterSelection; // @SINCE 1.7
<ide> private volatile int hashCode;
<ide>
<ide> /**
<ide> * Check if the current instance extends specified schema class.
<ide> *
<del> * @param iClassName of class that should be checked
<add> * @param iClassName
<add> * of class that should be checked
<ide> * @return Returns true if the current instance extends the passed schema class (iClass)
<ide> * @see #isSuperClassOf(OClass)
<ide> */
<ide> /**
<ide> * Check if the current instance extends specified schema class.
<ide> *
<del> * @param clazz to check
<add> * @param clazz
<add> * to check
<ide> * @return true if the current instance extends the passed schema class (iClass)
<ide> * @see #isSuperClassOf(OClass)
<ide> */
<ide> /**
<ide> * Returns true if the passed schema class (iClass) extends the current instance.
<ide> *
<del> * @param clazz to check
<add> * @param clazz
<add> * to check
<ide> * @return Returns true if the passed schema class extends the current instance
<ide> * @see #isSubClassOf(OClass)
<ide> */
<ide> database.query(new OSQLAsynchQuery<Object>("select from " + getEscapedName(name, strictSQL) + " where "
<ide> + getEscapedName(propertyName, strictSQL) + ".type() <> \"" + type.name() + "\"", new OCommandResultListener() {
<ide>
<del> @Override
<del> public boolean result(Object iRecord) {
<del> final ODocument record = ((OIdentifiable) iRecord).getRecord();
<del> record.field(propertyName, record.field(propertyName), type);
<del> database.save(record);
<del> return true;
<del> }
<del>
<del> @Override
<del> public void end() {
<del> }
<del>
<del> @Override
<del> public Object getResult() {
<del> return null;
<del> }
<del> }));
<add> @Override
<add> public boolean result(Object iRecord) {
<add> final ODocument record = ((OIdentifiable) iRecord).getRecord();
<add> record.field(propertyName, record.field(propertyName), type);
<add> database.save(record);
<add> return true;
<add> }
<add>
<add> @Override
<add> public void end() {
<add> }
<add>
<add> @Override
<add> public Object getResult() {
<add> return null;
<add> }
<add> }));
<ide> }
<ide>
<ide> public void firePropertyNameMigration(final ODatabaseDocument database, final String propertyName, final String newPropertyName,
<ide> int clId = getClusterId(parts[0]);
<ide>
<ide> if (clId == NOT_EXISTENT_CLUSTER_ID) {
<del> try {
<del> clId = Integer.parseInt(parts[0]);
<del> throw new IllegalArgumentException("Cluster id '" + clId + "' cannot be added");
<del> } catch (NumberFormatException e) {
<add> if (!parts[0].isEmpty() && Character.isDigit(parts[0].charAt(0)))
<add> try {
<add> clId = Integer.parseInt(parts[0]);
<add> throw new IllegalArgumentException("Cluster id '" + clId + "' cannot be added");
<add> } catch (NumberFormatException e) {
<add> clId = getDatabase().addCluster(parts[0]);
<add> }
<add> else
<ide> clId = getDatabase().addCluster(parts[0]);
<del> }
<ide> }
<ide>
<ide> return clId;
<ide>
<ide> private int getClusterId(final String stringValue) {
<ide> int clId;
<del> try {
<del> clId = Integer.parseInt(stringValue);
<del> } catch (NumberFormatException e) {
<add> if (!stringValue.isEmpty() && Character.isDigit(stringValue.charAt(0)))
<add> try {
<add> clId = Integer.parseInt(stringValue);
<add> } catch (NumberFormatException e) {
<add> clId = getDatabase().getClusterIdByName(stringValue);
<add> }
<add> else
<ide> clId = getDatabase().getClusterIdByName(stringValue);
<del> }
<add>
<ide> return clId;
<ide> }
<ide>
<ide> /**
<ide> * Adds a base class to the current one. It adds also the base class cluster ids to the polymorphic cluster ids array.
<ide> *
<del> * @param iBaseClass The base class to add.
<add> * @param iBaseClass
<add> * The base class to add.
<ide> */
<ide> private OClass addBaseClass(final OClassImpl iBaseClass) {
<ide> checkRecursion(iBaseClass); |
|
Java | apache-2.0 | 9552a7274d37291f81f0a090a04ece43983e1b7a | 0 | lan603168/Android-PullToRefresh,JRGGRoberto/Android-PullToRefresh,chengkaizone/Android-PullToRefresh,liboLiao/Android-PullToRefresh,jiedang/Android-PullToRefresh,xiabing082/PullToRefreshListview,jolynekujo/Android-PullToRefresh,paulzeng/Android-PullToRefresh,sk-huang/Android-PullToRefresh,erdanerdan/Android-PullToRefresh,beiliubei/Android-PullToRefresh,StarRain/Android-PullToRefresh,AkechiNEET/Android-PullToRefresh,franlisa/Android-PullToRefresh,seedzi/Android-PullToRefresh,b-cuts/Android-PullToRefresh,fengxiaole/Android-PullToRefresh,daviddone/Android-PullToRefresh,wangjun/Android-PullToRefresh,liqian1990/Android-PullToRefresh,Archenemy-xiatian/Android-PullToRefresh,wdyangll/Android-PullToRefresh,JohnTsaiAndroid/Android-PullToRefresh,soundcloud/Android-PullToRefresh,jargetz/Android-PullToRefresh-VerticalViewPager,sporting-innovations/Android-PullToRefresh,cncomer/pullTORefresh,jiedang/Android-PullToRefresh,Liyue1314/Android-PullToRefresh,huanting/Android-PullToRefresh,dkmeteor/Android-PullToRefresh-RecyclerView-Extention,Liyue1314/Android-PullToRefresh,TimeIncOSS/Android-PullToRefresh,JohnTsaiAndroid/Android-PullToRefresh,sunhai1992/Android-PullToRefresh,leeboo/Android-PullToRefresh,gaojinhua/Android-PullToRefresh,franlisa/Android-PullToRefresh,hotarzhang/Android-PullToRefresh,wfs3006/Android-PullToRefresh,devilWwj/Android-PullToRefresh,guoxiaojun001/Android-PullToRefresh,jianxiansining/Android-PullToRefresh,dominjune/Android-PullToRefresh,XiangHuang1992/Android-PullToRefresh-1,Ibotta/Android-PullToRefresh,fengnanyue/Android-PullToRefresh,niorgai/Android-PullToRefresh,5peak2me/Android-PullToRefresh,tianshiaimili/Z_MyProPullToRefreshListFragment,b2b2244424/Android-PullToRefresh-1,yuanhuihui/Android-PullToRefresh,zzljob/Android-PullToRefresh,hubaoyu/Android-PullToRefresh,chenxiruanhai/Android-PullToRefresh,lgzaaron/Android-PullToRefresh,luohong/Android-PullToRefresh,hubaoyu/Android-PullToRefresh,androidKaKa/Android-PullToRefresh,ZTAndroid/Android_Controller_Pull_To_Refresh,admin-zhx/Android-PullToRefresh,yulongxiao/Android-PullToRefresh,liqian1990/Android-PullToRefresh,HossainKhademian/AndroidPullToRefresh,pallyoung/Android-PullToRefresh,sainthyz/Android-PullToRefresh,yinzhiliang/Android-PullToRefresh,PengGeLiu/Android-PullToRefresh,paulzeng/Android-PullToRefresh,JunyiZhou/Android-PullToRefresh,sainthyz/Android-PullToRefresh,ren545457803/Android-PullToRefresh,GeekHades/Android-PullToRefresh,cjpx00008/Android-PullToRefresh,erdanerdan/Android-PullToRefresh,gaojinhua/Android-PullToRefresh,mxm2005/Android-PullToRefresh,hgl888/Android-PullToRefresh,liqk2014/Android-PullToRefresh,AkechiNEET/Android-PullToRefresh,djsolar/Android-PullToRefresh,yulongxiao/Android-PullToRefresh,taisukeoe/Android-PullToRefresh,b2b2244424/Android-PullToRefresh-1,shengge/Android-PullToRefresh,wswenyue/Android-PullToRefresh,huanting/Android-PullToRefresh,THEONE10211024/Android-PullToRefresh,mxm2005/Android-PullToRefresh,lirenxinshangqiu/Android-PullToRefresh,housong12590/Android-PullToRefresh,secnelis/Android-PullToRefresh,lostghoul/Android-PullToRefresh,StarRain/Android-PullToRefresh,huangsongyan/Android-PullToRefresh,wmydz1/Android-PullToRefresh,housong12590/Android-PullToRefresh,secnelis/Android-PullToRefresh,brucetoo/Android-PullToRefresh-RecyclerView-Extention,wmydz1/Android-PullToRefresh,hgl888/Android-PullToRefresh,jahonn/Android-PullToRefresh,miniPinocchio/Android-PullToRefresh,ylfonline/Android-PullToRefresh,tianshiaimili/Z_MyProPullToRefreshDemo,HamzaHasan90/Android-PullToRefresh,fengnanyue/Android-PullToRefresh,yadihaoku/Android-PullToRefresh,kaedelin/Android-PullToRefresh,lovecc0923/Android-PullToRefresh,20minutes/Android-PullToRefresh,wfs3006/Android-PullToRefresh,imeeting/Android-PullToRefresh,PengGeLiu/Android-PullToRefresh,yqh012/Android-PullToRefresh,dominjune/Android-PullToRefresh,THEONE10211024/Android-PullToRefresh,513768395/Android-PullToRefresh-1,zzljob/Android-PullToRefresh,niorgai/Android-PullToRefresh,sk-huang/Android-PullToRefresh,lan603168/Android-PullToRefresh,GeekHades/Android-PullToRefresh,xiaoleigua/Android-PullToRefresh,b-cuts/Android-PullToRefresh,HamzaHasan90/Android-PullToRefresh,scodemao/Android-PullToRefresh,liqk2014/Android-PullToRefresh,yinzhiliang/Android-PullToRefresh,zhangyp920201/Android-PullToRefresh,lzz358191062/Android-PullToRefresh,JRGGRoberto/Android-PullToRefresh,lxg8293/Android-PullToRefresh,zhupengGitHub/Android-PullToRefresh,jiangli615/Android-PullToRefresh,chrisbanes/Android-PullToRefresh,caoyang521/Android-PullToRefresh,caoyang521/Android-PullToRefresh,jiangli615/Android-PullToRefresh,SundayGao/Android-PullToRefresh,admin-zhx/Android-PullToRefresh,yuanhuihui/Android-PullToRefresh,jiaoyu123/Android-PullToRefresh,lostghoul/Android-PullToRefresh,513768395/Android-PullToRefresh-1,kidfolk/Android-PullToRefresh,pallyoung/Android-PullToRefresh,danDingCongRong/Android-PullToRefresh,yqh012/Android-PullToRefresh,SundayGao/Android-PullToRefresh,lirenxinshangqiu/Android-PullToRefresh,chenupt/Android-PullToRefresh,chenxiruanhai/Android-PullToRefresh,lzz358191062/Android-PullToRefresh,5peak2me/Android-PullToRefresh,androidmchen/Android-PullToRefresh,SHAU-LOK/Android-PullToRefresh,zhangyp920201/Android-PullToRefresh,zhoujianyu/Android-PullToRefresh,zhangyihao/Android-PullToRefresh,liboLiao/Android-PullToRefresh,sw926/Android-PullToRefresh,alexyvv/Android-PullToRefresh,sporting-innovations/Android-PullToRefresh,charlialiang/Android-PullToRefresh,ileisure/Android-PullToRefresh,XiangHuang1992/Android-PullToRefresh-1,jianxiansining/Android-PullToRefresh,zhangyihao/Android-PullToRefresh,chenupt/Android-PullToRefresh,djsolar/Android-PullToRefresh,Scorcher/Android-PullToRefresh,lxhxhlw/Android-PullToRefresh,guoxiaojun001/Android-PullToRefresh,kaedelin/Android-PullToRefresh,luohong/Android-PullToRefresh,liqt/Android-PullToRefresh,sw926/Android-PullToRefresh,JackRo/Android-PullToRefresh,simple88/Android-PullToRefresh,finch0219/Android-PullToRefresh,brucetoo/Android-PullToRefresh-RecyclerView-Extention,weijiangnan/Android-PullToRefresh,just4phil/Android-PullToRefresh,xiaob/Android-PullToRefresh,xiaob/Android-PullToRefresh,JackRo/Android-PullToRefresh,zhoujianyu/Android-PullToRefresh,lgzaaron/Android-PullToRefresh,miniPinocchio/Android-PullToRefresh,daviddone/Android-PullToRefresh,jiaoyu123/Android-PullToRefresh,finch0219/Android-PullToRefresh,HanAsteroid/Android-PullToRefresh,xiaoleigua/Android-PullToRefresh,HanAsteroid/Android-PullToRefresh,zfc580/Android-PullToRefresh,simple88/Android-PullToRefresh,wangjun/Android-PullToRefresh,ren545457803/Android-PullToRefresh,weijiangnan/Android-PullToRefresh,seedzi/Android-PullToRefresh,zhupengGitHub/Android-PullToRefresh,hotarzhang/Android-PullToRefresh,ZTAndroid/Android_Controller_Pull_To_Refresh,jahonn/Android-PullToRefresh,fairyzoro/Android-PullToRefresh,zhouyyibin/Android-PullToRefresh,tianshiaimili/Z_MyProPullToRefresh,jx-admin/Android-PullToRefresh,huangsongyan/Android-PullToRefresh,lovecc0923/Android-PullToRefresh,lxhxhlw/Android-PullToRefresh,xiabing082/PullToRefreshListview,yu-yang-halo/Android-PullToRefresh,JunyiZhou/Android-PullToRefresh,wswenyue/Android-PullToRefresh,Topface/Android-PullToRefresh,sunhai1992/Android-PullToRefresh,cjpx00008/Android-PullToRefresh,danDingCongRong/Android-PullToRefresh,jolynekujo/Android-PullToRefresh,zfc580/Android-PullToRefresh,fengxiaole/Android-PullToRefresh,VideoTec/Android-PullToRefresh,just4phil/Android-PullToRefresh,dkmeteor/Android-PullToRefresh-RecyclerView-Extention,charlialiang/Android-PullToRefresh,chengkaizone/Android-PullToRefresh,Ibotta/Android-PullToRefresh,ylfonline/Android-PullToRefresh,lxg8293/Android-PullToRefresh,yu-yang-halo/Android-PullToRefresh,ileisure/Android-PullToRefresh,serso/Android-PullToRefresh,Archenemy-xiatian/Android-PullToRefresh,12307/Android-PullToRefresh,scodemao/Android-PullToRefresh,fairyzoro/Android-PullToRefresh,androidKaKa/Android-PullToRefresh,VideoTec/Android-PullToRefresh,yadihaoku/Android-PullToRefresh,tuolin2013/pull_to_refresh_lib,27988301/Android-PullToRefresh,androidmchen/Android-PullToRefresh,SHAU-LOK/Android-PullToRefresh,liqt/Android-PullToRefresh | package com.handmark.pulltorefresh.library;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.Interpolator;
import android.widget.LinearLayout;
import com.handmark.pulltorefresh.library.internal.LoadingLayout;
public abstract class PullToRefreshBase<T extends View> extends LinearLayout {
final class SmoothScrollRunnable implements Runnable {
static final int ANIMATION_DURATION_MS = 190;
static final int ANIMATION_FPS = 1000 / 60;
private final Interpolator mInterpolator;
private final int mScrollToY;
private final int mScrollFromY;
private final Handler mHandler;
private boolean mContinueRunning = true;
private long mStartTime = -1;
private int mCurrentY = -1;
public SmoothScrollRunnable(Handler handler, int fromY, int toY) {
mHandler = handler;
mScrollFromY = fromY;
mScrollToY = toY;
mInterpolator = new AccelerateDecelerateInterpolator();
}
@Override
public void run() {
/**
* Only set mStartTime if this is the first time we're starting,
* else actually calculate the Y delta
*/
if (mStartTime == -1) {
mStartTime = System.currentTimeMillis();
} else {
/**
* We do do all calculations in long to reduce software float
* calculations. We use 1000 as it gives us good accuracy and
* small rounding errors
*/
long normalizedTime = (1000 * (System.currentTimeMillis() - mStartTime)) / ANIMATION_DURATION_MS;
normalizedTime = Math.max(Math.min(normalizedTime, 1000), 0);
final int deltaY = Math.round((mScrollFromY - mScrollToY)
* mInterpolator.getInterpolation(normalizedTime / 1000f));
mCurrentY = mScrollFromY - deltaY;
setHeaderScroll(mCurrentY);
}
// If we're not at the target Y, keep going...
if (mContinueRunning && mScrollToY != mCurrentY) {
mHandler.postDelayed(this, ANIMATION_FPS);
}
}
public void stop() {
mContinueRunning = false;
mHandler.removeCallbacks(this);
}
}
// ===========================================================
// Constants
// ===========================================================
static final boolean DEBUG = false;
static final String LOG_TAG = "PullToRefresh";
static final float FRICTION = 2.0f;
static final int PULL_TO_REFRESH = 0x0;
static final int RELEASE_TO_REFRESH = 0x1;
static final int REFRESHING = 0x2;
static final int MANUAL_REFRESHING = 0x3;
public static final int MODE_PULL_DOWN_TO_REFRESH = 0x1;
public static final int MODE_PULL_UP_TO_REFRESH = 0x2;
public static final int MODE_BOTH = 0x3;
// ===========================================================
// Fields
// ===========================================================
private int mTouchSlop;
private float mInitialMotionY;
private float mLastMotionX;
private float mLastMotionY;
private boolean mIsBeingDragged = false;
private int mState = PULL_TO_REFRESH;
private int mMode = MODE_PULL_DOWN_TO_REFRESH;
private int mCurrentMode;
private boolean mDisableScrollingWhileRefreshing = true;
T mRefreshableView;
private boolean mIsPullToRefreshEnabled = true;
private LoadingLayout mHeaderLayout;
private LoadingLayout mFooterLayout;
private int mHeaderHeight;
private final Handler mHandler = new Handler();
private OnRefreshListener mOnRefreshListener;
private OnRefreshListener2 mOnRefreshListener2;
private SmoothScrollRunnable mCurrentSmoothScrollRunnable;
// ===========================================================
// Constructors
// ===========================================================
public PullToRefreshBase(Context context) {
super(context);
init(context, null);
}
public PullToRefreshBase(Context context, int mode) {
super(context);
mMode = mode;
init(context, null);
}
public PullToRefreshBase(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
// ===========================================================
// Getter & Setter
// ===========================================================
/**
* Deprecated. Use {@link #getRefreshableView()} from now on.
*
* @deprecated
* @return The Refreshable View which is currently wrapped
*/
public final T getAdapterView() {
return mRefreshableView;
}
/**
* Get the Wrapped Refreshable View. Anything returned here has already been
* added to the content view.
*
* @return The View which is currently wrapped
*/
public final T getRefreshableView() {
return mRefreshableView;
}
/**
* Whether Pull-to-Refresh is enabled
*
* @return enabled
*/
public final boolean isPullToRefreshEnabled() {
return mIsPullToRefreshEnabled;
}
/**
* Returns whether the widget has disabled scrolling on the Refreshable View
* while refreshing.
*
* @return true if the widget has disabled scrolling while refreshing
*/
public final boolean isDisableScrollingWhileRefreshing() {
return mDisableScrollingWhileRefreshing;
}
/**
* Returns whether the Widget is currently in the Refreshing mState
*
* @return true if the Widget is currently refreshing
*/
public final boolean isRefreshing() {
return mState == REFRESHING || mState == MANUAL_REFRESHING;
}
/**
* By default the Widget disabled scrolling on the Refreshable View while
* refreshing. This method can change this behaviour.
*
* @param disableScrollingWhileRefreshing
* - true if you want to disable scrolling while refreshing
*/
public final void setDisableScrollingWhileRefreshing(boolean disableScrollingWhileRefreshing) {
mDisableScrollingWhileRefreshing = disableScrollingWhileRefreshing;
}
/**
* Mark the current Refresh as complete. Will Reset the UI and hide the
* Refreshing View
*/
public final void onRefreshComplete() {
if (mState != PULL_TO_REFRESH) {
resetHeader();
}
}
/**
* Set OnRefreshListener for the Widget
*
* @param listener
* - Listener to be used when the Widget is set to Refresh
*/
public final void setOnRefreshListener(OnRefreshListener listener) {
mOnRefreshListener = listener;
}
/**
* Set OnRefreshListener for the Widget
*
* @param listener
* - Listener to be used when the Widget is set to Refresh
*/
public final void setOnRefreshListener(OnRefreshListener2 listener) {
mOnRefreshListener2 = listener;
}
/**
* A mutator to enable/disable Pull-to-Refresh for the current View
*
* @param enable
* Whether Pull-To-Refresh should be used
*/
public final void setPullToRefreshEnabled(boolean enable) {
mIsPullToRefreshEnabled = enable;
}
/**
* Set Text to show when the Widget is being pulled, and will refresh when
* released
*
* @param releaseLabel
* - String to display
*/
public void setReleaseLabel(String releaseLabel) {
if (null != mHeaderLayout) {
mHeaderLayout.setReleaseLabel(releaseLabel);
}
if (null != mFooterLayout) {
mFooterLayout.setReleaseLabel(releaseLabel);
}
}
/**
* Set Text to show when the Widget is being Pulled
*
* @param pullLabel
* - String to display
*/
public void setPullLabel(String pullLabel) {
if (null != mHeaderLayout) {
mHeaderLayout.setPullLabel(pullLabel);
}
if (null != mFooterLayout) {
mFooterLayout.setPullLabel(pullLabel);
}
}
/**
* Set Text to show when the Widget is refreshing
*
* @param refreshingLabel
* - String to display
*/
public void setRefreshingLabel(String refreshingLabel) {
if (null != mHeaderLayout) {
mHeaderLayout.setRefreshingLabel(refreshingLabel);
}
if (null != mFooterLayout) {
mFooterLayout.setRefreshingLabel(refreshingLabel);
}
}
public final void setRefreshing() {
setRefreshing(true);
}
/**
* Sets the Widget to be in the refresh mState. The UI will be updated to
* show the 'Refreshing' view.
*
* @param doScroll
* - true if you want to force a scroll to the Refreshing view.
*/
public final void setRefreshing(boolean doScroll) {
if (!isRefreshing()) {
setRefreshingInternal(doScroll);
mState = MANUAL_REFRESHING;
}
}
public final boolean hasPullFromTop() {
return mCurrentMode != MODE_PULL_UP_TO_REFRESH;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public final boolean onTouchEvent(MotionEvent event) {
if (!mIsPullToRefreshEnabled) {
return false;
}
if (isRefreshing() && mDisableScrollingWhileRefreshing) {
return true;
}
if (event.getAction() == MotionEvent.ACTION_DOWN && event.getEdgeFlags() != 0) {
return false;
}
switch (event.getAction()) {
case MotionEvent.ACTION_MOVE: {
if (mIsBeingDragged) {
mLastMotionY = event.getY();
pullEvent();
return true;
}
break;
}
case MotionEvent.ACTION_DOWN: {
if (isReadyForPull()) {
mLastMotionY = mInitialMotionY = event.getY();
return true;
}
break;
}
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP: {
if (mIsBeingDragged) {
mIsBeingDragged = false;
if (mState == RELEASE_TO_REFRESH) {
if (null != mOnRefreshListener) {
setRefreshingInternal(true);
mOnRefreshListener.onRefresh();
return true;
} else if (null != mOnRefreshListener2) {
setRefreshingInternal(true);
if (mCurrentMode == MODE_PULL_DOWN_TO_REFRESH) {
mOnRefreshListener2.onPullDownToRefresh();
} else if (mCurrentMode == MODE_PULL_UP_TO_REFRESH) {
mOnRefreshListener2.onPullUpToRefresh();
}
return true;
}
return true;
}
smoothScrollTo(0);
return true;
}
break;
}
}
return false;
}
@Override
public final boolean onInterceptTouchEvent(MotionEvent event) {
if (!mIsPullToRefreshEnabled) {
return false;
}
if (isRefreshing() && mDisableScrollingWhileRefreshing) {
return true;
}
final int action = event.getAction();
if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP) {
mIsBeingDragged = false;
return false;
}
if (action != MotionEvent.ACTION_DOWN && mIsBeingDragged) {
return true;
}
switch (action) {
case MotionEvent.ACTION_MOVE: {
if (isReadyForPull()) {
final float y = event.getY();
final float dy = y - mLastMotionY;
final float yDiff = Math.abs(dy);
final float xDiff = Math.abs(event.getX() - mLastMotionX);
if (yDiff > mTouchSlop && yDiff > xDiff) {
if ((mMode == MODE_PULL_DOWN_TO_REFRESH || mMode == MODE_BOTH) && dy >= 0.0001f
&& isReadyForPullDown()) {
mLastMotionY = y;
mIsBeingDragged = true;
if (mMode == MODE_BOTH) {
mCurrentMode = MODE_PULL_DOWN_TO_REFRESH;
}
} else if ((mMode == MODE_PULL_UP_TO_REFRESH || mMode == MODE_BOTH) && dy <= 0.0001f
&& isReadyForPullUp()) {
mLastMotionY = y;
mIsBeingDragged = true;
if (mMode == MODE_BOTH) {
mCurrentMode = MODE_PULL_UP_TO_REFRESH;
}
}
}
}
break;
}
case MotionEvent.ACTION_DOWN: {
if (isReadyForPull()) {
mLastMotionY = mInitialMotionY = event.getY();
mLastMotionX = event.getX();
mIsBeingDragged = false;
}
break;
}
}
return mIsBeingDragged;
}
protected void addRefreshableView(Context context, T refreshableView) {
addView(refreshableView, new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, 0, 1.0f));
}
/**
* This is implemented by derived classes to return the created View. If you
* need to use a custom View (such as a custom ListView), override this
* method and return an instance of your custom class.
*
* Be sure to set the ID of the view in this method, especially if you're
* using a ListActivity or ListFragment.
*
* @param context
* Context to create view with
* @param attrs
* AttributeSet from wrapped class. Means that anything you
* include in the XML layout declaration will be routed to the
* created View
* @return New instance of the Refreshable View
*/
protected abstract T createRefreshableView(Context context, AttributeSet attrs);
protected final int getCurrentMode() {
return mCurrentMode;
}
protected final LoadingLayout getFooterLayout() {
return mFooterLayout;
}
protected final LoadingLayout getHeaderLayout() {
return mHeaderLayout;
}
protected final int getHeaderHeight() {
return mHeaderHeight;
}
protected final int getMode() {
return mMode;
}
/**
* Implemented by derived class to return whether the View is in a mState
* where the user can Pull to Refresh by scrolling down.
*
* @return true if the View is currently the correct mState (for example,
* top of a ListView)
*/
protected abstract boolean isReadyForPullDown();
/**
* Implemented by derived class to return whether the View is in a mState
* where the user can Pull to Refresh by scrolling up.
*
* @return true if the View is currently in the correct mState (for example,
* bottom of a ListView)
*/
protected abstract boolean isReadyForPullUp();
// ===========================================================
// Methods
// ===========================================================
protected void resetHeader() {
mState = PULL_TO_REFRESH;
mIsBeingDragged = false;
if (null != mHeaderLayout) {
mHeaderLayout.reset();
}
if (null != mFooterLayout) {
mFooterLayout.reset();
}
smoothScrollTo(0);
}
protected void setRefreshingInternal(boolean doScroll) {
mState = REFRESHING;
if (null != mHeaderLayout) {
mHeaderLayout.refreshing();
}
if (null != mFooterLayout) {
mFooterLayout.refreshing();
}
if (doScroll) {
smoothScrollTo(mCurrentMode == MODE_PULL_DOWN_TO_REFRESH ? -mHeaderHeight : mHeaderHeight);
}
}
protected final void setHeaderScroll(int y) {
scrollTo(0, y);
}
protected final void smoothScrollTo(int y) {
if (null != mCurrentSmoothScrollRunnable) {
mCurrentSmoothScrollRunnable.stop();
}
if (getScrollY() != y) {
mCurrentSmoothScrollRunnable = new SmoothScrollRunnable(mHandler, getScrollY(), y);
mHandler.post(mCurrentSmoothScrollRunnable);
}
}
private void init(Context context, AttributeSet attrs) {
setOrientation(LinearLayout.VERTICAL);
mTouchSlop = ViewConfiguration.getTouchSlop();
// Styleables from XML
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.PullToRefresh);
if (a.hasValue(R.styleable.PullToRefresh_mode)) {
mMode = a.getInteger(R.styleable.PullToRefresh_mode, MODE_PULL_DOWN_TO_REFRESH);
}
// Refreshable View
// By passing the attrs, we can add ListView/GridView params via XML
mRefreshableView = createRefreshableView(context, attrs);
addRefreshableView(context, mRefreshableView);
// Loading View Strings
String pullLabel = context.getString(R.string.pull_to_refresh_pull_label);
String refreshingLabel = context.getString(R.string.pull_to_refresh_refreshing_label);
String releaseLabel = context.getString(R.string.pull_to_refresh_release_label);
// Add Loading Views
if (mMode == MODE_PULL_DOWN_TO_REFRESH || mMode == MODE_BOTH) {
mHeaderLayout = new LoadingLayout(context, MODE_PULL_DOWN_TO_REFRESH, releaseLabel, pullLabel,
refreshingLabel, a);
addView(mHeaderLayout, 0, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
measureView(mHeaderLayout);
mHeaderHeight = mHeaderLayout.getMeasuredHeight();
}
if (mMode == MODE_PULL_UP_TO_REFRESH || mMode == MODE_BOTH) {
mFooterLayout = new LoadingLayout(context, MODE_PULL_UP_TO_REFRESH, releaseLabel, pullLabel,
refreshingLabel, a);
addView(mFooterLayout, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
measureView(mFooterLayout);
mHeaderHeight = mFooterLayout.getMeasuredHeight();
}
// Styleables from XML
if (a.hasValue(R.styleable.PullToRefresh_headerBackground)) {
setBackgroundResource(a.getResourceId(R.styleable.PullToRefresh_headerBackground, Color.WHITE));
}
if (a.hasValue(R.styleable.PullToRefresh_adapterViewBackground)) {
mRefreshableView.setBackgroundResource(a.getResourceId(R.styleable.PullToRefresh_adapterViewBackground,
Color.WHITE));
}
a.recycle();
a = null;
// Hide Loading Views
switch (mMode) {
case MODE_BOTH:
setPadding(0, -mHeaderHeight, 0, -mHeaderHeight);
break;
case MODE_PULL_UP_TO_REFRESH:
setPadding(0, 0, 0, -mHeaderHeight);
break;
case MODE_PULL_DOWN_TO_REFRESH:
default:
setPadding(0, -mHeaderHeight, 0, 0);
break;
}
// If we're not using MODE_BOTH, then just set mCurrentMode to current
// mMode
if (mMode != MODE_BOTH) {
mCurrentMode = mMode;
}
}
private void measureView(View child) {
ViewGroup.LayoutParams p = child.getLayoutParams();
if (p == null) {
p = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
}
int childWidthSpec = ViewGroup.getChildMeasureSpec(0, 0, p.width);
int lpHeight = p.height;
int childHeightSpec;
if (lpHeight > 0) {
childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight, MeasureSpec.EXACTLY);
} else {
childHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
}
child.measure(childWidthSpec, childHeightSpec);
}
/**
* Actions a Pull Event
*
* @return true if the Event has been handled, false if there has been no
* change
*/
private boolean pullEvent() {
final int newHeight;
final int oldHeight = getScrollY();
switch (mCurrentMode) {
case MODE_PULL_UP_TO_REFRESH:
newHeight = Math.round(Math.max(mInitialMotionY - mLastMotionY, 0) / FRICTION);
break;
case MODE_PULL_DOWN_TO_REFRESH:
default:
newHeight = Math.round(Math.min(mInitialMotionY - mLastMotionY, 0) / FRICTION);
break;
}
setHeaderScroll(newHeight);
if (newHeight != 0) {
if (mState == PULL_TO_REFRESH && mHeaderHeight < Math.abs(newHeight)) {
mState = RELEASE_TO_REFRESH;
switch (mCurrentMode) {
case MODE_PULL_UP_TO_REFRESH:
mFooterLayout.releaseToRefresh();
break;
case MODE_PULL_DOWN_TO_REFRESH:
mHeaderLayout.releaseToRefresh();
break;
}
return true;
} else if (mState == RELEASE_TO_REFRESH && mHeaderHeight >= Math.abs(newHeight)) {
mState = PULL_TO_REFRESH;
switch (mCurrentMode) {
case MODE_PULL_UP_TO_REFRESH:
mFooterLayout.pullToRefresh();
break;
case MODE_PULL_DOWN_TO_REFRESH:
mHeaderLayout.pullToRefresh();
break;
}
return true;
}
}
return oldHeight != newHeight;
}
private boolean isReadyForPull() {
switch (mMode) {
case MODE_PULL_DOWN_TO_REFRESH:
return isReadyForPullDown();
case MODE_PULL_UP_TO_REFRESH:
return isReadyForPullUp();
case MODE_BOTH:
return isReadyForPullUp() || isReadyForPullDown();
}
return false;
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
/**
* Simple Listener to listen for any callbacks to Refresh.
*
* @author Chris Banes
*/
public static interface OnRefreshListener {
/**
* onRefresh will be called for both Pull Down from top, and Pull Up
* from Bottom
*/
public void onRefresh();
}
/**
* An advanced version of the Listener to listen for callbacks to Refresh.
* This listener is different as it allows you to differentiate between Pull
* Ups, and Pull Downs.
*
* @author Chris Banes
*/
public static interface OnRefreshListener2 {
/**
* onPullDownToRefresh will be called only when the user has Pulled Down
* from the top, and released.
*/
public void onPullDownToRefresh();
/**
* onPullUpToRefresh will be called only when the user has Pulled Up
* from the bottom, and released.
*/
public void onPullUpToRefresh();
}
public static interface OnLastItemVisibleListener {
public void onLastItemVisible();
}
@Override
public void setLongClickable(boolean longClickable) {
getRefreshableView().setLongClickable(longClickable);
}
}
| library/src/com/handmark/pulltorefresh/library/PullToRefreshBase.java | package com.handmark.pulltorefresh.library;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.Interpolator;
import android.widget.LinearLayout;
import com.handmark.pulltorefresh.library.internal.LoadingLayout;
public abstract class PullToRefreshBase<T extends View> extends LinearLayout {
final class SmoothScrollRunnable implements Runnable {
static final int ANIMATION_DURATION_MS = 190;
static final int ANIMATION_FPS = 1000 / 60;
private final Interpolator mInterpolator;
private final int mScrollToY;
private final int mScrollFromY;
private final Handler mHandler;
private boolean mContinueRunning = true;
private long mStartTime = -1;
private int mCurrentY = -1;
public SmoothScrollRunnable(Handler handler, int fromY, int toY) {
mHandler = handler;
mScrollFromY = fromY;
mScrollToY = toY;
mInterpolator = new AccelerateDecelerateInterpolator();
}
@Override
public void run() {
/**
* Only set mStartTime if this is the first time we're starting, else
* actually calculate the Y delta
*/
if (mStartTime == -1) {
mStartTime = System.currentTimeMillis();
} else {
/**
* We do do all calculations in long to reduce software float
* calculations. We use 1000 as it gives us good accuracy and
* small rounding errors
*/
long normalizedTime = (1000 * (System.currentTimeMillis() - mStartTime)) / ANIMATION_DURATION_MS;
normalizedTime = Math.max(Math.min(normalizedTime, 1000), 0);
final int deltaY = Math.round((mScrollFromY - mScrollToY)
* mInterpolator.getInterpolation(normalizedTime / 1000f));
mCurrentY = mScrollFromY - deltaY;
setHeaderScroll(mCurrentY);
}
// If we're not at the target Y, keep going...
if (mContinueRunning && mScrollToY != mCurrentY) {
mHandler.postDelayed(this, ANIMATION_FPS);
}
}
public void stop() {
mContinueRunning = false;
mHandler.removeCallbacks(this);
}
}
// ===========================================================
// Constants
// ===========================================================
static final boolean DEBUG = false;
static final String LOG_TAG = "PullToRefresh";
static final float FRICTION = 2.0f;
static final int PULL_TO_REFRESH = 0x0;
static final int RELEASE_TO_REFRESH = 0x1;
static final int REFRESHING = 0x2;
static final int MANUAL_REFRESHING = 0x3;
public static final int MODE_PULL_DOWN_TO_REFRESH = 0x1;
public static final int MODE_PULL_UP_TO_REFRESH = 0x2;
public static final int MODE_BOTH = 0x3;
// ===========================================================
// Fields
// ===========================================================
private int mTouchSlop;
private float mInitialMotionY;
private float mLastMotionX;
private float mLastMotionY;
private boolean mIsBeingDragged = false;
private int mState = PULL_TO_REFRESH;
private int mMode = MODE_PULL_DOWN_TO_REFRESH;
private int mCurrentMode;
private boolean mDisableScrollingWhileRefreshing = true;
T mRefreshableView;
private boolean mIsPullToRefreshEnabled = true;
private LoadingLayout mHeaderLayout;
private LoadingLayout mFooterLayout;
private int mHeaderHeight;
private final Handler mHandler = new Handler();
private OnRefreshListener mOnRefreshListener;
private SmoothScrollRunnable mCurrentSmoothScrollRunnable;
// ===========================================================
// Constructors
// ===========================================================
public PullToRefreshBase(Context context) {
super(context);
init(context, null);
}
public PullToRefreshBase(Context context, int mode) {
super(context);
mMode = mode;
init(context, null);
}
public PullToRefreshBase(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
// ===========================================================
// Getter & Setter
// ===========================================================
/**
* Deprecated. Use {@link #getRefreshableView()} from now on.
*
* @deprecated
* @return The Refreshable View which is currently wrapped
*/
public final T getAdapterView() {
return mRefreshableView;
}
/**
* Get the Wrapped Refreshable View. Anything returned here has already been
* added to the content view.
*
* @return The View which is currently wrapped
*/
public final T getRefreshableView() {
return mRefreshableView;
}
/**
* Whether Pull-to-Refresh is enabled
*
* @return enabled
*/
public final boolean isPullToRefreshEnabled() {
return mIsPullToRefreshEnabled;
}
/**
* Returns whether the widget has disabled scrolling on the Refreshable View
* while refreshing.
*
* @return true if the widget has disabled scrolling while refreshing
*/
public final boolean isDisableScrollingWhileRefreshing() {
return mDisableScrollingWhileRefreshing;
}
/**
* Returns whether the Widget is currently in the Refreshing mState
*
* @return true if the Widget is currently refreshing
*/
public final boolean isRefreshing() {
return mState == REFRESHING || mState == MANUAL_REFRESHING;
}
/**
* By default the Widget disabled scrolling on the Refreshable View while
* refreshing. This method can change this behaviour.
*
* @param disableScrollingWhileRefreshing
* - true if you want to disable scrolling while refreshing
*/
public final void setDisableScrollingWhileRefreshing(boolean disableScrollingWhileRefreshing) {
mDisableScrollingWhileRefreshing = disableScrollingWhileRefreshing;
}
/**
* Mark the current Refresh as complete. Will Reset the UI and hide the
* Refreshing View
*/
public final void onRefreshComplete() {
if (mState != PULL_TO_REFRESH) {
resetHeader();
}
}
/**
* Set OnRefreshListener for the Widget
*
* @param listener
* - Listener to be used when the Widget is set to Refresh
*/
public final void setOnRefreshListener(OnRefreshListener listener) {
mOnRefreshListener = listener;
}
/**
* A mutator to enable/disable Pull-to-Refresh for the current View
*
* @param enable
* Whether Pull-To-Refresh should be used
*/
public final void setPullToRefreshEnabled(boolean enable) {
mIsPullToRefreshEnabled = enable;
}
/**
* Set Text to show when the Widget is being pulled, and will refresh when
* released
*
* @param releaseLabel
* - String to display
*/
public void setReleaseLabel(String releaseLabel) {
if (null != mHeaderLayout) {
mHeaderLayout.setReleaseLabel(releaseLabel);
}
if (null != mFooterLayout) {
mFooterLayout.setReleaseLabel(releaseLabel);
}
}
/**
* Set Text to show when the Widget is being Pulled
*
* @param pullLabel
* - String to display
*/
public void setPullLabel(String pullLabel) {
if (null != mHeaderLayout) {
mHeaderLayout.setPullLabel(pullLabel);
}
if (null != mFooterLayout) {
mFooterLayout.setPullLabel(pullLabel);
}
}
/**
* Set Text to show when the Widget is refreshing
*
* @param refreshingLabel
* - String to display
*/
public void setRefreshingLabel(String refreshingLabel) {
if (null != mHeaderLayout) {
mHeaderLayout.setRefreshingLabel(refreshingLabel);
}
if (null != mFooterLayout) {
mFooterLayout.setRefreshingLabel(refreshingLabel);
}
}
public final void setRefreshing() {
setRefreshing(true);
}
/**
* Sets the Widget to be in the refresh mState. The UI will be updated to
* show the 'Refreshing' view.
*
* @param doScroll
* - true if you want to force a scroll to the Refreshing view.
*/
public final void setRefreshing(boolean doScroll) {
if (!isRefreshing()) {
setRefreshingInternal(doScroll);
mState = MANUAL_REFRESHING;
}
}
public final boolean hasPullFromTop() {
return mCurrentMode != MODE_PULL_UP_TO_REFRESH;
}
// ===========================================================
// Methods for/from SuperClass/Interfaces
// ===========================================================
@Override
public final boolean onTouchEvent(MotionEvent event) {
if (!mIsPullToRefreshEnabled) {
return false;
}
if (isRefreshing() && mDisableScrollingWhileRefreshing) {
return true;
}
if (event.getAction() == MotionEvent.ACTION_DOWN && event.getEdgeFlags() != 0) {
return false;
}
switch (event.getAction()) {
case MotionEvent.ACTION_MOVE: {
if (mIsBeingDragged) {
mLastMotionY = event.getY();
pullEvent();
return true;
}
break;
}
case MotionEvent.ACTION_DOWN: {
if (isReadyForPull()) {
mLastMotionY = mInitialMotionY = event.getY();
return true;
}
break;
}
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP: {
if (mIsBeingDragged) {
mIsBeingDragged = false;
if (mState == RELEASE_TO_REFRESH && null != mOnRefreshListener) {
setRefreshingInternal(true);
mOnRefreshListener.onRefresh();
} else {
smoothScrollTo(0);
}
return true;
}
break;
}
}
return false;
}
@Override
public final boolean onInterceptTouchEvent(MotionEvent event) {
if (!mIsPullToRefreshEnabled) {
return false;
}
if (isRefreshing() && mDisableScrollingWhileRefreshing) {
return true;
}
final int action = event.getAction();
if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP) {
mIsBeingDragged = false;
return false;
}
if (action != MotionEvent.ACTION_DOWN && mIsBeingDragged) {
return true;
}
switch (action) {
case MotionEvent.ACTION_MOVE: {
if (isReadyForPull()) {
final float y = event.getY();
final float dy = y - mLastMotionY;
final float yDiff = Math.abs(dy);
final float xDiff = Math.abs(event.getX() - mLastMotionX);
if (yDiff > mTouchSlop && yDiff > xDiff) {
if ((mMode == MODE_PULL_DOWN_TO_REFRESH || mMode == MODE_BOTH) && dy >= 0.0001f
&& isReadyForPullDown()) {
mLastMotionY = y;
mIsBeingDragged = true;
if (mMode == MODE_BOTH) {
mCurrentMode = MODE_PULL_DOWN_TO_REFRESH;
}
} else if ((mMode == MODE_PULL_UP_TO_REFRESH || mMode == MODE_BOTH) && dy <= 0.0001f
&& isReadyForPullUp()) {
mLastMotionY = y;
mIsBeingDragged = true;
if (mMode == MODE_BOTH) {
mCurrentMode = MODE_PULL_UP_TO_REFRESH;
}
}
}
}
break;
}
case MotionEvent.ACTION_DOWN: {
if (isReadyForPull()) {
mLastMotionY = mInitialMotionY = event.getY();
mLastMotionX = event.getX();
mIsBeingDragged = false;
}
break;
}
}
return mIsBeingDragged;
}
protected void addRefreshableView(Context context, T refreshableView) {
addView(refreshableView, new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, 0, 1.0f));
}
/**
* This is implemented by derived classes to return the created View. If you
* need to use a custom View (such as a custom ListView), override this
* method and return an instance of your custom class.
*
* Be sure to set the ID of the view in this method, especially if you're
* using a ListActivity or ListFragment.
*
* @param context Context to create view with
* @param attrs
* AttributeSet from wrapped class. Means that anything you
* include in the XML layout declaration will be routed to the
* created View
* @return New instance of the Refreshable View
*/
protected abstract T createRefreshableView(Context context, AttributeSet attrs);
protected final int getCurrentMode() {
return mCurrentMode;
}
protected final LoadingLayout getFooterLayout() {
return mFooterLayout;
}
protected final LoadingLayout getHeaderLayout() {
return mHeaderLayout;
}
protected final int getHeaderHeight() {
return mHeaderHeight;
}
protected final int getMode() {
return mMode;
}
/**
* Implemented by derived class to return whether the View is in a mState
* where the user can Pull to Refresh by scrolling down.
*
* @return true if the View is currently the correct mState (for example, top
* of a ListView)
*/
protected abstract boolean isReadyForPullDown();
/**
* Implemented by derived class to return whether the View is in a mState
* where the user can Pull to Refresh by scrolling up.
*
* @return true if the View is currently in the correct mState (for example,
* bottom of a ListView)
*/
protected abstract boolean isReadyForPullUp();
// ===========================================================
// Methods
// ===========================================================
protected void resetHeader() {
mState = PULL_TO_REFRESH;
mIsBeingDragged = false;
if (null != mHeaderLayout) {
mHeaderLayout.reset();
}
if (null != mFooterLayout) {
mFooterLayout.reset();
}
smoothScrollTo(0);
}
protected void setRefreshingInternal(boolean doScroll) {
mState = REFRESHING;
if (null != mHeaderLayout) {
mHeaderLayout.refreshing();
}
if (null != mFooterLayout) {
mFooterLayout.refreshing();
}
if (doScroll) {
smoothScrollTo(mCurrentMode == MODE_PULL_DOWN_TO_REFRESH ? -mHeaderHeight : mHeaderHeight);
}
}
protected final void setHeaderScroll(int y) {
scrollTo(0, y);
}
protected final void smoothScrollTo(int y) {
if (null != mCurrentSmoothScrollRunnable) {
mCurrentSmoothScrollRunnable.stop();
}
if (getScrollY() != y) {
mCurrentSmoothScrollRunnable = new SmoothScrollRunnable(mHandler, getScrollY(), y);
mHandler.post(mCurrentSmoothScrollRunnable);
}
}
private void init(Context context, AttributeSet attrs) {
setOrientation(LinearLayout.VERTICAL);
mTouchSlop = ViewConfiguration.getTouchSlop();
// Styleables from XML
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.PullToRefresh);
if (a.hasValue(R.styleable.PullToRefresh_mode)) {
mMode = a.getInteger(R.styleable.PullToRefresh_mode, MODE_PULL_DOWN_TO_REFRESH);
}
// Refreshable View
// By passing the attrs, we can add ListView/GridView params via XML
mRefreshableView = createRefreshableView(context, attrs);
addRefreshableView(context, mRefreshableView);
// Loading View Strings
String pullLabel = context.getString(R.string.pull_to_refresh_pull_label);
String refreshingLabel = context.getString(R.string.pull_to_refresh_refreshing_label);
String releaseLabel = context.getString(R.string.pull_to_refresh_release_label);
// Add Loading Views
if (mMode == MODE_PULL_DOWN_TO_REFRESH || mMode == MODE_BOTH) {
mHeaderLayout = new LoadingLayout(context, MODE_PULL_DOWN_TO_REFRESH, releaseLabel, pullLabel,
refreshingLabel, a);
addView(mHeaderLayout, 0, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
measureView(mHeaderLayout);
mHeaderHeight = mHeaderLayout.getMeasuredHeight();
}
if (mMode == MODE_PULL_UP_TO_REFRESH || mMode == MODE_BOTH) {
mFooterLayout = new LoadingLayout(context, MODE_PULL_UP_TO_REFRESH, releaseLabel, pullLabel, refreshingLabel, a);
addView(mFooterLayout, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
measureView(mFooterLayout);
mHeaderHeight = mFooterLayout.getMeasuredHeight();
}
// Styleables from XML
if (a.hasValue(R.styleable.PullToRefresh_headerBackground)) {
setBackgroundResource(a.getResourceId(R.styleable.PullToRefresh_headerBackground, Color.WHITE));
}
if (a.hasValue(R.styleable.PullToRefresh_adapterViewBackground)) {
mRefreshableView.setBackgroundResource(a.getResourceId(R.styleable.PullToRefresh_adapterViewBackground,
Color.WHITE));
}
a.recycle();
a = null;
// Hide Loading Views
switch (mMode) {
case MODE_BOTH:
setPadding(0, -mHeaderHeight, 0, -mHeaderHeight);
break;
case MODE_PULL_UP_TO_REFRESH:
setPadding(0, 0, 0, -mHeaderHeight);
break;
case MODE_PULL_DOWN_TO_REFRESH:
default:
setPadding(0, -mHeaderHeight, 0, 0);
break;
}
// If we're not using MODE_BOTH, then just set mCurrentMode to current
// mMode
if (mMode != MODE_BOTH) {
mCurrentMode = mMode;
}
}
private void measureView(View child) {
ViewGroup.LayoutParams p = child.getLayoutParams();
if (p == null) {
p = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
}
int childWidthSpec = ViewGroup.getChildMeasureSpec(0, 0, p.width);
int lpHeight = p.height;
int childHeightSpec;
if (lpHeight > 0) {
childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight, MeasureSpec.EXACTLY);
} else {
childHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
}
child.measure(childWidthSpec, childHeightSpec);
}
/**
* Actions a Pull Event
*
* @return true if the Event has been handled, false if there has been no
* change
*/
private boolean pullEvent() {
final int newHeight;
final int oldHeight = getScrollY();
switch (mCurrentMode) {
case MODE_PULL_UP_TO_REFRESH:
newHeight = Math.round(Math.max(mInitialMotionY - mLastMotionY, 0) / FRICTION);
break;
case MODE_PULL_DOWN_TO_REFRESH:
default:
newHeight = Math.round(Math.min(mInitialMotionY - mLastMotionY, 0) / FRICTION);
break;
}
setHeaderScroll(newHeight);
if (newHeight != 0) {
if (mState == PULL_TO_REFRESH && mHeaderHeight < Math.abs(newHeight)) {
mState = RELEASE_TO_REFRESH;
switch (mCurrentMode) {
case MODE_PULL_UP_TO_REFRESH:
mFooterLayout.releaseToRefresh();
break;
case MODE_PULL_DOWN_TO_REFRESH:
mHeaderLayout.releaseToRefresh();
break;
}
return true;
} else if (mState == RELEASE_TO_REFRESH && mHeaderHeight >= Math.abs(newHeight)) {
mState = PULL_TO_REFRESH;
switch (mCurrentMode) {
case MODE_PULL_UP_TO_REFRESH:
mFooterLayout.pullToRefresh();
break;
case MODE_PULL_DOWN_TO_REFRESH:
mHeaderLayout.pullToRefresh();
break;
}
return true;
}
}
return oldHeight != newHeight;
}
private boolean isReadyForPull() {
switch (mMode) {
case MODE_PULL_DOWN_TO_REFRESH:
return isReadyForPullDown();
case MODE_PULL_UP_TO_REFRESH:
return isReadyForPullUp();
case MODE_BOTH:
return isReadyForPullUp() || isReadyForPullDown();
}
return false;
}
// ===========================================================
// Inner and Anonymous Classes
// ===========================================================
public static interface OnRefreshListener {
public void onRefresh();
}
public static interface OnLastItemVisibleListener {
public void onLastItemVisible();
}
@Override
public void setLongClickable(boolean longClickable) {
getRefreshableView().setLongClickable(longClickable);
}
}
| New listener, OnRefreshListener2. Allows you now to differentiate between Pull Downs and Pull Ups
| library/src/com/handmark/pulltorefresh/library/PullToRefreshBase.java | New listener, OnRefreshListener2. Allows you now to differentiate between Pull Downs and Pull Ups | <ide><path>ibrary/src/com/handmark/pulltorefresh/library/PullToRefreshBase.java
<ide> public void run() {
<ide>
<ide> /**
<del> * Only set mStartTime if this is the first time we're starting, else
<del> * actually calculate the Y delta
<add> * Only set mStartTime if this is the first time we're starting,
<add> * else actually calculate the Y delta
<ide> */
<ide> if (mStartTime == -1) {
<ide> mStartTime = System.currentTimeMillis();
<ide> normalizedTime = Math.max(Math.min(normalizedTime, 1000), 0);
<ide>
<ide> final int deltaY = Math.round((mScrollFromY - mScrollToY)
<del> * mInterpolator.getInterpolation(normalizedTime / 1000f));
<add> * mInterpolator.getInterpolation(normalizedTime / 1000f));
<ide> mCurrentY = mScrollFromY - deltaY;
<ide> setHeaderScroll(mCurrentY);
<ide> }
<ide>
<ide> // If we're not at the target Y, keep going...
<ide> if (mContinueRunning && mScrollToY != mCurrentY) {
<del> mHandler.postDelayed(this, ANIMATION_FPS);
<add> mHandler.postDelayed(this, ANIMATION_FPS);
<ide> }
<ide> }
<ide>
<ide> public void stop() {
<ide> mContinueRunning = false;
<del> mHandler.removeCallbacks(this);
<add> mHandler.removeCallbacks(this);
<ide> }
<ide> }
<ide>
<ide> // Constants
<ide> // ===========================================================
<ide>
<del> static final boolean DEBUG = false;
<del> static final String LOG_TAG = "PullToRefresh";
<add> static final boolean DEBUG = false;
<add> static final String LOG_TAG = "PullToRefresh";
<ide>
<ide> static final float FRICTION = 2.0f;
<ide>
<ide> private final Handler mHandler = new Handler();
<ide>
<ide> private OnRefreshListener mOnRefreshListener;
<add> private OnRefreshListener2 mOnRefreshListener2;
<ide>
<ide> private SmoothScrollRunnable mCurrentSmoothScrollRunnable;
<ide>
<ide> *
<ide> * @return The View which is currently wrapped
<ide> */
<del> public final T getRefreshableView() {
<add> public final T getRefreshableView() {
<ide> return mRefreshableView;
<ide> }
<ide>
<ide> }
<ide>
<ide> /**
<add> * Set OnRefreshListener for the Widget
<add> *
<add> * @param listener
<add> * - Listener to be used when the Widget is set to Refresh
<add> */
<add> public final void setOnRefreshListener(OnRefreshListener2 listener) {
<add> mOnRefreshListener2 = listener;
<add> }
<add>
<add> /**
<ide> * A mutator to enable/disable Pull-to-Refresh for the current View
<ide> *
<ide> * @param enable
<ide> */
<ide> public void setReleaseLabel(String releaseLabel) {
<ide> if (null != mHeaderLayout) {
<del> mHeaderLayout.setReleaseLabel(releaseLabel);
<add> mHeaderLayout.setReleaseLabel(releaseLabel);
<ide> }
<ide> if (null != mFooterLayout) {
<del> mFooterLayout.setReleaseLabel(releaseLabel);
<add> mFooterLayout.setReleaseLabel(releaseLabel);
<ide> }
<ide> }
<ide>
<ide> * - String to display
<ide> */
<ide> public void setPullLabel(String pullLabel) {
<del> if (null != mHeaderLayout) {
<add> if (null != mHeaderLayout) {
<ide> mHeaderLayout.setPullLabel(pullLabel);
<del> }
<del> if (null != mFooterLayout) {
<add> }
<add> if (null != mFooterLayout) {
<ide> mFooterLayout.setPullLabel(pullLabel);
<ide> }
<ide> }
<ide> public void setRefreshingLabel(String refreshingLabel) {
<ide> if (null != mHeaderLayout) {
<ide> mHeaderLayout.setRefreshingLabel(refreshingLabel);
<del> }
<add> }
<ide> if (null != mFooterLayout) {
<ide> mFooterLayout.setRefreshingLabel(refreshingLabel);
<ide> }
<ide> if (mIsBeingDragged) {
<ide> mIsBeingDragged = false;
<ide>
<del> if (mState == RELEASE_TO_REFRESH && null != mOnRefreshListener) {
<del> setRefreshingInternal(true);
<del> mOnRefreshListener.onRefresh();
<del> } else {
<del> smoothScrollTo(0);
<add> if (mState == RELEASE_TO_REFRESH) {
<add>
<add> if (null != mOnRefreshListener) {
<add> setRefreshingInternal(true);
<add> mOnRefreshListener.onRefresh();
<add> return true;
<add>
<add> } else if (null != mOnRefreshListener2) {
<add> setRefreshingInternal(true);
<add> if (mCurrentMode == MODE_PULL_DOWN_TO_REFRESH) {
<add> mOnRefreshListener2.onPullDownToRefresh();
<add> } else if (mCurrentMode == MODE_PULL_UP_TO_REFRESH) {
<add> mOnRefreshListener2.onPullUpToRefresh();
<add> }
<add> return true;
<add> }
<add>
<add> return true;
<ide> }
<add>
<add> smoothScrollTo(0);
<ide> return true;
<ide> }
<ide> break;
<ide> * Be sure to set the ID of the view in this method, especially if you're
<ide> * using a ListActivity or ListFragment.
<ide> *
<del> * @param context Context to create view with
<add> * @param context
<add> * Context to create view with
<ide> * @param attrs
<ide> * AttributeSet from wrapped class. Means that anything you
<ide> * include in the XML layout declaration will be routed to the
<ide> * Implemented by derived class to return whether the View is in a mState
<ide> * where the user can Pull to Refresh by scrolling down.
<ide> *
<del> * @return true if the View is currently the correct mState (for example, top
<del> * of a ListView)
<add> * @return true if the View is currently the correct mState (for example,
<add> * top of a ListView)
<ide> */
<ide> protected abstract boolean isReadyForPullDown();
<ide>
<ide> }
<ide>
<ide> smoothScrollTo(0);
<del> }
<add> }
<ide>
<ide> protected void setRefreshingInternal(boolean doScroll) {
<del> mState = REFRESHING;
<add> mState = REFRESHING;
<ide>
<ide> if (null != mHeaderLayout) {
<ide> mHeaderLayout.refreshing();
<ide> }
<ide>
<ide> protected final void smoothScrollTo(int y) {
<del> if (null != mCurrentSmoothScrollRunnable) {
<add> if (null != mCurrentSmoothScrollRunnable) {
<ide> mCurrentSmoothScrollRunnable.stop();
<ide> }
<ide>
<ide> if (getScrollY() != y) {
<ide> mCurrentSmoothScrollRunnable = new SmoothScrollRunnable(mHandler, getScrollY(), y);
<del> mHandler.post(mCurrentSmoothScrollRunnable);
<add> mHandler.post(mCurrentSmoothScrollRunnable);
<ide> }
<ide> }
<ide>
<ide>
<ide> // Add Loading Views
<ide> if (mMode == MODE_PULL_DOWN_TO_REFRESH || mMode == MODE_BOTH) {
<del> mHeaderLayout = new LoadingLayout(context, MODE_PULL_DOWN_TO_REFRESH, releaseLabel, pullLabel,
<add> mHeaderLayout = new LoadingLayout(context, MODE_PULL_DOWN_TO_REFRESH, releaseLabel, pullLabel,
<ide> refreshingLabel, a);
<ide> addView(mHeaderLayout, 0, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
<ide> ViewGroup.LayoutParams.WRAP_CONTENT));
<ide> mHeaderHeight = mHeaderLayout.getMeasuredHeight();
<ide> }
<ide> if (mMode == MODE_PULL_UP_TO_REFRESH || mMode == MODE_BOTH) {
<del> mFooterLayout = new LoadingLayout(context, MODE_PULL_UP_TO_REFRESH, releaseLabel, pullLabel, refreshingLabel, a);
<add> mFooterLayout = new LoadingLayout(context, MODE_PULL_UP_TO_REFRESH, releaseLabel, pullLabel,
<add> refreshingLabel, a);
<ide> addView(mFooterLayout, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
<ide> ViewGroup.LayoutParams.WRAP_CONTENT));
<ide> measureView(mFooterLayout);
<ide>
<ide> setHeaderScroll(newHeight);
<ide>
<del> if (newHeight != 0) {
<add> if (newHeight != 0) {
<ide> if (mState == PULL_TO_REFRESH && mHeaderHeight < Math.abs(newHeight)) {
<ide> mState = RELEASE_TO_REFRESH;
<ide>
<ide> // Inner and Anonymous Classes
<ide> // ===========================================================
<ide>
<add> /**
<add> * Simple Listener to listen for any callbacks to Refresh.
<add> *
<add> * @author Chris Banes
<add> */
<ide> public static interface OnRefreshListener {
<ide>
<add> /**
<add> * onRefresh will be called for both Pull Down from top, and Pull Up
<add> * from Bottom
<add> */
<ide> public void onRefresh();
<add>
<add> }
<add>
<add> /**
<add> * An advanced version of the Listener to listen for callbacks to Refresh.
<add> * This listener is different as it allows you to differentiate between Pull
<add> * Ups, and Pull Downs.
<add> *
<add> * @author Chris Banes
<add> */
<add> public static interface OnRefreshListener2 {
<add>
<add> /**
<add> * onPullDownToRefresh will be called only when the user has Pulled Down
<add> * from the top, and released.
<add> */
<add> public void onPullDownToRefresh();
<add>
<add> /**
<add> * onPullUpToRefresh will be called only when the user has Pulled Up
<add> * from the bottom, and released.
<add> */
<add> public void onPullUpToRefresh();
<ide>
<ide> }
<ide> |
|
Java | epl-1.0 | error: pathspec 'codenvy-ext-datasource-client/src/main/java/com/codenvy/ide/ext/datasource/client/ssl/SslExtension.java' did not match any file(s) known to git
| 7743ab6b33122ebe7f1813ec9daefd6fde1ccb8d | 1 | codenvy/plugin-datasource,codenvy/plugin-datasource | package com.codenvy.ide.ext.datasource.client.ssl;
import com.codenvy.ide.api.extension.Extension;
import com.codenvy.ide.rest.AsyncRequestCallback;
import com.codenvy.ide.util.loging.Log;
import com.google.inject.Inject;
import com.google.inject.Singleton;
@Singleton
@Extension(title = "SSL Extension", version = "1.0.0")
public class SslExtension {
@Inject
public SslExtension(SslKeyStoreClientService sslKeyStoreClientService) {
Log.info(SslExtension.class, "Init SSL callback");
sslKeyStoreClientService.init(new AsyncRequestCallback<Void>() {
@Override
public void onSuccess(Void result) {
Log.info(SslExtension.class, "Succeeded SSL init");
}
@Override
public void onFailure(Throwable exception) {
Log.error(SslExtension.class, "Failed tnit SSL callback", exception);
}
});
}
}
| codenvy-ext-datasource-client/src/main/java/com/codenvy/ide/ext/datasource/client/ssl/SslExtension.java | #41 Adding missing SSL Client Extension
| codenvy-ext-datasource-client/src/main/java/com/codenvy/ide/ext/datasource/client/ssl/SslExtension.java | #41 Adding missing SSL Client Extension | <ide><path>odenvy-ext-datasource-client/src/main/java/com/codenvy/ide/ext/datasource/client/ssl/SslExtension.java
<add>package com.codenvy.ide.ext.datasource.client.ssl;
<add>
<add>import com.codenvy.ide.api.extension.Extension;
<add>import com.codenvy.ide.rest.AsyncRequestCallback;
<add>import com.codenvy.ide.util.loging.Log;
<add>import com.google.inject.Inject;
<add>import com.google.inject.Singleton;
<add>
<add>@Singleton
<add>@Extension(title = "SSL Extension", version = "1.0.0")
<add>public class SslExtension {
<add>
<add> @Inject
<add> public SslExtension(SslKeyStoreClientService sslKeyStoreClientService) {
<add> Log.info(SslExtension.class, "Init SSL callback");
<add> sslKeyStoreClientService.init(new AsyncRequestCallback<Void>() {
<add> @Override
<add> public void onSuccess(Void result) {
<add> Log.info(SslExtension.class, "Succeeded SSL init");
<add> }
<add>
<add> @Override
<add> public void onFailure(Throwable exception) {
<add> Log.error(SslExtension.class, "Failed tnit SSL callback", exception);
<add> }
<add> });
<add> }
<add>} |
|
Java | apache-2.0 | 7897a368dee319c7d948fd6756d7f4570bb40f8a | 0 | reynoldsm88/drools,HHzzhz/drools,OnePaaS/drools,HHzzhz/drools,OnePaaS/drools,liupugong/drools,manstis/drools,liupugong/drools,vinodkiran/drools,jomarko/drools,jiripetrlik/drools,jiripetrlik/drools,liupugong/drools,vinodkiran/drools,ThomasLau/drools,winklerm/drools,ThomasLau/drools,prabasn/drools,HHzzhz/drools,lanceleverich/drools,ChallenHB/drools,Buble1981/MyDroolsFork,kedzie/drools-android,droolsjbpm/drools,kedzie/drools-android,liupugong/drools,292388900/drools,amckee23/drools,sutaakar/drools,sutaakar/drools,yurloc/drools,reynoldsm88/drools,droolsjbpm/drools,ngs-mtech/drools,sotty/drools,ngs-mtech/drools,prabasn/drools,mrietveld/drools,OnePaaS/drools,reynoldsm88/drools,OnePaaS/drools,ThiagoGarciaAlves/drools,jomarko/drools,sotty/drools,jiripetrlik/drools,ChallenHB/drools,sotty/drools,vinodkiran/drools,prabasn/drools,jomarko/drools,iambic69/drools,pperboires/PocDrools,amckee23/drools,lanceleverich/drools,sutaakar/drools,psiroky/drools,Buble1981/MyDroolsFork,jiripetrlik/drools,Buble1981/MyDroolsFork,mrrodriguez/drools,ThomasLau/drools,manstis/drools,sotty/drools,prabasn/drools,vinodkiran/drools,mswiderski/drools,winklerm/drools,iambic69/drools,292388900/drools,vinodkiran/drools,ngs-mtech/drools,sutaakar/drools,lanceleverich/drools,liupugong/drools,ChallenHB/drools,romartin/drools,mrrodriguez/drools,ThiagoGarciaAlves/drools,mrrodriguez/drools,yurloc/drools,ChallenHB/drools,sutaakar/drools,ThomasLau/drools,Buble1981/MyDroolsFork,ThomasLau/drools,TonnyFeng/drools,yurloc/drools,ThiagoGarciaAlves/drools,mswiderski/drools,pperboires/PocDrools,kedzie/drools-android,kedzie/drools-android,pwachira/droolsexamples,reynoldsm88/drools,yurloc/drools,ngs-mtech/drools,292388900/drools,292388900/drools,manstis/drools,kevinpeterson/drools,droolsjbpm/drools,romartin/drools,lanceleverich/drools,winklerm/drools,iambic69/drools,romartin/drools,jomarko/drools,prabasn/drools,HHzzhz/drools,pperboires/PocDrools,romartin/drools,kevinpeterson/drools,kedzie/drools-android,manstis/drools,292388900/drools,kevinpeterson/drools,jiripetrlik/drools,mrietveld/drools,TonnyFeng/drools,HHzzhz/drools,rajashekharmunthakewill/drools,TonnyFeng/drools,psiroky/drools,sotty/drools,mrietveld/drools,winklerm/drools,TonnyFeng/drools,mrrodriguez/drools,kevinpeterson/drools,ThiagoGarciaAlves/drools,iambic69/drools,TonnyFeng/drools,reynoldsm88/drools,OnePaaS/drools,rajashekharmunthakewill/drools,amckee23/drools,manstis/drools,psiroky/drools,mrietveld/drools,mswiderski/drools,amckee23/drools,amckee23/drools,ThiagoGarciaAlves/drools,ngs-mtech/drools,ChallenHB/drools,winklerm/drools,psiroky/drools,mrrodriguez/drools,mswiderski/drools,droolsjbpm/drools,romartin/drools,iambic69/drools,rajashekharmunthakewill/drools,lanceleverich/drools,jomarko/drools,mrietveld/drools,pperboires/PocDrools,droolsjbpm/drools,rajashekharmunthakewill/drools,rajashekharmunthakewill/drools,kevinpeterson/drools | /*
* Copyright 2010 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.drools.reteoo;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import org.drools.common.BaseNode;
import org.drools.common.InternalFactHandle;
import org.drools.common.InternalWorkingMemory;
import org.drools.common.RuleBasePartitionId;
import org.drools.spi.PropagationContext;
public class CompositeLeftTupleSinkAdapter extends AbstractLeftTupleSinkAdapter {
private LeftTupleSinkNodeList sinks;
public CompositeLeftTupleSinkAdapter() {
super( RuleBasePartitionId.MAIN_PARTITION );
}
public CompositeLeftTupleSinkAdapter(final RuleBasePartitionId partitionId) {
super( partitionId );
this.sinks = new LeftTupleSinkNodeList();
}
public void addTupleSink(final LeftTupleSink sink) {
this.sinks.add( (LeftTupleSinkNode) sink );
}
public void removeTupleSink(final LeftTupleSink sink) {
this.sinks.remove( (LeftTupleSinkNode) sink );
}
public void createChildLeftTuplesforQuery(final LeftTuple leftTuple,
final RightTuple rightTuple,
boolean leftTupleMemoryEnabled) {
for ( LeftTupleSinkNode sink = this.sinks.getFirst(); sink != null; sink = sink.getNextLeftTupleSinkNode() ) {
LeftTuple child = new LeftTuple( leftTuple,
rightTuple,
null,
null,
sink,
leftTupleMemoryEnabled );
child.setLeftParentNext( leftTuple.firstChild );
leftTuple.firstChild = child;
}
}
public void propagateAssertLeftTuple(final LeftTuple leftTuple,
final RightTuple rightTuple,
final LeftTuple currentLeftChild,
final LeftTuple currentRightChild,
final PropagationContext context,
final InternalWorkingMemory workingMemory,
final boolean leftTupleMemoryEnabled) {
for ( LeftTupleSinkNode sink = this.sinks.getFirst(); sink != null; sink = sink.getNextLeftTupleSinkNode() ) {
LeftTuple newLeftTuple = new LeftTuple( leftTuple,
rightTuple,
currentLeftChild,
currentRightChild,
sink,
leftTupleMemoryEnabled );
doPropagateAssertLeftTuple( context,
workingMemory,
sink,
newLeftTuple );
}
}
public void propagateAssertLeftTuple(final LeftTuple tuple,
final PropagationContext context,
final InternalWorkingMemory workingMemory,
final boolean leftTupleMemoryEnabled) {
for ( LeftTupleSinkNode sink = this.sinks.getFirst(); sink != null; sink = sink.getNextLeftTupleSinkNode() ) {
doPropagateAssertLeftTuple( context,
workingMemory,
sink,
new LeftTuple( tuple,
sink,
leftTupleMemoryEnabled ) );
}
}
public void createAndPropagateAssertLeftTuple(final InternalFactHandle factHandle,
final PropagationContext context,
final InternalWorkingMemory workingMemory,
final boolean leftTupleMemoryEnabled) {
for ( LeftTupleSinkNode sink = this.sinks.getFirst(); sink != null; sink = sink.getNextLeftTupleSinkNode() ) {
doPropagateAssertLeftTuple( context,
workingMemory,
sink,
new LeftTuple( factHandle,
sink,
leftTupleMemoryEnabled ) );
}
}
public void propagateRetractLeftTuple(final LeftTuple leftTuple,
final PropagationContext context,
final InternalWorkingMemory workingMemory) {
LeftTuple child = leftTuple.firstChild;
while ( child != null ) {
LeftTuple temp = child.getLeftParentNext();
doPropagateRetractLeftTuple( context,
workingMemory,
child,
child.getLeftTupleSink() );
child.unlinkFromRightParent();
child.unlinkFromLeftParent();
child = temp;
}
}
public void propagateRetractLeftTupleDestroyRightTuple(final LeftTuple leftTuple,
final PropagationContext context,
final InternalWorkingMemory workingMemory) {
LeftTuple child = leftTuple.firstChild;
InternalFactHandle rightParent = child.getRightParent().getFactHandle();
while ( child != null ) {
LeftTuple temp = child.getLeftParentNext();
doPropagateRetractLeftTuple( context,
workingMemory,
child,
child.getLeftTupleSink() );
child.unlinkFromRightParent();
child.unlinkFromLeftParent();
child = temp;
}
workingMemory.getFactHandleFactory().destroyFactHandle( rightParent );
}
public void propagateRetractRightTuple(final RightTuple rightTuple,
final PropagationContext context,
final InternalWorkingMemory workingMemory) {
LeftTuple child = rightTuple.firstChild;
while ( child != null ) {
LeftTuple temp = child.getRightParentNext();
doPropagateRetractLeftTuple( context,
workingMemory,
child,
child.getLeftTupleSink() );
child.unlinkFromLeftParent();
child.unlinkFromRightParent();
child = temp;
}
}
public BaseNode getMatchingNode(BaseNode candidate) {
for ( LeftTupleSinkNode sink = this.sinks.getFirst(); sink != null; sink = sink.getNextLeftTupleSinkNode() ) {
if ( candidate.equals( sink ) ) {
return (BaseNode) sink;
}
}
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public LeftTupleSink[] getSinks() {
final LeftTupleSink[] sinkArray = new LeftTupleSink[this.sinks.size()];
int i = 0;
for ( LeftTupleSinkNode sink = this.sinks.getFirst(); sink != null; sink = sink.getNextLeftTupleSinkNode() ) {
sinkArray[i++] = sink;
}
return sinkArray;
}
public int size() {
return this.sinks.size();
}
public void readExternal(ObjectInput in) throws IOException,
ClassNotFoundException {
super.readExternal( in );
this.sinks = (LeftTupleSinkNodeList) in.readObject();
}
public void writeExternal(ObjectOutput out) throws IOException {
super.writeExternal( out );
out.writeObject( this.sinks );
}
public void doPropagateAssertLeftTuple(PropagationContext context,
InternalWorkingMemory workingMemory,
LeftTuple leftTuple,
LeftTupleSink sink) {
sink.assertLeftTuple( leftTuple, context, workingMemory );
}
/**
* This is a hook method that may be overriden by subclasses. Please keep it
* protected.
*
* @param context
* @param workingMemory
* @param sink
* @param leftTuple
*/
protected void doPropagateAssertLeftTuple(PropagationContext context,
InternalWorkingMemory workingMemory,
LeftTupleSinkNode sink,
LeftTuple leftTuple) {
sink.assertLeftTuple( leftTuple,
context,
workingMemory );
}
/**
* This is a hook method that may be overriden by subclasses. Please keep it
* protected.
*
* @param context
* @param workingMemory
* @param leftTuple
* @param sink
*/
protected void doPropagateRetractLeftTuple(PropagationContext context,
InternalWorkingMemory workingMemory,
LeftTuple leftTuple,
LeftTupleSink sink) {
sink.retractLeftTuple( leftTuple,
context,
workingMemory );
}
public void doPropagateModifyObject(InternalFactHandle factHandle,
ModifyPreviousTuples modifyPreviousTuples,
PropagationContext context,
InternalWorkingMemory workingMemory,
LeftTupleSink sink) {
sink.modifyLeftTuple( factHandle,
modifyPreviousTuples,
context,
workingMemory );
}
// related to true modify
//this.sink.propagateModifyObject( factHandle, modifyPreviousTuples, context, workingMemory );
public void propagateModifyObject(InternalFactHandle factHandle,
ModifyPreviousTuples modifyPreviousTuples,
PropagationContext context,
InternalWorkingMemory workingMemory) {
for ( LeftTupleSinkNode sink = this.sinks.getFirst(); sink != null; sink = sink.getNextLeftTupleSinkNode() ) {
doPropagateModifyObject( factHandle,
modifyPreviousTuples,
context,
workingMemory,
sink );
}
}
public LeftTuple propagateModifyChildLeftTuple(LeftTuple childLeftTuple,
RightTuple parentRightTuple,
PropagationContext context,
InternalWorkingMemory workingMemory,
boolean tupleMemoryEnabled) {
// iterate to find all child tuples for the shared node
while ( childLeftTuple != null && childLeftTuple.getRightParent() == parentRightTuple ) {
// this will iterate for each child node when the
// the current node is shared
// preserve the current LeftTuple, as we need to iterate to the next before re-adding
LeftTuple temp = childLeftTuple;
childLeftTuple.getLeftTupleSink().modifyLeftTuple( childLeftTuple,
context,
workingMemory );
childLeftTuple = childLeftTuple.getLeftParentNext();
temp.reAddRight();
}
return childLeftTuple;
}
public LeftTuple propagateModifyChildLeftTuple(LeftTuple childLeftTuple,
LeftTuple parentLeftTuple,
PropagationContext context,
InternalWorkingMemory workingMemory,
boolean tupleMemoryEnabled) {
// iterate to find all child tuples for the shared node
while ( childLeftTuple != null && childLeftTuple.getLeftParent() == parentLeftTuple ) {
// this will iterate for each child node when the
// the current node is shared
// preserve the current LeftTuple, as we need to iterate to the next before re-adding
LeftTuple temp = childLeftTuple;
childLeftTuple.getLeftTupleSink().modifyLeftTuple( childLeftTuple,
context,
workingMemory );
childLeftTuple = childLeftTuple.getRightParentNext();
temp.reAddLeft();
}
return childLeftTuple;
}
public void propagateModifyChildLeftTuple(LeftTuple leftTuple,
PropagationContext context,
InternalWorkingMemory workingMemory,
boolean tupleMemoryEnabled) {
for ( LeftTuple childLeftTuple = leftTuple.firstChild; childLeftTuple != null; childLeftTuple = (LeftTuple) childLeftTuple.getLeftParentNext() ) {
childLeftTuple.getLeftTupleSink().modifyLeftTuple( childLeftTuple,
context,
workingMemory );
}
}
public LeftTuple propagateRetractChildLeftTuple(LeftTuple childLeftTuple,
RightTuple parentRightTuple,
PropagationContext context,
InternalWorkingMemory workingMemory) {
// iterate to find all child tuples for the shared node
while ( childLeftTuple != null && childLeftTuple.getRightParent() == parentRightTuple ) {
// this will iterate for each child node when the
// the current node is shared
LeftTuple temp = childLeftTuple.getLeftParentNext();
doPropagateRetractLeftTuple( context,
workingMemory,
childLeftTuple,
childLeftTuple.getLeftTupleSink() );
childLeftTuple.unlinkFromRightParent();
childLeftTuple.unlinkFromLeftParent();
childLeftTuple = temp;
}
return childLeftTuple;
}
public LeftTuple propagateRetractChildLeftTuple(LeftTuple childLeftTuple,
LeftTuple parentLeftTuple,
PropagationContext context,
InternalWorkingMemory workingMemory) {
// iterate to find all child tuples for the shared node
while ( childLeftTuple != null && childLeftTuple.getLeftParent() == parentLeftTuple ) {
// this will iterate for each child node when the
// the current node is shared
LeftTuple temp = childLeftTuple.getRightParentNext();
doPropagateRetractLeftTuple( context,
workingMemory,
childLeftTuple,
childLeftTuple.getLeftTupleSink() );
childLeftTuple.unlinkFromRightParent();
childLeftTuple.unlinkFromLeftParent();
childLeftTuple = temp;
}
return childLeftTuple;
}
}
| drools-core/src/main/java/org/drools/reteoo/CompositeLeftTupleSinkAdapter.java | /*
* Copyright 2010 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.drools.reteoo;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import org.drools.common.BaseNode;
import org.drools.common.InternalFactHandle;
import org.drools.common.InternalWorkingMemory;
import org.drools.common.RuleBasePartitionId;
import org.drools.spi.PropagationContext;
public class CompositeLeftTupleSinkAdapter extends AbstractLeftTupleSinkAdapter {
private LeftTupleSinkNodeList sinks;
public CompositeLeftTupleSinkAdapter() {
super( RuleBasePartitionId.MAIN_PARTITION );
}
public CompositeLeftTupleSinkAdapter(final RuleBasePartitionId partitionId) {
super( partitionId );
this.sinks = new LeftTupleSinkNodeList();
}
public void addTupleSink(final LeftTupleSink sink) {
this.sinks.add( (LeftTupleSinkNode) sink );
}
public void removeTupleSink(final LeftTupleSink sink) {
this.sinks.remove( (LeftTupleSinkNode) sink );
}
public void createChildLeftTuplesforQuery(final LeftTuple leftTuple,
final RightTuple rightTuple,
boolean leftTupleMemoryEnabled) {
for ( LeftTupleSinkNode sink = this.sinks.getFirst(); sink != null; sink = sink.getNextLeftTupleSinkNode() ) {
LeftTuple child = new LeftTuple( leftTuple,
rightTuple,
null,
null,
sink,
leftTupleMemoryEnabled );
child.setLeftParentNext( leftTuple.firstChild );
leftTuple.firstChild = child;
}
}
public void propagateAssertLeftTuple(final LeftTuple leftTuple,
final RightTuple rightTuple,
final LeftTuple currentLeftChild,
final LeftTuple currentRightChild,
final PropagationContext context,
final InternalWorkingMemory workingMemory,
final boolean leftTupleMemoryEnabled) {
for ( LeftTupleSinkNode sink = this.sinks.getFirst(); sink != null; sink = sink.getNextLeftTupleSinkNode() ) {
LeftTuple newLeftTuple = new LeftTuple( leftTuple,
rightTuple,
currentLeftChild,
currentRightChild,
sink,
leftTupleMemoryEnabled );
doPropagateAssertLeftTuple( context,
workingMemory,
sink,
newLeftTuple );
}
}
public void propagateAssertLeftTuple(final LeftTuple tuple,
final PropagationContext context,
final InternalWorkingMemory workingMemory,
final boolean leftTupleMemoryEnabled) {
for ( LeftTupleSinkNode sink = this.sinks.getFirst(); sink != null; sink = sink.getNextLeftTupleSinkNode() ) {
doPropagateAssertLeftTuple( context,
workingMemory,
sink,
new LeftTuple( tuple,
sink,
leftTupleMemoryEnabled ) );
}
}
public void createAndPropagateAssertLeftTuple(final InternalFactHandle factHandle,
final PropagationContext context,
final InternalWorkingMemory workingMemory,
final boolean leftTupleMemoryEnabled) {
for ( LeftTupleSinkNode sink = this.sinks.getFirst(); sink != null; sink = sink.getNextLeftTupleSinkNode() ) {
doPropagateAssertLeftTuple( context,
workingMemory,
sink,
new LeftTuple( factHandle,
sink,
leftTupleMemoryEnabled ) );
}
}
public void propagateRetractLeftTuple(final LeftTuple leftTuple,
final PropagationContext context,
final InternalWorkingMemory workingMemory) {
LeftTuple child = leftTuple.firstChild;
while ( child != null ) {
LeftTuple temp = child.getLeftParentNext();
doPropagateRetractLeftTuple( context,
workingMemory,
child,
child.getLeftTupleSink() );
child.unlinkFromRightParent();
child.unlinkFromLeftParent();
child = temp;
}
}
public void propagateRetractLeftTupleDestroyRightTuple(final LeftTuple leftTuple,
final PropagationContext context,
final InternalWorkingMemory workingMemory) {
LeftTuple child = leftTuple.firstChild;
while ( child != null ) {
LeftTuple temp = child.getLeftParentNext();
doPropagateRetractLeftTuple( context,
workingMemory,
child,
child.getLeftTupleSink() );
workingMemory.getFactHandleFactory().destroyFactHandle( child.getRightParent().getFactHandle() );
child.unlinkFromRightParent();
child.unlinkFromLeftParent();
child = temp;
}
}
public void propagateRetractRightTuple(final RightTuple rightTuple,
final PropagationContext context,
final InternalWorkingMemory workingMemory) {
LeftTuple child = rightTuple.firstChild;
while ( child != null ) {
LeftTuple temp = child.getRightParentNext();
doPropagateRetractLeftTuple( context,
workingMemory,
child,
child.getLeftTupleSink() );
child.unlinkFromLeftParent();
child.unlinkFromRightParent();
child = temp;
}
}
public BaseNode getMatchingNode(BaseNode candidate) {
for ( LeftTupleSinkNode sink = this.sinks.getFirst(); sink != null; sink = sink.getNextLeftTupleSinkNode() ) {
if ( candidate.equals( sink ) ) {
return (BaseNode) sink;
}
}
return null; //To change body of implemented methods use File | Settings | File Templates.
}
public LeftTupleSink[] getSinks() {
final LeftTupleSink[] sinkArray = new LeftTupleSink[this.sinks.size()];
int i = 0;
for ( LeftTupleSinkNode sink = this.sinks.getFirst(); sink != null; sink = sink.getNextLeftTupleSinkNode() ) {
sinkArray[i++] = sink;
}
return sinkArray;
}
public int size() {
return this.sinks.size();
}
public void readExternal(ObjectInput in) throws IOException,
ClassNotFoundException {
super.readExternal( in );
this.sinks = (LeftTupleSinkNodeList) in.readObject();
}
public void writeExternal(ObjectOutput out) throws IOException {
super.writeExternal( out );
out.writeObject( this.sinks );
}
public void doPropagateAssertLeftTuple(PropagationContext context,
InternalWorkingMemory workingMemory,
LeftTuple leftTuple,
LeftTupleSink sink) {
sink.assertLeftTuple( leftTuple, context, workingMemory );
}
/**
* This is a hook method that may be overriden by subclasses. Please keep it
* protected.
*
* @param context
* @param workingMemory
* @param sink
* @param leftTuple
*/
protected void doPropagateAssertLeftTuple(PropagationContext context,
InternalWorkingMemory workingMemory,
LeftTupleSinkNode sink,
LeftTuple leftTuple) {
sink.assertLeftTuple( leftTuple,
context,
workingMemory );
}
/**
* This is a hook method that may be overriden by subclasses. Please keep it
* protected.
*
* @param context
* @param workingMemory
* @param leftTuple
* @param sink
*/
protected void doPropagateRetractLeftTuple(PropagationContext context,
InternalWorkingMemory workingMemory,
LeftTuple leftTuple,
LeftTupleSink sink) {
sink.retractLeftTuple( leftTuple,
context,
workingMemory );
}
public void doPropagateModifyObject(InternalFactHandle factHandle,
ModifyPreviousTuples modifyPreviousTuples,
PropagationContext context,
InternalWorkingMemory workingMemory,
LeftTupleSink sink) {
sink.modifyLeftTuple( factHandle,
modifyPreviousTuples,
context,
workingMemory );
}
// related to true modify
//this.sink.propagateModifyObject( factHandle, modifyPreviousTuples, context, workingMemory );
public void propagateModifyObject(InternalFactHandle factHandle,
ModifyPreviousTuples modifyPreviousTuples,
PropagationContext context,
InternalWorkingMemory workingMemory) {
for ( LeftTupleSinkNode sink = this.sinks.getFirst(); sink != null; sink = sink.getNextLeftTupleSinkNode() ) {
doPropagateModifyObject( factHandle,
modifyPreviousTuples,
context,
workingMemory,
sink );
}
}
public LeftTuple propagateModifyChildLeftTuple(LeftTuple childLeftTuple,
RightTuple parentRightTuple,
PropagationContext context,
InternalWorkingMemory workingMemory,
boolean tupleMemoryEnabled) {
// iterate to find all child tuples for the shared node
while ( childLeftTuple != null && childLeftTuple.getRightParent() == parentRightTuple ) {
// this will iterate for each child node when the
// the current node is shared
// preserve the current LeftTuple, as we need to iterate to the next before re-adding
LeftTuple temp = childLeftTuple;
childLeftTuple.getLeftTupleSink().modifyLeftTuple( childLeftTuple,
context,
workingMemory );
childLeftTuple = childLeftTuple.getLeftParentNext();
temp.reAddRight();
}
return childLeftTuple;
}
public LeftTuple propagateModifyChildLeftTuple(LeftTuple childLeftTuple,
LeftTuple parentLeftTuple,
PropagationContext context,
InternalWorkingMemory workingMemory,
boolean tupleMemoryEnabled) {
// iterate to find all child tuples for the shared node
while ( childLeftTuple != null && childLeftTuple.getLeftParent() == parentLeftTuple ) {
// this will iterate for each child node when the
// the current node is shared
// preserve the current LeftTuple, as we need to iterate to the next before re-adding
LeftTuple temp = childLeftTuple;
childLeftTuple.getLeftTupleSink().modifyLeftTuple( childLeftTuple,
context,
workingMemory );
childLeftTuple = childLeftTuple.getRightParentNext();
temp.reAddLeft();
}
return childLeftTuple;
}
public void propagateModifyChildLeftTuple(LeftTuple leftTuple,
PropagationContext context,
InternalWorkingMemory workingMemory,
boolean tupleMemoryEnabled) {
for ( LeftTuple childLeftTuple = leftTuple.firstChild; childLeftTuple != null; childLeftTuple = (LeftTuple) childLeftTuple.getLeftParentNext() ) {
childLeftTuple.getLeftTupleSink().modifyLeftTuple( childLeftTuple,
context,
workingMemory );
}
}
public LeftTuple propagateRetractChildLeftTuple(LeftTuple childLeftTuple,
RightTuple parentRightTuple,
PropagationContext context,
InternalWorkingMemory workingMemory) {
// iterate to find all child tuples for the shared node
while ( childLeftTuple != null && childLeftTuple.getRightParent() == parentRightTuple ) {
// this will iterate for each child node when the
// the current node is shared
LeftTuple temp = childLeftTuple.getLeftParentNext();
doPropagateRetractLeftTuple( context,
workingMemory,
childLeftTuple,
childLeftTuple.getLeftTupleSink() );
childLeftTuple.unlinkFromRightParent();
childLeftTuple.unlinkFromLeftParent();
childLeftTuple = temp;
}
return childLeftTuple;
}
public LeftTuple propagateRetractChildLeftTuple(LeftTuple childLeftTuple,
LeftTuple parentLeftTuple,
PropagationContext context,
InternalWorkingMemory workingMemory) {
// iterate to find all child tuples for the shared node
while ( childLeftTuple != null && childLeftTuple.getLeftParent() == parentLeftTuple ) {
// this will iterate for each child node when the
// the current node is shared
LeftTuple temp = childLeftTuple.getRightParentNext();
doPropagateRetractLeftTuple( context,
workingMemory,
childLeftTuple,
childLeftTuple.getLeftTupleSink() );
childLeftTuple.unlinkFromRightParent();
childLeftTuple.unlinkFromLeftParent();
childLeftTuple = temp;
}
return childLeftTuple;
}
}
| JBRULES-2887: fixing NPE on accumulate retracts
| drools-core/src/main/java/org/drools/reteoo/CompositeLeftTupleSinkAdapter.java | JBRULES-2887: fixing NPE on accumulate retracts | <ide><path>rools-core/src/main/java/org/drools/reteoo/CompositeLeftTupleSinkAdapter.java
<ide> final PropagationContext context,
<ide> final InternalWorkingMemory workingMemory) {
<ide> LeftTuple child = leftTuple.firstChild;
<add> InternalFactHandle rightParent = child.getRightParent().getFactHandle();
<ide> while ( child != null ) {
<ide> LeftTuple temp = child.getLeftParentNext();
<ide> doPropagateRetractLeftTuple( context,
<ide> workingMemory,
<ide> child,
<ide> child.getLeftTupleSink() );
<del> workingMemory.getFactHandleFactory().destroyFactHandle( child.getRightParent().getFactHandle() );
<ide> child.unlinkFromRightParent();
<ide> child.unlinkFromLeftParent();
<ide> child = temp;
<ide> }
<add> workingMemory.getFactHandleFactory().destroyFactHandle( rightParent );
<ide> }
<ide>
<ide> public void propagateRetractRightTuple(final RightTuple rightTuple, |
|
Java | apache-2.0 | f8c6586d37dea8a0b91796aea722319c9f345dca | 0 | Vizaxo/Terasology,Nanoware/Terasology,Malanius/Terasology,kartikey0303/Terasology,Nanoware/Terasology,kaen/Terasology,Vizaxo/Terasology,MovingBlocks/Terasology,MovingBlocks/Terasology,Malanius/Terasology,Nanoware/Terasology,kaen/Terasology,kartikey0303/Terasology,MovingBlocks/Terasology | /*
* Copyright 2017 MovingBlocks
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.terasology.engine.subsystem.openvr;
import jopenvr.VRControllerState_t;
import org.joml.Matrix4f;
import org.terasology.input.ButtonState;
import org.terasology.input.ControllerDevice;
import org.terasology.input.InputType;
import org.terasology.input.device.ControllerAction;
import org.terasology.rendering.openvrprovider.ControllerListener;
import org.terasology.rendering.openvrprovider.OpenVRUtil;
import org.terasology.input.ControllerId;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
/**
* This class acts as an interface between OpenVR controllers and Terasology controllers. By implementing
* ControllerListener.buttonStateChanged(), OpenVR controller events make it into this class and are stored. Then,
* by implementing getInputQueue(), an overridden method from ControllerDevice, the Terasology controller system
* frequently retrieves and handles these events.
*/
class OpenVRControllers implements ControllerDevice, ControllerListener {
private Queue<ControllerAction> queuedActions = new ArrayDeque<>();
private VRControllerState_t cachedStateBefore;
private VRControllerState_t cachedStateAfter;
/**
* Get the controller names provided by this ControllerDevice.
* @return the list of controllers names.
*/
@Override
public List<String> getControllers() {
List<String> ids = new ArrayList<>();
ids.add("OpenVR");
return ids;
}
/**
* Get all queued actions registered since this method was last called.
* @return a queue of actions.
*/
@Override
public Queue<ControllerAction> getInputQueue() {
Queue<ControllerAction> result = new ArrayDeque<>(queuedActions);
queuedActions.clear();
return result;
}
private boolean switchedUp(long buttonIndex) {
return OpenVRUtil.switchedUp(buttonIndex, cachedStateBefore.ulButtonPressed, cachedStateAfter.ulButtonPressed);
}
private boolean switchedDown(long buttonIndex) {
return OpenVRUtil.switchedDown(buttonIndex, cachedStateBefore.ulButtonPressed, cachedStateAfter.ulButtonPressed);
}
private void addAction(int controllerButton, ButtonState buttonState, float axisValue) {
queuedActions.add(new ControllerAction(InputType.CONTROLLER_BUTTON.getInput(controllerButton),
"OpenVR", buttonState, axisValue));
}
private void addAction(int controllerButton, ButtonState buttonState) {
addAction(controllerButton, buttonState, 1.0f);
}
private void handleController0() {
if (switchedUp(ControllerListener.BUTTON_TRIGGER)) {
addAction(ControllerId.ZERO, ButtonState.UP);
} else if (switchedDown(ControllerListener.BUTTON_TRIGGER)) {
addAction(ControllerId.ZERO, ButtonState.DOWN);
} else if (switchedUp(ControllerListener.BUTTON_GRIP)) {
addAction(ControllerId.ONE, ButtonState.UP);
} else if (switchedDown(ControllerListener.BUTTON_GRIP)) {
addAction(ControllerId.ONE, ButtonState.DOWN);
} else if (switchedUp(ControllerListener.BUTTON_APP_MENU)) {
addAction(ControllerId.TWO, ButtonState.UP);
} else if (switchedDown(ControllerListener.BUTTON_APP_MENU)) {
addAction(ControllerId.TWO, ButtonState.DOWN);
} else if (switchedDown(ControllerListener.BUTTON_TOUCHPAD)) {
addAction(ControllerId.X_AXIS, ButtonState.DOWN, -cachedStateAfter.rAxis[0].x);
addAction(ControllerId.Y_AXIS, ButtonState.DOWN, cachedStateAfter.rAxis[0].y);
} else if (switchedUp(ControllerListener.BUTTON_TOUCHPAD)) {
addAction(ControllerId.X_AXIS, ButtonState.UP, 0.0f);
addAction(ControllerId.Y_AXIS, ButtonState.UP, 0.0f);
}
}
private void handleController1() {
if (switchedUp(ControllerListener.BUTTON_TRIGGER)) {
addAction(ControllerId.THREE, ButtonState.UP);
} else if (switchedDown(ControllerListener.BUTTON_TRIGGER)) {
addAction(ControllerId.THREE, ButtonState.DOWN);
} else if (switchedUp(ControllerListener.BUTTON_GRIP)) {
addAction(ControllerId.FOUR, ButtonState.UP);
} else if (switchedDown(ControllerListener.BUTTON_GRIP)) {
addAction(ControllerId.FOUR, ButtonState.DOWN);
} else if (switchedUp(ControllerListener.BUTTON_APP_MENU)) {
addAction(ControllerId.FIVE, ButtonState.UP);
} else if (switchedDown(ControllerListener.BUTTON_APP_MENU)) {
addAction(ControllerId.FIVE, ButtonState.DOWN);
} else if (switchedDown(ControllerListener.BUTTON_TOUCHPAD)) {
if (cachedStateAfter.rAxis[0].x < 0 && cachedStateAfter.rAxis[0].y < 0) {
addAction(ControllerId.SIX, ButtonState.DOWN);
} else if (cachedStateAfter.rAxis[0].x > 0 && cachedStateAfter.rAxis[0].y < 0) {
addAction(ControllerId.SEVEN, ButtonState.DOWN);
} else if (cachedStateAfter.rAxis[0].x < 0 && cachedStateAfter.rAxis[0].y < 0) {
addAction(ControllerId.EIGHT, ButtonState.DOWN);
} else if (cachedStateAfter.rAxis[0].x > 0 && cachedStateAfter.rAxis[0].y > 0) {
addAction(ControllerId.NINE, ButtonState.DOWN);
}
} else if (switchedUp(ControllerListener.BUTTON_TOUCHPAD)) {
if (cachedStateAfter.rAxis[0].x < 0 && cachedStateAfter.rAxis[0].y < 0) {
addAction(ControllerId.SIX, ButtonState.UP);
} else if (cachedStateAfter.rAxis[0].x > 0 && cachedStateAfter.rAxis[0].y < 0) {
addAction(ControllerId.SEVEN, ButtonState.UP);
} else if (cachedStateAfter.rAxis[0].x < 0 && cachedStateAfter.rAxis[0].y < 0) {
addAction(ControllerId.EIGHT, ButtonState.UP);
} else if (cachedStateAfter.rAxis[0].x > 0 && cachedStateAfter.rAxis[0].y > 0) {
addAction(ControllerId.NINE, ButtonState.UP);
}
}
}
/**
* Called whenever the OpenVR controller button state changes for a given controller (left or right).
* @param stateBefore - the state before the last change.
* @param stateAfter - the state after the last change.
* @param handIndex - the hand index, an integer - 0 for left, 1 for right.
*/
@Override
public void buttonStateChanged(VRControllerState_t stateBefore, VRControllerState_t stateAfter, int handIndex) {
cachedStateBefore = stateBefore;
cachedStateAfter = stateAfter;
queuedActions.add(new ControllerAction(InputType.CONTROLLER_BUTTON.getInput(ControllerId.X_AXIS),
"OpenVR", ButtonState.DOWN, 1.0f));
if (handIndex == 0) {
handleController0();
} else {
handleController1();
}
}
/**
* Called whenever the OpenVR controller pose changes for a given controller (left or right). This particular
* listener just ignores pose updates.
* @param pose - the pose of the controller (a 4x4 matrix).
* @param handIndex - the hand index, an integer - 0 for left, 1 for right.
*/
@Override
public void poseChanged(Matrix4f pose, int handIndex) {
// currently no actions are sensitive to controller movement
}
}
| engine/src/main/java/org/terasology/engine/subsystem/openvr/OpenVRControllers.java | /*
* Copyright 2017 MovingBlocks
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.terasology.engine.subsystem.openvr;
import jopenvr.VRControllerState_t;
import org.joml.Matrix4f;
import org.terasology.input.ButtonState;
import org.terasology.input.ControllerDevice;
import org.terasology.input.InputType;
import org.terasology.input.device.ControllerAction;
import org.terasology.rendering.openvrprovider.ControllerListener;
import org.terasology.rendering.openvrprovider.OpenVRUtil;
import org.terasology.input.ControllerId;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
/**
* This class acts as an interface between OpenVR controllers and Terasology controllers. By implementing
* ControllerListener.buttonStateChanged(), OpenVR controller events make it into this class and are stored. Then,
* by implementing getInputQueue(), an overridden method from ControllerDevice, the Terasology controller system
* frequently retrieves and handles these events.
*/
class OpenVRControllers implements ControllerDevice, ControllerListener {
private Queue<ControllerAction> queuedActions = new ArrayDeque<>();
private VRControllerState_t cachedStateBefore;
private VRControllerState_t cachedStateAfter;
/**
* Get the controller names provided by this ControllerDevice.
* @return the list of controllers names.
*/
@Override
public List<String> getControllers() {
List<String> ids = new ArrayList<>();
ids.add("OpenVR");
return ids;
}
/**
* Get all queued actions registered since this method was last called.
* @return a queue of actions.
*/
@Override
public Queue<ControllerAction> getInputQueue() {
Queue<ControllerAction> result = new ArrayDeque<>(queuedActions);
queuedActions.clear();
return result;
}
private boolean switchedUp(long buttonIndex) {
return OpenVRUtil.switchedUp(buttonIndex, cachedStateBefore.ulButtonPressed, cachedStateAfter.ulButtonPressed);
}
private boolean switchedDown(long buttonIndex) {
return OpenVRUtil.switchedDown(buttonIndex, cachedStateBefore.ulButtonPressed, cachedStateAfter.ulButtonPressed);
}
private void addAction(int controllerButton, ButtonState buttonState, float axisValue) {
queuedActions.add(new ControllerAction(InputType.CONTROLLER_BUTTON.getInput(controllerButton),
"OpenVR", buttonState, axisValue));
}
private void addAction(int controllerButton, ButtonState buttonState) {
addAction(controllerButton, buttonState, 1.0f);
}
private void handleController0() {
if (switchedUp(ControllerListener.BUTTON_TRIGGER)) {
addAction(ControllerId.ZERO, ButtonState.UP);
} else if (switchedDown(ControllerListener.BUTTON_TRIGGER)) {
addAction(ControllerId.ZERO, ButtonState.DOWN);
} else if (switchedUp(ControllerListener.BUTTON_GRIP)) {
addAction(ControllerId.ONE, ButtonState.UP);
} else if (switchedDown(ControllerListener.BUTTON_GRIP)) {
addAction(ControllerId.ONE, ButtonState.DOWN);
} else if (switchedUp(ControllerListener.BUTTON_APP_MENU)) {
addAction(ControllerId.TWO, ButtonState.UP);
} else if (switchedDown(ControllerListener.BUTTON_APP_MENU)) {
addAction(ControllerId.TWO, ButtonState.DOWN);
} else if (switchedDown(ControllerListener.BUTTON_TOUCHPAD)) {
addAction(ControllerId.X_AXIS, ButtonState.DOWN, -cachedStateAfter.rAxis[0].x);
addAction(ControllerId.Y_AXIS, ButtonState.DOWN, cachedStateAfter.rAxis[0].y);
} else if (switchedUp(ControllerListener.BUTTON_TOUCHPAD)) {
addAction(ControllerId.X_AXIS, ButtonState.UP, 0);
addAction(ControllerId.Y_AXIS, ButtonState.UP, 0);
}
}
private void handleController1() {
if (switchedUp(ControllerListener.BUTTON_TRIGGER)) {
addAction(ControllerId.THREE, ButtonState.UP);
} else if (switchedDown(ControllerListener.BUTTON_TRIGGER)) {
addAction(ControllerId.THREE, ButtonState.DOWN);
} else if (switchedUp(ControllerListener.BUTTON_GRIP)) {
addAction(ControllerId.FOUR, ButtonState.UP);
} else if (switchedDown(ControllerListener.BUTTON_GRIP)) {
addAction(ControllerId.FOUR, ButtonState.DOWN);
} else if (switchedUp(ControllerListener.BUTTON_APP_MENU)) {
addAction(ControllerId.FIVE, ButtonState.UP);
} else if (switchedDown(ControllerListener.BUTTON_APP_MENU)) {
addAction(ControllerId.FIVE, ButtonState.DOWN);
} else if (switchedDown(ControllerListener.BUTTON_TOUCHPAD)) {
if (cachedStateAfter.rAxis[0].x < 0 && cachedStateAfter.rAxis[0].y < 0) {
addAction(ControllerId.SIX, ButtonState.DOWN);
} else if (cachedStateAfter.rAxis[0].x > 0 && cachedStateAfter.rAxis[0].y < 0) {
addAction(ControllerId.SEVEN, ButtonState.DOWN);
} else if (cachedStateAfter.rAxis[0].x < 0 && cachedStateAfter.rAxis[0].y < 0) {
addAction(ControllerId.EIGHT, ButtonState.DOWN);
} else if (cachedStateAfter.rAxis[0].x > 0 && cachedStateAfter.rAxis[0].y > 0) {
addAction(ControllerId.NINE, ButtonState.DOWN);
}
} else if (switchedUp(ControllerListener.BUTTON_TOUCHPAD)) {
if (cachedStateAfter.rAxis[0].x < 0 && cachedStateAfter.rAxis[0].y < 0) {
addAction(ControllerId.SIX, ButtonState.UP);
} else if (cachedStateAfter.rAxis[0].x > 0 && cachedStateAfter.rAxis[0].y < 0) {
addAction(ControllerId.SEVEN, ButtonState.UP);
} else if (cachedStateAfter.rAxis[0].x < 0 && cachedStateAfter.rAxis[0].y < 0) {
addAction(ControllerId.EIGHT, ButtonState.UP);
} else if (cachedStateAfter.rAxis[0].x > 0 && cachedStateAfter.rAxis[0].y > 0) {
addAction(ControllerId.NINE, ButtonState.UP);
}
}
}
/**
* Called whenever the OpenVR controller button state changes for a given controller (left or right).
* @param stateBefore - the state before the last change.
* @param stateAfter - the state after the last change.
* @param handIndex - the hand index, an integer - 0 for left, 1 for right.
*/
@Override
public void buttonStateChanged(VRControllerState_t stateBefore, VRControllerState_t stateAfter, int handIndex) {
cachedStateBefore = stateBefore;
cachedStateAfter = stateAfter;
if (handIndex == 0) {
handleController0();
} else {
handleController1();
}
}
/**
* Called whenever the OpenVR controller pose changes for a given controller (left or right). This particular
* listener just ignores pose updates.
* @param pose - the pose of the controller (a 4x4 matrix).
* @param handIndex - the hand index, an integer - 0 for left, 1 for right.
*/
@Override
public void poseChanged(Matrix4f pose, int handIndex) {
// currently no actions are sensitive to controller movement
}
}
| More clear casting.
| engine/src/main/java/org/terasology/engine/subsystem/openvr/OpenVRControllers.java | More clear casting. | <ide><path>ngine/src/main/java/org/terasology/engine/subsystem/openvr/OpenVRControllers.java
<ide> addAction(ControllerId.X_AXIS, ButtonState.DOWN, -cachedStateAfter.rAxis[0].x);
<ide> addAction(ControllerId.Y_AXIS, ButtonState.DOWN, cachedStateAfter.rAxis[0].y);
<ide> } else if (switchedUp(ControllerListener.BUTTON_TOUCHPAD)) {
<del> addAction(ControllerId.X_AXIS, ButtonState.UP, 0);
<del> addAction(ControllerId.Y_AXIS, ButtonState.UP, 0);
<add> addAction(ControllerId.X_AXIS, ButtonState.UP, 0.0f);
<add> addAction(ControllerId.Y_AXIS, ButtonState.UP, 0.0f);
<ide> }
<ide> }
<ide>
<ide> public void buttonStateChanged(VRControllerState_t stateBefore, VRControllerState_t stateAfter, int handIndex) {
<ide> cachedStateBefore = stateBefore;
<ide> cachedStateAfter = stateAfter;
<add> queuedActions.add(new ControllerAction(InputType.CONTROLLER_BUTTON.getInput(ControllerId.X_AXIS),
<add> "OpenVR", ButtonState.DOWN, 1.0f));
<ide> if (handIndex == 0) {
<ide> handleController0();
<ide> } else { |
|
Java | mit | b16d30d102473df1c3ae254b4bf4f18f888e953d | 0 | agersant/polaris-android,agersant/polaris-android,agersant/polaris-android | package agersant.polaris.features.queue;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import java.util.Random;
import agersant.polaris.PlaybackQueue;
import agersant.polaris.Player;
import agersant.polaris.PolarisService;
import agersant.polaris.R;
import agersant.polaris.api.local.OfflineCache;
import agersant.polaris.api.remote.DownloadQueue;
import agersant.polaris.features.PolarisActivity;
public class QueueActivity extends PolarisActivity {
private QueueAdapter adapter;
private BroadcastReceiver receiver;
private View tutorial;
private PolarisService service;
public QueueActivity() {
super(R.string.queue, R.id.nav_queue);
}
private ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
service = null;
}
@Override
public void onServiceConnected(ComponentName name, IBinder iBinder) {
service = ((PolarisService.PolarisBinder) iBinder).getService();
populate();
updateOrderingIcon();
updateTutorial();
}
};
private void subscribeToEvents() {
IntentFilter filter = new IntentFilter();
filter.addAction(PlaybackQueue.REMOVED_ITEM);
filter.addAction(PlaybackQueue.REMOVED_ITEMS);
filter.addAction(PlaybackQueue.QUEUED_ITEMS);
filter.addAction(Player.PLAYING_TRACK);
filter.addAction(OfflineCache.AUDIO_CACHED);
filter.addAction(DownloadQueue.WORKLOAD_CHANGED);
filter.addAction(OfflineCache.AUDIO_REMOVED_FROM_CACHE);
receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
switch (intent.getAction()) {
case PlaybackQueue.REMOVED_ITEM:
case PlaybackQueue.REMOVED_ITEMS:
updateTutorial();
break;
case PlaybackQueue.QUEUED_ITEMS:
updateTutorial();
// Fallthrough
case Player.PLAYING_TRACK:
case OfflineCache.AUDIO_CACHED:
case OfflineCache.AUDIO_REMOVED_FROM_CACHE:
case DownloadQueue.WORKLOAD_CHANGED:
if (adapter != null) {
adapter.notifyDataSetChanged();
}
break;
}
}
};
registerReceiver(receiver, filter);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_queue);
super.onCreate(savedInstanceState);
tutorial = findViewById(R.id.queue_tutorial);
updateTutorial();
}
void updateTutorial() {
if (adapter == null) {
return;
}
boolean empty = adapter.getItemCount() == 0;
if (empty) {
tutorial.setVisibility(View.VISIBLE);
} else {
tutorial.setVisibility(View.GONE);
}
}
@Override
public void onStart() {
super.onStart();
Intent intent = new Intent(this, PolarisService.class);
startService(intent);
bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
subscribeToEvents();
}
@Override
public void onStop() {
super.onStop();
if (service != null) {
unbindService(serviceConnection);
}
unregisterReceiver(receiver);
receiver = null;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_queue, menu);
updateOrderingIcon();
return true;
}
@Override
public void onResume() {
super.onResume();
if (adapter != null) {
adapter.notifyDataSetChanged();
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_clear:
clear();
return true;
case R.id.action_shuffle:
shuffle();
return true;
case R.id.action_ordering_sequence:
case R.id.action_ordering_repeat_one:
case R.id.action_ordering_repeat_all:
setOrdering(item);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void populate() {
adapter = new QueueAdapter(service);
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.queue_recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
ItemTouchHelper.Callback callback = new QueueTouchCallback(adapter);
ItemTouchHelper itemTouchHelper = new ItemTouchHelper(callback);
itemTouchHelper.attachToRecyclerView(recyclerView);
recyclerView.setAdapter(adapter);
}
private void clear() {
if (service == null) {
return;
}
int oldCount = adapter.getItemCount();
service.clear();
adapter.notifyItemRangeRemoved(0, oldCount);
}
private void shuffle() {
if (service == null) {
return;
}
Random rng = new Random();
int count = adapter.getItemCount();
for (int i = 0; i <= count - 2; i++) {
int j = i + rng.nextInt(count - i);
service.move(i, j);
adapter.notifyItemMoved(i, j);
}
}
private void setOrdering(MenuItem item) {
if (service == null) {
return;
}
switch (item.getItemId()) {
case R.id.action_ordering_sequence:
service.setOrdering(PlaybackQueue.Ordering.SEQUENCE);
break;
case R.id.action_ordering_repeat_one:
service.setOrdering(PlaybackQueue.Ordering.REPEAT_ONE);
break;
case R.id.action_ordering_repeat_all:
service.setOrdering(PlaybackQueue.Ordering.REPEAT_ALL);
break;
}
updateOrderingIcon();
}
private int getIconForOrdering(PlaybackQueue.Ordering ordering) {
switch (ordering) {
case REPEAT_ONE:
return R.drawable.ic_repeat_one_white_24dp;
case REPEAT_ALL:
return R.drawable.ic_repeat_white_24dp;
case SEQUENCE:
default:
return R.drawable.ic_reorder_white_24dp;
}
}
private void updateOrderingIcon() {
if (service == null) {
return;
}
int icon = getIconForOrdering(service.getOrdering());
MenuItem orderingItem = toolbar.getMenu().findItem(R.id.action_ordering);
if (orderingItem != null) {
orderingItem.setIcon(icon);
}
}
}
| app/src/main/java/agersant/polaris/features/queue/QueueActivity.java | package agersant.polaris.features.queue;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import java.util.Random;
import agersant.polaris.PlaybackQueue;
import agersant.polaris.Player;
import agersant.polaris.PolarisService;
import agersant.polaris.R;
import agersant.polaris.api.local.OfflineCache;
import agersant.polaris.api.remote.DownloadQueue;
import agersant.polaris.features.PolarisActivity;
public class QueueActivity extends PolarisActivity {
private QueueAdapter adapter;
private BroadcastReceiver receiver;
private View tutorial;
private PolarisService service;
public QueueActivity() {
super(R.string.queue, R.id.nav_queue);
}
private ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
service = null;
}
@Override
public void onServiceConnected(ComponentName name, IBinder iBinder) {
service = ((PolarisService.PolarisBinder) iBinder).getService();
populate();
updateOrderingIcon();
updateTutorial();
}
};
private void subscribeToEvents() {
IntentFilter filter = new IntentFilter();
filter.addAction(PlaybackQueue.REMOVED_ITEM);
filter.addAction(PlaybackQueue.REMOVED_ITEMS);
filter.addAction(PlaybackQueue.QUEUED_ITEMS);
filter.addAction(Player.PLAYING_TRACK);
filter.addAction(OfflineCache.AUDIO_CACHED);
filter.addAction(DownloadQueue.WORKLOAD_CHANGED);
filter.addAction(OfflineCache.AUDIO_REMOVED_FROM_CACHE);
receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
switch (intent.getAction()) {
case PlaybackQueue.REMOVED_ITEM:
case PlaybackQueue.REMOVED_ITEMS:
updateTutorial();
break;
case PlaybackQueue.QUEUED_ITEMS:
updateTutorial();
// Fallthrough
case Player.PLAYING_TRACK:
case OfflineCache.AUDIO_CACHED:
case OfflineCache.AUDIO_REMOVED_FROM_CACHE:
if (adapter != null) {
adapter.notifyDataSetChanged();
}
break;
}
}
};
registerReceiver(receiver, filter);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_queue);
super.onCreate(savedInstanceState);
tutorial = findViewById(R.id.queue_tutorial);
updateTutorial();
}
void updateTutorial() {
if (adapter == null) {
return;
}
boolean empty = adapter.getItemCount() == 0;
if (empty) {
tutorial.setVisibility(View.VISIBLE);
} else {
tutorial.setVisibility(View.GONE);
}
}
@Override
public void onStart() {
super.onStart();
Intent intent = new Intent(this, PolarisService.class);
startService(intent);
bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
subscribeToEvents();
}
@Override
public void onStop() {
super.onStop();
if (service != null) {
unbindService(serviceConnection);
}
unregisterReceiver(receiver);
receiver = null;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_queue, menu);
updateOrderingIcon();
return true;
}
@Override
public void onResume() {
super.onResume();
if (adapter != null) {
adapter.notifyDataSetChanged();
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_clear:
clear();
return true;
case R.id.action_shuffle:
shuffle();
return true;
case R.id.action_ordering_sequence:
case R.id.action_ordering_repeat_one:
case R.id.action_ordering_repeat_all:
setOrdering(item);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void populate() {
adapter = new QueueAdapter(service);
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.queue_recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
ItemTouchHelper.Callback callback = new QueueTouchCallback(adapter);
ItemTouchHelper itemTouchHelper = new ItemTouchHelper(callback);
itemTouchHelper.attachToRecyclerView(recyclerView);
recyclerView.setAdapter(adapter);
}
private void clear() {
if (service == null) {
return;
}
int oldCount = adapter.getItemCount();
service.clear();
adapter.notifyItemRangeRemoved(0, oldCount);
}
private void shuffle() {
if (service == null) {
return;
}
Random rng = new Random();
int count = adapter.getItemCount();
for (int i = 0; i <= count - 2; i++) {
int j = i + rng.nextInt(count - i);
service.move(i, j);
adapter.notifyItemMoved(i, j);
}
}
private void setOrdering(MenuItem item) {
if (service == null) {
return;
}
switch (item.getItemId()) {
case R.id.action_ordering_sequence:
service.setOrdering(PlaybackQueue.Ordering.SEQUENCE);
break;
case R.id.action_ordering_repeat_one:
service.setOrdering(PlaybackQueue.Ordering.REPEAT_ONE);
break;
case R.id.action_ordering_repeat_all:
service.setOrdering(PlaybackQueue.Ordering.REPEAT_ALL);
break;
}
updateOrderingIcon();
}
private int getIconForOrdering(PlaybackQueue.Ordering ordering) {
switch (ordering) {
case REPEAT_ONE:
return R.drawable.ic_repeat_one_white_24dp;
case REPEAT_ALL:
return R.drawable.ic_repeat_white_24dp;
case SEQUENCE:
default:
return R.drawable.ic_reorder_white_24dp;
}
}
private void updateOrderingIcon() {
if (service == null) {
return;
}
int icon = getIconForOrdering(service.getOrdering());
MenuItem orderingItem = toolbar.getMenu().findItem(R.id.action_ordering);
if (orderingItem != null) {
orderingItem.setIcon(icon);
}
}
}
| Fixed a bug where playlist didn't display which items are downloading
| app/src/main/java/agersant/polaris/features/queue/QueueActivity.java | Fixed a bug where playlist didn't display which items are downloading | <ide><path>pp/src/main/java/agersant/polaris/features/queue/QueueActivity.java
<ide> case Player.PLAYING_TRACK:
<ide> case OfflineCache.AUDIO_CACHED:
<ide> case OfflineCache.AUDIO_REMOVED_FROM_CACHE:
<add> case DownloadQueue.WORKLOAD_CHANGED:
<ide> if (adapter != null) {
<ide> adapter.notifyDataSetChanged();
<ide> } |
|
Java | apache-2.0 | f014b15ff6382a8e23eadb7d55acbbb726f6366f | 0 | henrichg/PhoneProfilesPlus | package sk.henrichg.phoneprofilesplus;
import android.app.Fragment;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import java.lang.ref.WeakReference;
import java.util.Collections;
import java.util.Comparator;
public class ActivateProfileListFragment extends Fragment {
DataWrapper activityDataWrapper;
private ActivateProfileListAdapter profileListAdapter = null;
private ListView listView = null;
private GridView gridView = null;
private TextView activeProfileName;
private ImageView activeProfileIcon;
TextView textViewNoData;
private LinearLayout progressBar;
private WeakReference<LoadProfileListAsyncTask> asyncTaskContext;
private static final String START_TARGET_HELPS_ARGUMENT = "start_target_helps";
//public boolean targetHelpsSequenceStarted;
public static final String PREF_START_TARGET_HELPS = "activate_profile_list_fragment_start_target_helps";
public static final int PORDER_FOR_IGNORED_PROFILE = 1000000;
public ActivateProfileListFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// this is really important in order to save the state across screen
// configuration changes for example
setRetainInstance(true);
activityDataWrapper = new DataWrapper(getActivity().getApplicationContext(), false, 0);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView;
if (!ApplicationPreferences.applicationActivatorGridLayout(activityDataWrapper.context))
{
if (ApplicationPreferences.applicationActivatorPrefIndicator(activityDataWrapper.context) && ApplicationPreferences.applicationActivatorHeader(activityDataWrapper.context))
rootView = inflater.inflate(R.layout.activate_profile_list, container, false);
else
if (ApplicationPreferences.applicationActivatorHeader(activityDataWrapper.context))
rootView = inflater.inflate(R.layout.activate_profile_list_no_indicator, container, false);
else
rootView = inflater.inflate(R.layout.activate_profile_list_no_header, container, false);
}
else
{
if (ApplicationPreferences.applicationActivatorPrefIndicator(activityDataWrapper.context) && ApplicationPreferences.applicationActivatorHeader(activityDataWrapper.context))
rootView = inflater.inflate(R.layout.activate_profile_grid, container, false);
else
if (ApplicationPreferences.applicationActivatorHeader(activityDataWrapper.context))
rootView = inflater.inflate(R.layout.activate_profile_grid_no_indicator, container, false);
else
rootView = inflater.inflate(R.layout.activate_profile_grid_no_header, container, false);
}
return rootView;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
doOnViewCreated(view/*, savedInstanceState*/);
boolean startTargetHelps = getArguments() != null && getArguments().getBoolean(START_TARGET_HELPS_ARGUMENT, false);
if (startTargetHelps)
showTargetHelps();
}
private void doOnViewCreated(View view/*, Bundle savedInstanceState*/)
{
activeProfileName = view.findViewById(R.id.act_prof_activated_profile_name);
activeProfileIcon = view.findViewById(R.id.act_prof_activated_profile_icon);
if (!ApplicationPreferences.applicationActivatorGridLayout(activityDataWrapper.context))
listView = view.findViewById(R.id.act_prof_profiles_list);
else
gridView = view.findViewById(R.id.act_prof_profiles_grid);
textViewNoData = view.findViewById(R.id.act_prof_list_empty);
progressBar = view.findViewById(R.id.act_prof_list_linla_progress);
AbsListView absListView;
if (!ApplicationPreferences.applicationActivatorGridLayout(activityDataWrapper.context))
absListView = listView;
else
absListView = gridView;
//absListView.setLongClickable(false);
absListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (!ApplicationPreferences.applicationLongClickActivation(activityDataWrapper.context))
//activateProfileWithAlert(position);
activateProfile((Profile)profileListAdapter.getItem(position));
}
});
absListView.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
if (ApplicationPreferences.applicationLongClickActivation(activityDataWrapper.context))
//activateProfileWithAlert(position);
activateProfile((Profile)profileListAdapter.getItem(position));
return false;
}
});
//absListView.setRemoveListener(onRemove);
if (!activityDataWrapper.profileListFilled)
{
LoadProfileListAsyncTask asyncTask = new LoadProfileListAsyncTask(this);
this.asyncTaskContext = new WeakReference<>(asyncTask );
asyncTask.execute();
}
else
{
absListView.setAdapter(profileListAdapter);
doOnStart();
}
}
private static class LoadProfileListAsyncTask extends AsyncTask<Void, Void, Void> {
private final WeakReference<ActivateProfileListFragment> fragmentWeakRef;
private final DataWrapper dataWrapper;
private class ProfileComparator implements Comparator<Profile> {
public int compare(Profile lhs, Profile rhs) {
int res = 0;
if ((lhs != null) && (rhs != null))
res = lhs._porder - rhs._porder;
return res;
}
}
private LoadProfileListAsyncTask (ActivateProfileListFragment fragment) {
this.fragmentWeakRef = new WeakReference<>(fragment);
this.dataWrapper = new DataWrapper(fragment.getActivity().getApplicationContext(), false, 0);
}
@Override
protected void onPreExecute()
{
super.onPreExecute();
ActivateProfileListFragment fragment = this.fragmentWeakRef.get();
if ((fragment != null) && (fragment.isAdded())) {
fragment.textViewNoData.setVisibility(View.GONE);
fragment.progressBar.setVisibility(View.VISIBLE);
}
}
@Override
protected Void doInBackground(Void... params) {
this.dataWrapper.fillProfileList(true, ApplicationPreferences.applicationActivatorPrefIndicator(dataWrapper.context));
if (!ApplicationPreferences.applicationActivatorHeader(this.dataWrapper.context))
{
Profile profile = this.dataWrapper.getActivatedProfile(false, false);
if ((profile != null) && (!profile._showInActivator))
{
profile._showInActivator = true;
profile._porder = -1;
}
}
if (ApplicationPreferences.applicationActivatorGridLayout(this.dataWrapper.context)) {
int count = 0;
for (Profile profile : this.dataWrapper.profileList)
{
if (profile._showInActivator)
++count;
}
int modulo = count % 3;
if (modulo > 0) {
for (int i = 0; i < 3 - modulo; i++) {
Profile profile = DataWrapper.getNonInitializedProfile(
dataWrapper.context.getResources().getString(R.string.profile_name_default),
Profile.PROFILE_ICON_DEFAULT, PORDER_FOR_IGNORED_PROFILE);
profile._showInActivator = true;
this.dataWrapper.profileList.add(profile);
}
}
}
Collections.sort(this.dataWrapper.profileList, new ProfileComparator());
return null;
}
@Override
protected void onPostExecute(Void response) {
super.onPostExecute(response);
final ActivateProfileListFragment fragment = this.fragmentWeakRef.get();
if ((fragment != null) && (fragment.isAdded())) {
fragment.progressBar.setVisibility(View.GONE);
// get local profileList
this.dataWrapper.fillProfileList(true, ApplicationPreferences.applicationActivatorPrefIndicator(dataWrapper.context));
// set copy local profile list into activity profilesDataWrapper
fragment.activityDataWrapper.copyProfileList(this.dataWrapper);
if (fragment.activityDataWrapper.profileList.size() == 0)
{
// no profile in list, start Editor
Intent intent = new Intent(fragment.getActivity().getBaseContext(), EditorProfilesActivity.class);
intent.putExtra(PPApplication.EXTRA_STARTUP_SOURCE, PPApplication.STARTUP_SOURCE_ACTIVATOR_START);
fragment.getActivity().startActivity(intent);
fragment.getActivity().finish();
return;
}
fragment.profileListAdapter = new ActivateProfileListAdapter(fragment, /*fragment.profileList, */fragment.activityDataWrapper);
AbsListView absListView;
if (!ApplicationPreferences.applicationActivatorGridLayout(dataWrapper.context))
absListView = fragment.listView;
else
absListView = fragment.gridView;
absListView.setAdapter(fragment.profileListAdapter);
fragment.doOnStart();
final Handler handler = new Handler(fragment.getActivity().getMainLooper());
handler.postDelayed(new Runnable() {
@Override
public void run() {
if (fragment.getActivity() != null)
((ActivateProfileActivity)fragment.getActivity()).startTargetHelpsActivity();
}
}, 1000);
}
}
}
private boolean isAsyncTaskPendingOrRunning() {
try {
return this.asyncTaskContext != null &&
this.asyncTaskContext.get() != null &&
!this.asyncTaskContext.get().getStatus().equals(AsyncTask.Status.FINISHED);
} catch (Exception e) {
return false;
}
}
private void doOnStart()
{
//long nanoTimeStart = PPApplication.startMeasuringRunTime();
Profile profile = activityDataWrapper.getActivatedProfile(true, ApplicationPreferences.applicationActivatorPrefIndicator(activityDataWrapper.context));
updateHeader(profile);
setProfileSelection(profile, false);
//PPApplication.getMeasuredRunTime(nanoTimeStart, "ActivateProfileActivity.onStart");
}
@Override
public void onDestroy()
{
if (isAsyncTaskPendingOrRunning()) {
this.asyncTaskContext.get().cancel(true);
}
AbsListView absListView;
if (!ApplicationPreferences.applicationActivatorGridLayout(activityDataWrapper.context))
absListView = listView;
else
absListView = gridView;
if (absListView != null)
absListView.setAdapter(null);
if (profileListAdapter != null)
profileListAdapter.release();
if (activityDataWrapper != null)
activityDataWrapper.invalidateDataWrapper();
activityDataWrapper = null;
super.onDestroy();
}
private void updateHeader(Profile profile)
{
if (!ApplicationPreferences.applicationActivatorHeader(activityDataWrapper.context))
return;
if (activeProfileName == null)
// Activator opened from recent app list and setting for show header is changed
return;
if (profile == null)
{
activeProfileName.setText(getResources().getString(R.string.profiles_header_profile_name_no_activated));
activeProfileIcon.setImageResource(R.drawable.ic_profile_default);
}
else
{
activeProfileName.setText(DataWrapper.getProfileNameWithManualIndicator(profile, true, true, false, activityDataWrapper, false));
if (profile.getIsIconResourceID())
{
if (profile._iconBitmap != null)
activeProfileIcon.setImageBitmap(profile._iconBitmap);
else {
//int res = getResources().getIdentifier(profile.getIconIdentifier(), "drawable", getActivity().getPackageName());
int res = Profile.getIconResource(profile.getIconIdentifier());
activeProfileIcon.setImageResource(res); // icon resource
}
}
else
{
activeProfileIcon.setImageBitmap(profile._iconBitmap);
}
}
if (ApplicationPreferences.applicationActivatorPrefIndicator(activityDataWrapper.context))
{
ImageView profilePrefIndicatorImageView = getActivity().findViewById(R.id.act_prof_activated_profile_pref_indicator);
if (profilePrefIndicatorImageView != null)
{
if (profile == null)
profilePrefIndicatorImageView.setImageResource(R.drawable.ic_empty);
else {
if (profile._preferencesIndicator != null)
profilePrefIndicatorImageView.setImageBitmap(profile._preferencesIndicator);
else
profilePrefIndicatorImageView.setImageResource(R.drawable.ic_empty);
}
}
}
}
private void activateProfile(Profile profile)
{
if ((activityDataWrapper == null) || (profile == null))
return;
if (profile._porder != PORDER_FOR_IGNORED_PROFILE) {
activityDataWrapper.activateProfile(profile._id, PPApplication.STARTUP_SOURCE_ACTIVATOR, getActivity()/*, ""*/);
}
}
private void setProfileSelection(Profile profile, boolean refreshIcons) {
if (profileListAdapter != null)
{
int profilePos = ListView.INVALID_POSITION;
if (profile != null)
profilePos = profileListAdapter.getItemPosition(profile);
else {
if (!ApplicationPreferences.applicationActivatorGridLayout(activityDataWrapper.context)) {
if (listView != null)
profilePos = listView.getCheckedItemPosition();
}
else {
if (gridView != null)
profilePos = gridView.getCheckedItemPosition();
}
}
profileListAdapter.notifyDataSetChanged(refreshIcons);
if ((!ApplicationPreferences.applicationActivatorHeader(activityDataWrapper.context)) && (profilePos != ListView.INVALID_POSITION))
{
// set profile visible in list
if (!ApplicationPreferences.applicationActivatorGridLayout(activityDataWrapper.context)) {
if (listView != null) {
listView.setItemChecked(profilePos, true);
int last = listView.getLastVisiblePosition();
int first = listView.getFirstVisiblePosition();
if ((profilePos <= first) || (profilePos >= last)) {
listView.setSelection(profilePos);
}
}
}
else {
if (gridView != null) {
gridView.setItemChecked(profilePos, true);
int last = gridView.getLastVisiblePosition();
int first = gridView.getFirstVisiblePosition();
if ((profilePos <= first) || (profilePos >= last)) {
gridView.setSelection(profilePos);
}
}
}
}
}
}
public void refreshGUI(boolean refreshIcons)
{
if ((activityDataWrapper == null) || (profileListAdapter == null))
return;
((ActivateProfileActivity) getActivity()).setEventsRunStopIndicator();
Profile profileFromAdapter = profileListAdapter.getActivatedProfile();
if (profileFromAdapter != null)
profileFromAdapter._checked = false;
Profile profileFromDB = DatabaseHandler.getInstance(activityDataWrapper.context).getActivatedProfile();
if (profileFromDB != null) {
Profile profileFromDataWrapper = activityDataWrapper.getProfileById(profileFromDB._id, true,
ApplicationPreferences.applicationActivatorPrefIndicator(activityDataWrapper.context), false);
if (profileFromDataWrapper != null)
profileFromDataWrapper._checked = true;
updateHeader(profileFromDataWrapper);
setProfileSelection(profileFromDataWrapper, refreshIcons);
} else {
updateHeader(null);
setProfileSelection(null, refreshIcons);
}
profileListAdapter.notifyDataSetChanged(refreshIcons);
}
void showTargetHelps() {
/*if (Build.VERSION.SDK_INT <= 19)
// TapTarget.forToolbarMenuItem FC :-(
// Toolbar.findViewById() returns null
return;*/
if (getActivity() == null)
return;
if (((ActivateProfileActivity)getActivity()).targetHelpsSequenceStarted)
return;
ApplicationPreferences.getSharedPreferences(getActivity());
if (ApplicationPreferences.preferences.getBoolean(PREF_START_TARGET_HELPS, true) ||
ApplicationPreferences.preferences.getBoolean(ActivateProfileListAdapter.PREF_START_TARGET_HELPS, true)) {
//Log.d("ActivateProfileListFragment.showTargetHelps", "PREF_START_TARGET_HELPS_ORDER=true");
if (ApplicationPreferences.preferences.getBoolean(PREF_START_TARGET_HELPS, true)) {
//Log.d("ActivateProfileListFragment.showTargetHelps", "PREF_START_TARGET_HELPS=true");
SharedPreferences.Editor editor = ApplicationPreferences.preferences.edit();
editor.putBoolean(PREF_START_TARGET_HELPS, false);
editor.apply();
showAdapterTargetHelps();
}
else {
//Log.d("ActivateProfileListFragment.showTargetHelps", "PREF_START_TARGET_HELPS=false");
final Handler handler = new Handler(getActivity().getMainLooper());
handler.postDelayed(new Runnable() {
@Override
public void run() {
showAdapterTargetHelps();
}
}, 500);
}
}
else {
final Handler handler = new Handler(getActivity().getMainLooper());
handler.postDelayed(new Runnable() {
@Override
public void run() {
if (ActivatorTargetHelpsActivity.activity != null) {
//Log.d("ActivateProfileListFragment.showTargetHelps", "finish activity");
ActivatorTargetHelpsActivity.activity.finish();
ActivatorTargetHelpsActivity.activity = null;
//ActivatorTargetHelpsActivity.activatorActivity = null;
}
}
}, 500);
}
}
private void showAdapterTargetHelps() {
/*if (Build.VERSION.SDK_INT <= 19)
// TapTarget.forToolbarMenuItem FC :-(
// Toolbar.findViewById() returns null
return;*/
if (getActivity() == null)
return;
View itemView;
if (!ApplicationPreferences.applicationActivatorGridLayout(getActivity())) {
if (listView.getChildCount() > 1)
itemView = listView.getChildAt(1);
else
itemView = listView.getChildAt(0);
}
else {
if (gridView.getChildCount() > 1)
itemView = gridView.getChildAt(1);
else
itemView = gridView.getChildAt(0);
}
//Log.d("ActivateProfileListFragment.showAdapterTargetHelps", "profileListAdapter="+profileListAdapter);
//Log.d("ActivateProfileListFragment.showAdapterTargetHelps", "itemView="+itemView);
if ((profileListAdapter != null) && (itemView != null))
profileListAdapter.showTargetHelps(getActivity(), /*this,*/ itemView);
else {
final Handler handler = new Handler(getActivity().getMainLooper());
handler.postDelayed(new Runnable() {
@Override
public void run() {
if (ActivatorTargetHelpsActivity.activity != null) {
//Log.d("ActivateProfileListFragment.showAdapterTargetHelps", "finish activity");
ActivatorTargetHelpsActivity.activity.finish();
ActivatorTargetHelpsActivity.activity = null;
//ActivatorTargetHelpsActivity.activatorActivity = null;
}
}
}, 500);
}
}
}
| phoneProfilesPlus/src/main/java/sk/henrichg/phoneprofilesplus/ActivateProfileListFragment.java | package sk.henrichg.phoneprofilesplus;
import android.app.Fragment;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import java.lang.ref.WeakReference;
import java.util.Collections;
import java.util.Comparator;
public class ActivateProfileListFragment extends Fragment {
DataWrapper activityDataWrapper;
private ActivateProfileListAdapter profileListAdapter = null;
private ListView listView = null;
private GridView gridView = null;
private TextView activeProfileName;
private ImageView activeProfileIcon;
TextView textViewNoData;
private LinearLayout progressBar;
private WeakReference<LoadProfileListAsyncTask> asyncTaskContext;
private static final String START_TARGET_HELPS_ARGUMENT = "start_target_helps";
//public boolean targetHelpsSequenceStarted;
public static final String PREF_START_TARGET_HELPS = "activate_profile_list_fragment_start_target_helps";
public static final int PORDER_FOR_IGNORED_PROFILE = 1000000;
public ActivateProfileListFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// this is really important in order to save the state across screen
// configuration changes for example
setRetainInstance(true);
activityDataWrapper = new DataWrapper(getActivity().getApplicationContext(), false, 0);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView;
if (!ApplicationPreferences.applicationActivatorGridLayout(activityDataWrapper.context))
{
if (ApplicationPreferences.applicationActivatorPrefIndicator(activityDataWrapper.context) && ApplicationPreferences.applicationActivatorHeader(activityDataWrapper.context))
rootView = inflater.inflate(R.layout.activate_profile_list, container, false);
else
if (ApplicationPreferences.applicationActivatorHeader(activityDataWrapper.context))
rootView = inflater.inflate(R.layout.activate_profile_list_no_indicator, container, false);
else
rootView = inflater.inflate(R.layout.activate_profile_list_no_header, container, false);
}
else
{
if (ApplicationPreferences.applicationActivatorPrefIndicator(activityDataWrapper.context) && ApplicationPreferences.applicationActivatorHeader(activityDataWrapper.context))
rootView = inflater.inflate(R.layout.activate_profile_grid, container, false);
else
if (ApplicationPreferences.applicationActivatorHeader(activityDataWrapper.context))
rootView = inflater.inflate(R.layout.activate_profile_grid_no_indicator, container, false);
else
rootView = inflater.inflate(R.layout.activate_profile_grid_no_header, container, false);
}
return rootView;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
doOnViewCreated(view/*, savedInstanceState*/);
boolean startTargetHelps = getArguments() != null && getArguments().getBoolean(START_TARGET_HELPS_ARGUMENT, false);
if (startTargetHelps)
showTargetHelps();
}
private void doOnViewCreated(View view/*, Bundle savedInstanceState*/)
{
activeProfileName = view.findViewById(R.id.act_prof_activated_profile_name);
activeProfileIcon = view.findViewById(R.id.act_prof_activated_profile_icon);
if (!ApplicationPreferences.applicationActivatorGridLayout(activityDataWrapper.context))
listView = view.findViewById(R.id.act_prof_profiles_list);
else
gridView = view.findViewById(R.id.act_prof_profiles_grid);
textViewNoData = view.findViewById(R.id.act_prof_list_empty);
progressBar = view.findViewById(R.id.act_prof_list_linla_progress);
AbsListView absListView;
if (!ApplicationPreferences.applicationActivatorGridLayout(activityDataWrapper.context))
absListView = listView;
else
absListView = gridView;
//absListView.setLongClickable(false);
absListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (!ApplicationPreferences.applicationLongClickActivation(activityDataWrapper.context))
//activateProfileWithAlert(position);
activateProfile((Profile)profileListAdapter.getItem(position));
}
});
absListView.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
if (ApplicationPreferences.applicationLongClickActivation(activityDataWrapper.context))
//activateProfileWithAlert(position);
activateProfile((Profile)profileListAdapter.getItem(position));
return false;
}
});
//absListView.setRemoveListener(onRemove);
if (!activityDataWrapper.profileListFilled)
{
LoadProfileListAsyncTask asyncTask = new LoadProfileListAsyncTask(this);
this.asyncTaskContext = new WeakReference<>(asyncTask );
asyncTask.execute();
}
else
{
absListView.setAdapter(profileListAdapter);
doOnStart();
}
}
private static class LoadProfileListAsyncTask extends AsyncTask<Void, Void, Void> {
private final WeakReference<ActivateProfileListFragment> fragmentWeakRef;
private final DataWrapper dataWrapper;
private class ProfileComparator implements Comparator<Profile> {
public int compare(Profile lhs, Profile rhs) {
int res = 0;
if ((lhs != null) && (rhs != null))
res = lhs._porder - rhs._porder;
return res;
}
}
private LoadProfileListAsyncTask (ActivateProfileListFragment fragment) {
this.fragmentWeakRef = new WeakReference<>(fragment);
this.dataWrapper = new DataWrapper(fragment.getActivity().getApplicationContext(), false, 0);
}
@Override
protected void onPreExecute()
{
super.onPreExecute();
ActivateProfileListFragment fragment = this.fragmentWeakRef.get();
if ((fragment != null) && (fragment.isAdded())) {
fragment.textViewNoData.setVisibility(View.GONE);
fragment.progressBar.setVisibility(View.VISIBLE);
}
}
@Override
protected Void doInBackground(Void... params) {
this.dataWrapper.fillProfileList(true, ApplicationPreferences.applicationActivatorPrefIndicator(dataWrapper.context));
if (!ApplicationPreferences.applicationActivatorHeader(this.dataWrapper.context))
{
Profile profile = this.dataWrapper.getActivatedProfile(false, false);
if ((profile != null) && (!profile._showInActivator))
{
profile._showInActivator = true;
profile._porder = -1;
}
}
if (ApplicationPreferences.applicationActivatorGridLayout(this.dataWrapper.context)) {
int count = 0;
for (Profile profile : this.dataWrapper.profileList)
{
if (profile._showInActivator)
++count;
}
int modulo = count % 3;
if (modulo > 0) {
for (int i = 0; i < 3 - modulo; i++) {
Profile profile = DataWrapper.getNonInitializedProfile(
dataWrapper.context.getResources().getString(R.string.profile_name_default),
Profile.PROFILE_ICON_DEFAULT, PORDER_FOR_IGNORED_PROFILE);
profile._showInActivator = true;
this.dataWrapper.profileList.add(profile);
}
}
}
Collections.sort(this.dataWrapper.profileList, new ProfileComparator());
return null;
}
@Override
protected void onPostExecute(Void response) {
super.onPostExecute(response);
final ActivateProfileListFragment fragment = this.fragmentWeakRef.get();
if ((fragment != null) && (fragment.isAdded())) {
fragment.progressBar.setVisibility(View.GONE);
// get local profileList
this.dataWrapper.fillProfileList(true, ApplicationPreferences.applicationActivatorPrefIndicator(dataWrapper.context));
// set copy local profile list into activity profilesDataWrapper
fragment.activityDataWrapper.copyProfileList(this.dataWrapper);
if (fragment.activityDataWrapper.profileList.size() == 0)
{
// no profile in list, start Editor
Intent intent = new Intent(fragment.getActivity().getBaseContext(), EditorProfilesActivity.class);
intent.putExtra(PPApplication.EXTRA_STARTUP_SOURCE, PPApplication.STARTUP_SOURCE_ACTIVATOR_START);
fragment.getActivity().startActivity(intent);
fragment.getActivity().finish();
return;
}
fragment.profileListAdapter = new ActivateProfileListAdapter(fragment, /*fragment.profileList, */fragment.activityDataWrapper);
AbsListView absListView;
if (!ApplicationPreferences.applicationActivatorGridLayout(dataWrapper.context))
absListView = fragment.listView;
else
absListView = fragment.gridView;
absListView.setAdapter(fragment.profileListAdapter);
fragment.doOnStart();
final Handler handler = new Handler(fragment.getActivity().getMainLooper());
handler.postDelayed(new Runnable() {
@Override
public void run() {
if (fragment.getActivity() != null)
((ActivateProfileActivity)fragment.getActivity()).startTargetHelpsActivity();
}
}, 1000);
}
}
}
private boolean isAsyncTaskPendingOrRunning() {
try {
return this.asyncTaskContext != null &&
this.asyncTaskContext.get() != null &&
!this.asyncTaskContext.get().getStatus().equals(AsyncTask.Status.FINISHED);
} catch (Exception e) {
return false;
}
}
private void doOnStart()
{
//long nanoTimeStart = PPApplication.startMeasuringRunTime();
Profile profile = activityDataWrapper.getActivatedProfile(true, ApplicationPreferences.applicationActivatorPrefIndicator(activityDataWrapper.context));
updateHeader(profile);
setProfileSelection(profile, false);
//PPApplication.getMeasuredRunTime(nanoTimeStart, "ActivateProfileActivity.onStart");
}
@Override
public void onDestroy()
{
if (isAsyncTaskPendingOrRunning()) {
this.asyncTaskContext.get().cancel(true);
}
AbsListView absListView;
if (!ApplicationPreferences.applicationActivatorGridLayout(activityDataWrapper.context))
absListView = listView;
else
absListView = gridView;
if (absListView != null)
absListView.setAdapter(null);
if (profileListAdapter != null)
profileListAdapter.release();
if (activityDataWrapper != null)
activityDataWrapper.invalidateDataWrapper();
activityDataWrapper = null;
super.onDestroy();
}
private void updateHeader(Profile profile)
{
if (!ApplicationPreferences.applicationActivatorHeader(activityDataWrapper.context))
return;
if (activeProfileName == null)
// Activator opened from recent app list and setting for show header is changed
return;
if (profile == null)
{
activeProfileName.setText(getResources().getString(R.string.profiles_header_profile_name_no_activated));
activeProfileIcon.setImageResource(R.drawable.ic_profile_default);
}
else
{
activeProfileName.setText(DataWrapper.getProfileNameWithManualIndicator(profile, true, true, false, activityDataWrapper, false));
if (profile.getIsIconResourceID())
{
if (profile._iconBitmap != null)
activeProfileIcon.setImageBitmap(profile._iconBitmap);
else {
//int res = getResources().getIdentifier(profile.getIconIdentifier(), "drawable", getActivity().getPackageName());
int res = Profile.getIconResource(profile.getIconIdentifier());
activeProfileIcon.setImageResource(res); // icon resource
}
}
else
{
activeProfileIcon.setImageBitmap(profile._iconBitmap);
}
}
if (ApplicationPreferences.applicationActivatorPrefIndicator(activityDataWrapper.context))
{
ImageView profilePrefIndicatorImageView = getActivity().findViewById(R.id.act_prof_activated_profile_pref_indicator);
if (profilePrefIndicatorImageView != null)
{
if (profile == null)
profilePrefIndicatorImageView.setImageResource(R.drawable.ic_empty);
else {
if (profile._preferencesIndicator != null)
profilePrefIndicatorImageView.setImageBitmap(profile._preferencesIndicator);
else
profilePrefIndicatorImageView.setImageResource(R.drawable.ic_empty);
}
}
}
}
private void activateProfile(Profile profile)
{
if ((activityDataWrapper == null) || (profile == null))
return;
if (profile._porder != PORDER_FOR_IGNORED_PROFILE) {
activityDataWrapper.activateProfile(profile._id, PPApplication.STARTUP_SOURCE_ACTIVATOR, getActivity()/*, ""*/);
}
}
private void setProfileSelection(Profile profile, boolean refreshIcons) {
if (profileListAdapter != null)
{
int profilePos;
if (profile != null)
profilePos = profileListAdapter.getItemPosition(profile);
else {
if (!ApplicationPreferences.applicationActivatorGridLayout(activityDataWrapper.context))
profilePos = listView.getCheckedItemPosition();
else
profilePos = gridView.getCheckedItemPosition();
}
profileListAdapter.notifyDataSetChanged(refreshIcons);
if ((!ApplicationPreferences.applicationActivatorHeader(activityDataWrapper.context)) && (profilePos != ListView.INVALID_POSITION))
{
// set profile visible in list
if (!ApplicationPreferences.applicationActivatorGridLayout(activityDataWrapper.context)) {
listView.setItemChecked(profilePos, true);
int last = listView.getLastVisiblePosition();
int first = listView.getFirstVisiblePosition();
if ((profilePos <= first) || (profilePos >= last)) {
listView.setSelection(profilePos);
}
}
else {
gridView.setItemChecked(profilePos, true);
int last = gridView.getLastVisiblePosition();
int first = gridView.getFirstVisiblePosition();
if ((profilePos <= first) || (profilePos >= last)) {
gridView.setSelection(profilePos);
}
}
}
}
}
public void refreshGUI(boolean refreshIcons)
{
if ((activityDataWrapper == null) || (profileListAdapter == null))
return;
((ActivateProfileActivity) getActivity()).setEventsRunStopIndicator();
Profile profileFromAdapter = profileListAdapter.getActivatedProfile();
if (profileFromAdapter != null)
profileFromAdapter._checked = false;
Profile profileFromDB = DatabaseHandler.getInstance(activityDataWrapper.context).getActivatedProfile();
if (profileFromDB != null) {
Profile profileFromDataWrapper = activityDataWrapper.getProfileById(profileFromDB._id, true,
ApplicationPreferences.applicationActivatorPrefIndicator(activityDataWrapper.context), false);
if (profileFromDataWrapper != null)
profileFromDataWrapper._checked = true;
updateHeader(profileFromDataWrapper);
setProfileSelection(profileFromDataWrapper, refreshIcons);
} else {
updateHeader(null);
setProfileSelection(null, refreshIcons);
}
profileListAdapter.notifyDataSetChanged(refreshIcons);
}
void showTargetHelps() {
/*if (Build.VERSION.SDK_INT <= 19)
// TapTarget.forToolbarMenuItem FC :-(
// Toolbar.findViewById() returns null
return;*/
if (getActivity() == null)
return;
if (((ActivateProfileActivity)getActivity()).targetHelpsSequenceStarted)
return;
ApplicationPreferences.getSharedPreferences(getActivity());
if (ApplicationPreferences.preferences.getBoolean(PREF_START_TARGET_HELPS, true) ||
ApplicationPreferences.preferences.getBoolean(ActivateProfileListAdapter.PREF_START_TARGET_HELPS, true)) {
//Log.d("ActivateProfileListFragment.showTargetHelps", "PREF_START_TARGET_HELPS_ORDER=true");
if (ApplicationPreferences.preferences.getBoolean(PREF_START_TARGET_HELPS, true)) {
//Log.d("ActivateProfileListFragment.showTargetHelps", "PREF_START_TARGET_HELPS=true");
SharedPreferences.Editor editor = ApplicationPreferences.preferences.edit();
editor.putBoolean(PREF_START_TARGET_HELPS, false);
editor.apply();
showAdapterTargetHelps();
}
else {
//Log.d("ActivateProfileListFragment.showTargetHelps", "PREF_START_TARGET_HELPS=false");
final Handler handler = new Handler(getActivity().getMainLooper());
handler.postDelayed(new Runnable() {
@Override
public void run() {
showAdapterTargetHelps();
}
}, 500);
}
}
else {
final Handler handler = new Handler(getActivity().getMainLooper());
handler.postDelayed(new Runnable() {
@Override
public void run() {
if (ActivatorTargetHelpsActivity.activity != null) {
//Log.d("ActivateProfileListFragment.showTargetHelps", "finish activity");
ActivatorTargetHelpsActivity.activity.finish();
ActivatorTargetHelpsActivity.activity = null;
//ActivatorTargetHelpsActivity.activatorActivity = null;
}
}
}, 500);
}
}
private void showAdapterTargetHelps() {
/*if (Build.VERSION.SDK_INT <= 19)
// TapTarget.forToolbarMenuItem FC :-(
// Toolbar.findViewById() returns null
return;*/
if (getActivity() == null)
return;
View itemView;
if (!ApplicationPreferences.applicationActivatorGridLayout(getActivity())) {
if (listView.getChildCount() > 1)
itemView = listView.getChildAt(1);
else
itemView = listView.getChildAt(0);
}
else {
if (gridView.getChildCount() > 1)
itemView = gridView.getChildAt(1);
else
itemView = gridView.getChildAt(0);
}
//Log.d("ActivateProfileListFragment.showAdapterTargetHelps", "profileListAdapter="+profileListAdapter);
//Log.d("ActivateProfileListFragment.showAdapterTargetHelps", "itemView="+itemView);
if ((profileListAdapter != null) && (itemView != null))
profileListAdapter.showTargetHelps(getActivity(), /*this,*/ itemView);
else {
final Handler handler = new Handler(getActivity().getMainLooper());
handler.postDelayed(new Runnable() {
@Override
public void run() {
if (ActivatorTargetHelpsActivity.activity != null) {
//Log.d("ActivateProfileListFragment.showAdapterTargetHelps", "finish activity");
ActivatorTargetHelpsActivity.activity.finish();
ActivatorTargetHelpsActivity.activity = null;
//ActivatorTargetHelpsActivity.activatorActivity = null;
}
}
}, 500);
}
}
}
| Fixed FC: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.AbsListView.setItemChecked(int, boolean)' on a null object reference
at sk.henrichg.phoneprofilesplus.ActivateProfileListFragment.setProfileSelection(ActivateProfileListFragment.java:414)
| phoneProfilesPlus/src/main/java/sk/henrichg/phoneprofilesplus/ActivateProfileListFragment.java | Fixed FC: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.AbsListView.setItemChecked(int, boolean)' on a null object reference at sk.henrichg.phoneprofilesplus.ActivateProfileListFragment.setProfileSelection(ActivateProfileListFragment.java:414) | <ide><path>honeProfilesPlus/src/main/java/sk/henrichg/phoneprofilesplus/ActivateProfileListFragment.java
<ide> private void setProfileSelection(Profile profile, boolean refreshIcons) {
<ide> if (profileListAdapter != null)
<ide> {
<del> int profilePos;
<add> int profilePos = ListView.INVALID_POSITION;
<ide>
<ide> if (profile != null)
<ide> profilePos = profileListAdapter.getItemPosition(profile);
<ide> else {
<del> if (!ApplicationPreferences.applicationActivatorGridLayout(activityDataWrapper.context))
<del> profilePos = listView.getCheckedItemPosition();
<del> else
<del> profilePos = gridView.getCheckedItemPosition();
<add> if (!ApplicationPreferences.applicationActivatorGridLayout(activityDataWrapper.context)) {
<add> if (listView != null)
<add> profilePos = listView.getCheckedItemPosition();
<add> }
<add> else {
<add> if (gridView != null)
<add> profilePos = gridView.getCheckedItemPosition();
<add> }
<ide> }
<ide>
<ide> profileListAdapter.notifyDataSetChanged(refreshIcons);
<ide> {
<ide> // set profile visible in list
<ide> if (!ApplicationPreferences.applicationActivatorGridLayout(activityDataWrapper.context)) {
<del> listView.setItemChecked(profilePos, true);
<del> int last = listView.getLastVisiblePosition();
<del> int first = listView.getFirstVisiblePosition();
<del> if ((profilePos <= first) || (profilePos >= last)) {
<del> listView.setSelection(profilePos);
<add> if (listView != null) {
<add> listView.setItemChecked(profilePos, true);
<add> int last = listView.getLastVisiblePosition();
<add> int first = listView.getFirstVisiblePosition();
<add> if ((profilePos <= first) || (profilePos >= last)) {
<add> listView.setSelection(profilePos);
<add> }
<ide> }
<ide> }
<ide> else {
<del> gridView.setItemChecked(profilePos, true);
<del> int last = gridView.getLastVisiblePosition();
<del> int first = gridView.getFirstVisiblePosition();
<del> if ((profilePos <= first) || (profilePos >= last)) {
<del> gridView.setSelection(profilePos);
<add> if (gridView != null) {
<add> gridView.setItemChecked(profilePos, true);
<add> int last = gridView.getLastVisiblePosition();
<add> int first = gridView.getFirstVisiblePosition();
<add> if ((profilePos <= first) || (profilePos >= last)) {
<add> gridView.setSelection(profilePos);
<add> }
<ide> }
<ide> }
<ide> } |
|
JavaScript | mit | 99abdc3d012102ca61c96bc78abb981193a7eb15 | 0 | JayCanuck/enyo-2-components,JayCanuck/enyo-ext,JayCanuck/enyo-ext,JayCanuck/enyo-2-components | /**
Enyo component bindings for Socket.IO, with dynamic support for the Enyo event system.
For more information about Socket.IO, see [http://socket.io](http://socket.io)
*/
enyo.kind({
name: "enyo.Socket",
kind: "enyo.Component",
//* Websocket url to connect to.
url: "",
//* Connection timeout (in milliseconds).
timeout: 10000,
//* Whether or not to multiplex connections.
multiplex: true,
//* Whether or not to create new sockets for each new websocket.
forceNew: false,
//* Number of reconnection attempts to make.
reconnectionAttempts: Infinity,
//* Delay time on reconnection (in milliseconds).
reconnectionDelay: 1000,
//* Maximum delay time on reconnection (in milliseconds).
reconnectionDelayMax: 5000,
/**
As the events received from the websocket can be anything the server wants to send,
the event system in _enyo.Socket_ is dynamic and will listen and bubble for any events
specified. For example,
{kind:"enyo.Socket", onconnect:"con", ontest:"test"}
will automatically listen for (and bubble) "connect" and "test" events. However, as
you may have noticed, this dynamic event handling requires you to specify a handler function
inline in the component declaration. If you don't want that, and simply want events to bubble
up, to be handled elsewhere, you can specify those events in the _"bubblers"_ array property.
*/
events: {
},
/**
Set events to bubble websocket events for. For example,
{kind:"enyo.Socket", bubblers:["connect", "test"]}
will bubble the "connect" and "test" events, for handling anywhere in its component hierarchy.
*/
bubblers: [],
//* attempts to connect the websocket to the server
connect: function() {
this.eventQueue = enyo.clone(this.bubblers);
var evScan = [this, this.handlers];
for(var i=0; i<evScan.length; i++) {
for(var x in evScan[i]) {
if(x.indexOf("on")==0) {
var ev = x.substring(2);
if(this.eventQueue.indexOf(ev)<0) {
this.eventQueue.push(ev);
}
}
}
}
var opts = {
multiplex: this.multiplex,
forceNew: this.forceNew,
reconnectionAttempts: this.reconnectionAttempts,
reconnectionDelay: this.reconnectionDelay,
reconnectionDelayMax: this.reconnectionDelayMax
};
this.socket = io.connect(this.url, opts);
for(var i=0; i<this.eventQueue.length; i++) {
var currEv = this.eventQueue[i];
this.socket.on(currEv, enyo.bind(this, function(data) {
this.bubble("on" + currEv, data);
}));
}
},
//* Sends string data in the form of a `message` event to the server.
send: function(inMessage) {
if(this.socket) {
this.socket.send(inMessage);
}
},
//* Emits an event and event data to the server.
emit: function(inEvent, inParams) {
if(this.socket) {
this.socket.emit(inEvent, inParams);
}
},
//* Disconnects the websocket
disconnect: function() {
if(this.socket) {
this.socket.disconnect();
this.socket = undefined;
}
},
statics: {
//* Default events that are part of the Socket.IO system
Events: [
"connect",
"connecting",
"connect_failed",
"message",
"reconnect",
"reconnecting",
"reconnect_failed",
"disconnect",
"error"
]
}
}); | socket/Socket.js | /**
Enyo component bindings for Socket.IO, with dynamic support for the Enyo event system.
For more information about Socket.IO, see [http://socket.io](http://socket.io)
*/
enyo.kind({
name: "enyo.Socket",
kind: "enyo.Component",
//* Websocket url to connect to.
url: "",
//* Connection timeout (in milliseconds).
timeout: 10000,
//* Whether or not to multiplex connections.
multiplex: true,
//* Whether or not to create new sockets for each new websocket.
forceNew: false,
//* Number of reconnection attempts to make.
reconnectionAttempts: Infinity,
//* Delay time on reconnection (in milliseconds).
reconnectionDelay: 1000,
//* Maximum delay time on reconnection (in milliseconds).
reconnectionDelayMax: 5000,
/**
As the events received from the websocket can be anything the server wants to send,
the event system in _enyo.Socket_ is dynamic and will listen and bubble for any events
specified. For example,
{kind:"enyo.Socket", onconnect:"con", ontest:"test"}
will automatically listen for (and bubble) "connect" and "test" events. However, as
you may have noticed, this dynamic event handling requires you to specify a handler function
inline in the component declaration. If you don't want that, and simply want events to bubble
up, to be handled elsewhere, you can specify those events in the _"bubblers"_ array property.
*/
events: {
},
/**
Set events to bubble websocket events for. For example,
{kind:"enyo.Socket", bubblers:["connect", "test"]}
will bubble the "connect" and "test" events, for handling anywhere in its component hierarchy.
*/
bubblers: [],
//* attempts to connect the websocket to the server
connect: function() {
this.eventQueue = enyo.clone(this.bubblers);
var evScan = [this, this.handlers];
for(var i=0; i<evScan.length; i++) {
for(var x in evScan[i]) {
if(x.indexOf("on")==0) {
var ev = x.substring(2);
if(this.eventQueue.indexOf(ev)<0) {
this.eventQueue.push(ev);
}
}
}
}
var opts = {
multiplex: this.multiplex,
forceNew: this.forceNew,
reconnectionAttempts: this.reconnectionAttempts,
reconnectionDelay: this.reconnectionDelay,
reconnectionDelayMax: this.reconnectionDelayMax
};
this.socket = io.connect(this.url, opts);
this.socketEvents = {};
for(var i=0; i<this.eventQueue; i++) {
var currEv = this.eventQueue[i];
this.socket.on(currEv, enyo.bind(this, function(data) {
this.bubble("on" + currEv, data);
}));
}
},
//* Sends data in the form of a `message` event to the server.
send: function(inParams) {
if(this.socket) {
this.socket.send(arguments);
}
},
//* Emits an event and event data to the server.
emit: function(inEvent, inParams) {
if(this.socket) {
this.socket.emit(arguments);
}
},
//* Disconnects the websocket
disconnect: function() {
if(this.socket) {
this.socket.disconnect();
this.socket = undefined;
}
},
statics: {
//* Default events that are part of the Socket.IO system
Events: [
"connect",
"connecting",
"connect_failed",
"message",
"reconnect",
"reconnecting",
"reconnect_failed",
"disconnect",
"error"
]
}
}); | Fixed issues with Socket.IO event listening/sending/emitting
| socket/Socket.js | Fixed issues with Socket.IO event listening/sending/emitting | <ide><path>ocket/Socket.js
<ide> reconnectionDelayMax: this.reconnectionDelayMax
<ide> };
<ide> this.socket = io.connect(this.url, opts);
<del> this.socketEvents = {};
<del> for(var i=0; i<this.eventQueue; i++) {
<add> for(var i=0; i<this.eventQueue.length; i++) {
<ide> var currEv = this.eventQueue[i];
<ide> this.socket.on(currEv, enyo.bind(this, function(data) {
<ide> this.bubble("on" + currEv, data);
<ide> }));
<ide> }
<ide> },
<del> //* Sends data in the form of a `message` event to the server.
<del> send: function(inParams) {
<add> //* Sends string data in the form of a `message` event to the server.
<add> send: function(inMessage) {
<ide> if(this.socket) {
<del> this.socket.send(arguments);
<add> this.socket.send(inMessage);
<ide> }
<ide> },
<ide> //* Emits an event and event data to the server.
<ide> emit: function(inEvent, inParams) {
<ide> if(this.socket) {
<del> this.socket.emit(arguments);
<add> this.socket.emit(inEvent, inParams);
<ide> }
<ide> },
<ide> //* Disconnects the websocket |
|
Java | apache-2.0 | d422946174c29f6d31b90581d6ba23f60ad542c7 | 0 | MyersResearchGroup/iBioSim,MyersResearchGroup/iBioSim,MyersResearchGroup/iBioSim | package lhpn2sbml.parser;
//import gcm2sbml.util.GlobalConstants;
import java.io.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
//import javax.swing.JOptionPane;
import biomodelsim.Log;
/**
* This class describes an LHPN file
*
* @author Kevin Jones
* @organization University of Utah
*/
public class LHPNFile {
private HashMap<String, Boolean> places;
private HashMap<String, String> inputs;
private HashMap<String, String> outputs;
private HashMap<String, String> enablings;
private HashMap<String, Properties> controlFlow;
private HashMap<String, Properties> controlPlaces;
private HashMap<String, Properties> variables;
private HashMap<String, String> integers;
private HashMap<String, Properties> rateAssignments;
private HashMap<String, Properties> contAssignments;
private HashMap<String, Properties> intAssignments;
private HashMap<String, String> delays;
private HashMap<String, String> transitionRates;
private HashMap<String, Properties> booleanAssignments;
private String property;
private Log log;
public LHPNFile(Log log) {
this.log = log;
places = new HashMap<String, Boolean>();
inputs = new HashMap<String, String>();
outputs = new HashMap<String, String>();
enablings = new HashMap<String, String>();
delays = new HashMap<String, String>();
transitionRates = new HashMap<String, String>();
booleanAssignments = new HashMap<String, Properties>();
controlFlow = new HashMap<String, Properties>();
controlPlaces = new HashMap<String, Properties>();
variables = new HashMap<String, Properties>();
integers = new HashMap<String, String>();
rateAssignments = new HashMap<String, Properties>();
contAssignments = new HashMap<String, Properties>();
intAssignments = new HashMap<String, Properties>();
}
public LHPNFile() {
places = new HashMap<String, Boolean>();
inputs = new HashMap<String, String>();
outputs = new HashMap<String, String>();
enablings = new HashMap<String, String>();
delays = new HashMap<String, String>();
transitionRates = new HashMap<String, String>();
booleanAssignments = new HashMap<String, Properties>();
controlFlow = new HashMap<String, Properties>();
controlPlaces = new HashMap<String, Properties>();
variables = new HashMap<String, Properties>();
integers = new HashMap<String, String>();
rateAssignments = new HashMap<String, Properties>();
contAssignments = new HashMap<String, Properties>();
intAssignments = new HashMap<String, Properties>();
}
public void save(String filename) {
try {
String file = filename;
PrintStream p = new PrintStream(new FileOutputStream(filename));
StringBuffer buffer = new StringBuffer();
HashMap<String, Integer> boolOrder = new HashMap<String, Integer>();
int i = 0;
if (!inputs.isEmpty()) {
buffer.append(".inputs ");
for (String s : inputs.keySet()) {
if (inputs.get(s) != null) {
buffer.append(s + " ");
boolOrder.put(s, i);
i++;
}
}
buffer.append("\n");
}
if (!outputs.isEmpty()) {
buffer.append(".outputs ");
for (String s : outputs.keySet()) {
if (outputs.get(s) != null) {
buffer.append(s + " ");
boolOrder.put(s, i);
i++;
}
}
buffer.append("\n");
}
if (!controlFlow.isEmpty()) {
buffer.append(".dummy ");
for (String s : controlFlow.keySet()) {
buffer.append(s + " ");
}
buffer.append("\n");
}
if (!variables.isEmpty() || !integers.isEmpty()) {
buffer.append("#@.variables ");
for (String s : variables.keySet()) {
buffer.append(s + " ");
}
for (String s : integers.keySet()) {
buffer.append(s + " ");
}
buffer.append("\n");
}
if (!places.isEmpty()) {
buffer.append("#|.places ");
for (String s : places.keySet()) {
buffer.append(s + " ");
}
buffer.append("\n");
}
if (!inputs.isEmpty() || !outputs.isEmpty()) {
boolean flag = false;
for (i = 0; i < boolOrder.size(); i++) {
for (String s : inputs.keySet()) {
if (boolOrder.get(s).equals(i)) {
if (!flag) {
buffer.append("#@.init_state [");
flag = true;
}
if (inputs.get(s).equals("true")) {
buffer.append("1");
}
else if (inputs.get(s).equals("false")) {
buffer.append("0");
}
else {
buffer.append("X");
}
}
}
for (String s : outputs.keySet()) {
if (s != null && boolOrder.get(s) != null) {
// log.addText(s);
if (boolOrder.get(s).equals(i) && outputs.get(s) != null) {
if (!flag) {
buffer.append("#@.init_state [");
flag = true;
}
if (outputs.get(s).equals("true")) {
buffer.append("1");
}
else if (outputs.get(s).equals("false")) {
buffer.append("0");
}
else {
buffer.append("X");
}
}
}
}
}
if (flag) {
buffer.append("]\n");
}
}
if (!controlFlow.isEmpty()) {
buffer.append(".graph\n");
for (String s : controlFlow.keySet()) {
// log.addText(s);
if (controlFlow.get(s) != null) {
Properties prop = controlFlow.get(s);
// log.addText(s + prop.getProperty("to"));
if (prop.getProperty("to") != null) {
String toString = prop.getProperty("to");
if (toString != null) {
// log.addText("to " + toString);
String[] toArray = toString.split("\\s");
for (i = 0; i < toArray.length; i++) {
if (toArray[i] != null && !toArray[i].equals("null")) {
buffer.append(s + " " + toArray[i] + "\n");
}
}
}
}
if (prop.getProperty("from") != null) {
String fromString = prop.getProperty("from");
if (fromString != null) {
// log.addText("from "+ fromString);
String[] fromArray = fromString.split("\\s");
for (i = 0; i < fromArray.length; i++) {
if (fromArray[i] != null && !fromArray[i].equals("null")) {
buffer.append(fromArray[i] + " " + s + "\n");
}
}
}
}
}
}
}
boolean flag = false;
if (!places.keySet().isEmpty()) {
for (String s : places.keySet()) {
if (places.get(s).equals(true)) {
if (!flag) {
buffer.append(".marking {");
flag = true;
}
buffer.append(s + " ");
}
}
if (flag) {
buffer.append("}\n");
}
}
if (property != null && !property.equals("")) {
buffer.append("#@.property " + property + "\n");
}
if (!variables.isEmpty() || !integers.isEmpty()) {
buffer.append("#@.init_vals {");
for (String s : variables.keySet()) {
Properties prop = variables.get(s);
buffer.append("<" + s + "=" + prop.getProperty("value") + ">");
}
for (String s : integers.keySet()) {
String ic = integers.get(s);
buffer.append("<" + s + "=" + ic + ">");
}
if (!variables.isEmpty()) {
buffer.append("}\n#@.init_rates {");
for (String s : variables.keySet()) {
Properties prop = variables.get(s);
buffer.append("<" + s + "=" + prop.getProperty("rate") + ">");
}
}
buffer.append("}\n");
}
if (!enablings.isEmpty()) {
flag = false;
for (String s : enablings.keySet()) {
if (s != null && !enablings.get(s).equals("")) {
if (!flag) {
buffer.append("#@.enablings {");
flag = true;
}
// log.addText("here " + enablings.get(s));
buffer.append("<" + s + "=[" + enablings.get(s) + "]>");
}
}
if (flag) {
buffer.append("}\n");
}
}
if (!contAssignments.isEmpty() || !intAssignments.isEmpty()) {
flag = false;
for (String s : contAssignments.keySet()) {
Properties prop = contAssignments.get(s);
// log.addText(prop.toString());
if (!prop.isEmpty()) {
if (!flag) {
buffer.append("#@.assignments {");
flag = true;
}
buffer.append("<" + s + "=");
for (Object key : prop.keySet()) {
String t = (String) key;
buffer.append("[" + t + ":=" + prop.getProperty(t) + "]");
}
buffer.append(">");
}
}
for (String s : intAssignments.keySet()) {
Properties prop = intAssignments.get(s);
if (!prop.isEmpty()) {
if (!flag) {
buffer.append("#@.assignments {");
flag = true;
}
buffer.append("<" + s + "=");
for (Object key : prop.keySet()) {
String t = (String) key;
// log.addText("key " + t);
buffer.append("[" + t + ":=" + prop.getProperty(t) + "]");
}
buffer.append(">");
}
}
if (flag) {
buffer.append("}\n");
}
}
if (!rateAssignments.isEmpty()) {
flag = false;
for (String s : rateAssignments.keySet()) {
boolean varFlag = false;
Properties prop = rateAssignments.get(s);
for (Object key : prop.keySet()) {
String t = (String) key;
if (!t.equals("")) {
if (!flag) {
buffer.append("#@.rate_assignments {");
flag = true;
}
if (!varFlag) {
buffer.append("<" + s + "=");
varFlag = true;
}
buffer.append("[" + t + ":=" + prop.getProperty(t) + "]");
}
}
if (varFlag) {
buffer.append(">");
}
}
if (flag) {
buffer.append("}\n");
}
}
if (!delays.isEmpty()) {
buffer.append("#@.delay_assignments {");
for (String s : delays.keySet()) {
buffer.append("<" + s + "=" + delays.get(s) + ">");
}
buffer.append("}\n");
}
if (!transitionRates.isEmpty()) {
buffer.append("#@.transition_rates {");
for (String s : transitionRates.keySet()) {
buffer.append("<" + s + "=" + transitionRates.get(s) + ">");
}
buffer.append("}\n");
}
if (!booleanAssignments.isEmpty()) {
flag = false;
for (String s : booleanAssignments.keySet()) {
if (!s.equals("")) {
boolean varFlag = false;
Properties prop = booleanAssignments.get(s);
for (Object key : prop.keySet()) {
String t = (String) key;
if (!t.equals("") && (isInput(t) || isOutput(t))) {
if (!flag) {
buffer.append("#@.boolean_assignments {");
flag = true;
}
if (!varFlag) {
buffer.append("<" + s + "=");
varFlag = true;
}
buffer.append("[" + t + ":=" + prop.getProperty(t) + "]");
}
}
if (varFlag) {
buffer.append(">");
}
}
}
if (flag) {
buffer.append("}\n");
}
}
if (!variables.isEmpty()) {
buffer.append("#@.continuous ");
for (String s : variables.keySet()) {
buffer.append(s + " ");
}
buffer.append("\n");
}
if (buffer.toString().length() > 0) {
buffer.append(".end\n");
}
// System.out.print(buffer);
p.print(buffer);
p.close();
if (log != null) {
log.addText("Saving:\n" + file + "\n");
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public void load(String filename) {
places = new HashMap<String, Boolean>();
inputs = new HashMap<String, String>();
outputs = new HashMap<String, String>();
enablings = new HashMap<String, String>();
controlFlow = new HashMap<String, Properties>();
controlPlaces = new HashMap<String, Properties>();
variables = new HashMap<String, Properties>();
contAssignments = new HashMap<String, Properties>();
rateAssignments = new HashMap<String, Properties>();
StringBuffer data = new StringBuffer();
try {
BufferedReader in = new BufferedReader(new FileReader(filename));
String str;
while ((str = in.readLine()) != null) {
data.append(str + "\n");
// System.out.println(str);
}
in.close();
}
catch (IOException e) {
e.printStackTrace();
throw new IllegalStateException("Error opening file");
}
try {
parseProperty(data);
// System.out.println("check1");
// log.addText("check1");
parseInOut(data);
// System.out.println("check2");
// log.addText("check2");
// parseTransitions(data);
parseControlFlow(data);
// System.out.println("check3");
// log.addText("check3");
parseVars(data);
// System.out.println("check4");
// log.addText("check");
parseIntegers(data);
// parseInitialVals(data);
// System.out.println("check5");
// log.addText("check4");
parsePlaces(data);
parseMarking(data);
// System.out.println("check6");
// log.addText("check5");
parseEnabling(data);
// System.out.println("check7");
// log.addText("check6");
parseAssign(data);
// System.out.println("check8");
// log.addText("check7");
parseRateAssign(data);
// System.out.println("check9");
// log.addText("check8");
parseDelayAssign(data);
parseTransitionRate(data);
// parseIntAssign(data);
// System.out.println("check0");
// log.addText("check9");
parseBooleanAssign(data);
// System.out.println("check11");
// log.addText("check0");
// log.addText(intAssignments.toString());
}
catch (Exception e) {
e.printStackTrace();
throw new IllegalArgumentException("Unable to parse LHPN");
}
}
public void addPlace(String name, Boolean ic) {
places.put(name, ic);
}
public void removePlace(String name) {
if (name != null && places.containsKey(name)) {
places.remove(name);
}
}
public void addInput(String name, String ic) {
inputs.put(name, ic);
}
public void removeInput(String name) {
if (name != null && inputs.containsKey(name)) {
inputs.remove(name);
}
}
public void addOutput(String name, String ic) {
outputs.put(name, ic);
}
public void removeOutput(String name) {
if (name != null && outputs.containsKey(name)) {
outputs.remove(name);
}
}
// public void addFlow(String from, String to) {
// String name = "";
// Properties flow = new Properties();
// if (controlFlow.containsKey(from)) {
// name = from;
// flow = controlFlow.get(from);
// flow.setProperty(name + "to", flow.getProperty(name + "to") + to + " ");
// }
// else if (controlFlow.containsKey(to)) {
// name = to;
// flow = controlFlow.get(to);
// flow.setProperty(name + "from", flow.getProperty(name + "from") + to + "
// ");
// }
// controlFlow.put(name, flow);
// }
// public void removeFlow(String from, String to) {
// String name = "";
// Properties flow = new Properties();
// if (controlFlow.containsKey(from)) {
// name = from;
// flow = controlFlow.get(from);
// String toString = flow.getProperty("to");
// String[] toArray = toString.split("\\s");
// boolean flag = false;
// for (int i = 0; i < toArray.length; i++) {
// if (flag) {
// toArray[i - 1] = toArray[i];
// }
// if (toArray[i].equals(to)) {
// flag = true;
// }
// }
// flow.setProperty(name + "to", "");
// for (int i = 0; i < toArray.length - 1; i++) {
// flow.setProperty("to", flow.getProperty("to") + toArray[i] + " ");
// }
// }
// else if (controlFlow.containsKey(to)) {
// name = to;
// flow = controlFlow.get(to);
// String fromString = flow.getProperty("from");
// String[] fromArray = fromString.split("\\s");
// boolean flag = false;
// for (int i = 0; i < fromArray.length; i++) {
// if (flag) {
// fromArray[i - 1] = fromArray[i];
// }
// if (fromArray[i].equals(to)) {
// flag = true;
// }
// }
// flow.setProperty("from", "");
// for (int i = 0; i < fromArray.length - 1; i++) {
// flow.setProperty("from", flow.getProperty("from") + fromArray[i] + " ");
// }
// }
// }
public void addTransition(String name) {
controlFlow.put(name, null);
}
public void addTransition(String name, Properties prop) {
controlFlow.put(name, prop);
}
public void addControlFlow(String fromName, String toName) {
// log.addText(fromName+toName);
if (isTransition(fromName)) {
Properties prop = new Properties();
String list = "";
String placeList = "";
if (controlFlow.containsKey(fromName)) {
if (controlFlow.get(fromName) != null) {
prop = controlFlow.get(fromName);
list = prop.getProperty("to");
list = list + " " + toName;
}
}
else {
list = toName;
}
if (controlPlaces.containsKey(fromName)) {
if (controlPlaces.get(fromName) != null) {
prop = controlPlaces.get(fromName);
placeList = prop.getProperty("to");
placeList = placeList + " " + toName;
}
}
else {
placeList = toName;
}
// log.addText(list);
// System.out.println(prop == null);
prop.setProperty("to", list);
controlFlow.put(fromName, prop);
prop.setProperty("to", placeList);
controlPlaces.put(fromName, prop);
}
else {
Properties prop = new Properties();
String list = "";
String placeList = "";
if (controlFlow.containsKey(toName)) {
if (controlFlow.get(toName) != null) {
prop = controlFlow.get(toName);
list = prop.getProperty("from");
list = list + " " + fromName;
}
else {
list = fromName;
}
}
else {
list = fromName;
}
if (controlPlaces.containsKey(toName)) {
if (controlPlaces.get(toName) != null) {
prop = controlPlaces.get(toName);
placeList = prop.getProperty("from");
placeList = placeList + " " + fromName;
}
else {
placeList = fromName;
}
}
else {
placeList = fromName;
}
prop.setProperty("from", list);
controlFlow.put(toName, prop);
prop.setProperty("from", list);
controlPlaces.put(toName, prop);
}
}
public void removeControlFlow(String fromName, String toName) {
if (isTransition(fromName)) {
Properties prop = controlFlow.get(fromName);
String[] list = prop.getProperty("to").split("\\s");
String[] toList = new String[list.length - 1];
Boolean flag = false;
for (int i = 0; i < list.length - 1; i++) {
if (toName.equals(list[i])) {
flag = true;
}
else {
if (flag) {
toList[i - 1] = list[i];
}
else {
toList[i] = list[i];
}
}
}
if (toList.length > 0) {
prop.put("to", toList);
}
else {
prop.remove("to");
}
controlFlow.put(fromName, prop);
prop = controlPlaces.get(toName);
list = prop.getProperty("from").split("\\s");
String[] fromList = new String[list.length - 1];
flag = false;
for (int i = 0; i < list.length - 1; i++) {
if (toName.equals(list[i])) {
flag = true;
}
else {
if (flag) {
fromList[i - 1] = list[i];
}
else {
fromList[i] = list[i];
}
}
}
if (fromList.length > 0) {
prop.put("from", fromList);
}
else {
prop.remove("from");
}
controlPlaces.put(toName, prop);
}
else {
Properties prop = controlFlow.get(toName);
String[] list = prop.getProperty("from").split("\\s");
String[] fromList = new String[list.length - 1];
Boolean flag = false;
for (int i = 0; i < list.length - 1; i++) {
if (toName.equals(list[i])) {
flag = true;
}
else {
if (flag) {
fromList[i - 1] = list[i];
}
else {
fromList[i] = list[i];
}
}
}
if (fromList.length > 0) {
prop.put("from", fromList);
}
else {
prop.remove("from");
}
controlPlaces.put(toName, prop);
prop = controlPlaces.get(fromName);
list = prop.getProperty("to").split("\\s");
String[] toList = new String[list.length - 1];
flag = false;
for (int i = 0; i < list.length - 1; i++) {
if (toName.equals(list[i])) {
flag = true;
}
else {
if (flag) {
toList[i - 1] = list[i];
}
else {
toList[i] = list[i];
}
}
}
if (toList.length > 0) {
prop.put("to", toList);
}
else {
prop.remove("to");
}
controlPlaces.put(fromName, prop);
}
}
public boolean containsFlow(String fromName, String toName) {
if (isTransition(fromName)) {
Properties prop = controlFlow.get(fromName);
if (prop != null) {
if (prop.getProperty("to") != null) {
String[] list = prop.getProperty("to").split("\\s");
for (int i = 0; i < list.length; i++) {
if (list[i].equals(toName)) {
return true;
}
}
}
}
return false;
}
else {
Properties prop = controlFlow.get(toName);
if (prop != null) {
if (prop.getProperty("from") != null) {
String[] list = prop.getProperty("from").split("\\s");
for (int i = 0; i < list.length; i++) {
if (list[i].equals(fromName)) {
return true;
}
}
}
}
return false;
}
}
public boolean containsFlow(String place) {
if (controlFlow.containsKey(place) && controlFlow.get(place) != null) {
if (!controlFlow.get(place).isEmpty()) {
return true;
}
}
for (String s : controlFlow.keySet()) {
if (controlFlow.get(s) != null) {
Properties prop = controlFlow.get(s);
if (prop.containsKey("to")) {
String[] toList = prop.get("to").toString().split(" ");
for (int i = 0; i < toList.length; i++) {
if (toList[i].equals(place)) {
return true;
}
}
}
if (prop.containsKey("from")) {
String[] fromList = prop.get("from").toString().split(" ");
for (int i = 0; i < fromList.length; i++) {
if (fromList[i].equals(place)) {
return true;
}
}
}
}
}
return false;
}
public void addTransition(String name, String delay, String transitionRate,
Properties rateAssign, Properties booleanAssign, String enabling) {
addTransition(name);
delays.put(name, delay);
transitionRates.put(name, transitionRate);
rateAssignments.put(name, rateAssign);
booleanAssignments.put(name, booleanAssign);
enablings.put(name, enabling);
}
public void removeTransition(String name) {
controlFlow.remove(name);
delays.remove(name);
transitionRates.remove(name);
rateAssignments.remove(name);
booleanAssignments.remove(name);
enablings.remove(name);
}
public void addEnabling(String name, String cond) {
enablings.put(name, cond);
}
public void removeEnabling(String name) {
if (name != null && enablings.containsKey(name)) {
enablings.remove(name);
}
}
public void addVar(String name, Properties initCond) {
variables.put(name, initCond);
}
public int removeVar(String name) {
int flag = 0;
for (String s : booleanAssignments.keySet()) {
Properties prop = booleanAssignments.get(s);
for (Object object : prop.keySet()) {
String propName = object.toString();
if (propName.equals(name)) {
flag = 1;
}
}
}
for (String s : contAssignments.keySet()) {
Properties prop = contAssignments.get(s);
for (Object object : prop.keySet()) {
String propName = object.toString();
if (propName.equals(name)) {
flag = 1;
}
}
}
for (String s : rateAssignments.keySet()) {
Properties prop = rateAssignments.get(s);
for (Object object : prop.keySet()) {
String propName = object.toString();
if (propName.equals(name)) {
flag = 1;
}
}
}
for (String s : integers.keySet()) {
Properties prop = intAssignments.get(s);
if (prop != null) {
for (Object object : prop.keySet()) {
String propName = object.toString();
if (propName.equals(name)) {
flag = 1;
}
}
}
}
if (flag == 0 && name != null && variables.containsKey(name)) {
variables.remove(name);
}
else if (flag == 0 && name != null && inputs.containsKey(name)) {
inputs.remove(name);
}
else if (flag == 0 && name != null && outputs.containsKey(name)) {
outputs.remove(name);
}
else if (flag == 0 && name != null && integers.containsKey(name)) {
integers.remove(name);
}
return flag;
}
public void addInteger(String name, String ic) {
integers.put(name, ic);
}
public void addRateAssign(String transition, String name, String value) {
Properties prop = new Properties();
if (rateAssignments.get(transition) != null) {
prop = rateAssignments.get(transition);
}
prop.setProperty(name, value);
rateAssignments.put(transition, prop);
}
public void removeRateAssign(String transition, String name) {
if (rateAssignments.containsKey(transition)) {
Properties prop = rateAssignments.get(transition);
if (name != null && prop.containsKey(name)) {
prop.remove(name);
}
rateAssignments.put(transition, prop);
}
}
public void addBoolAssign(String transition, String name, String value) {
Properties prop = new Properties();
if (booleanAssignments.get(transition) != null) {
prop = booleanAssignments.get(transition);
}
prop.setProperty(name, value);
booleanAssignments.put(transition, prop);
}
public void removeBoolAssign(String transition, String name) {
Properties prop = booleanAssignments.get(transition);
if (name != null && prop.containsKey(name)) {
prop.remove(name);
}
booleanAssignments.put(transition, prop);
}
public void addContAssign(String transition, String name, String value) {
Properties prop = new Properties();
if (contAssignments.get(transition) != null) {
prop = contAssignments.get(transition);
}
// System.out.println("here " + transition + name + value);
prop.setProperty(name, value);
// log.addText("lhpn " + prop.toString());
contAssignments.put(transition, prop);
}
public void removeContAssign(String transition, String name) {
if (contAssignments.containsKey(transition)) {
Properties prop = contAssignments.get(transition);
if (name != null && prop.containsKey(name)) {
prop.remove(name);
}
// log.addText("lhpn " + prop.toString());
contAssignments.put(transition, prop);
}
}
public void addIntAssign(String transition, String name, String value) {
Properties prop = new Properties();
if (intAssignments.get(transition) != null) {
prop = intAssignments.get(transition);
}
// System.out.println("here " + transition + name + value);
prop.setProperty(name, value);
intAssignments.put(transition, prop);
}
public void removeIntAssign(String transition, String name) {
if (intAssignments.containsKey(transition)) {
Properties prop = intAssignments.get(transition);
if (name != null && prop.containsKey(name)) {
prop.remove(name);
}
intAssignments.put(transition, prop);
}
}
public void removeAllAssign(String transition) {
if (booleanAssignments.containsKey(transition)) {
Properties prop = new Properties();
booleanAssignments.put(transition, prop);
}
if (contAssignments.containsKey(transition)) {
Properties prop = new Properties();
contAssignments.put(transition, prop);
}
if (rateAssignments.containsKey(transition)) {
Properties prop = new Properties();
rateAssignments.put(transition, prop);
}
if (intAssignments.containsKey(transition)) {
Properties prop = new Properties();
intAssignments.put(transition, prop);
}
}
public void addProperty(String newProperty) {
property = newProperty;
}
public void removeProperty() {
property = "";
}
public String getProperty() {
return property;
}
public void changeVariableName(String oldName, String newName) {
if (isContinuous(oldName)) {
variables.put(newName, variables.get(oldName));
variables.remove(oldName);
}
else if (isInput(oldName)) {
inputs.put(newName, inputs.get(oldName));
inputs.remove(oldName);
}
else if (isInteger(oldName)) {
integers.put(newName, integers.get(oldName));
integers.remove(oldName);
}
else {
outputs.put(newName, outputs.get(oldName));
outputs.remove(oldName);
}
}
public void changeTransitionName(String oldName, String newName) {
controlFlow.put(newName, controlFlow.get(oldName));
controlFlow.remove(oldName);
delays.put(newName, delays.get(oldName));
delays.remove(oldName);
transitionRates.put(newName, transitionRates.get(oldName));
transitionRates.remove(oldName);
rateAssignments.put(newName, rateAssignments.get(oldName));
rateAssignments.remove(oldName);
booleanAssignments.put(newName, booleanAssignments.get(oldName));
booleanAssignments.remove(oldName);
enablings.put(newName, enablings.get(oldName));
enablings.remove(oldName);
}
public void changeDelay(String transition, String delay) {
if (delays.containsKey(transition)) {
delays.remove(transition);
}
// log.addText(transition + delay);
delays.put(transition, delay);
}
public void changeTransitionRate(String transition, String rate) {
if (transitionRates.containsKey(transition)) {
transitionRates.remove(transition);
}
// log.addText(transition + delay);
transitionRates.put(transition, rate);
}
public void changeEnabling(String transition, String enabling) {
if (enablings.containsKey(transition)) {
enablings.remove(transition);
}
enablings.put(transition, enabling);
}
public String[] getAllIDs() {
String[] allVariables = new String[variables.size() + integers.size() + inputs.size()
+ outputs.size() + delays.size() + places.size()];
int i = 0;
for (String s : variables.keySet()) {
allVariables[i] = s;
i++;
}
for (String s : integers.keySet()) {
allVariables[i] = s;
i++;
}
for (String s : inputs.keySet()) {
allVariables[i] = s;
i++;
}
for (String s : outputs.keySet()) {
allVariables[i] = s;
i++;
}
for (String s : delays.keySet()) {
allVariables[i] = s;
i++;
}
for (String s : places.keySet()) {
allVariables[i] = s;
i++;
}
return allVariables;
}
public HashMap<String, Properties> getVariables() {
return variables;
}
public HashMap<String, String> getIntegers() {
return integers;
}
public HashMap<String, String> getInputs() {
return inputs;
}
public HashMap<String, String> getOutputs() {
return outputs;
}
public HashMap<String, Boolean> getPlaces() {
return places;
}
public HashMap<String, String> getDelays() {
return delays;
}
public String getDelay(String var) {
return delays.get(var);
}
public HashMap<String, String> getTransitionRates() {
return transitionRates;
}
public String getTransitionRate(String var) {
return transitionRates.get(var);
}
public String[] getControlFlow() {
String retString = "";
for (String s : controlFlow.keySet()) {
// log.addText("key: " + s);
Properties prop = controlFlow.get(s);
String toString = prop.getProperty("to");
// log.addText("toString " + toString);
if (toString != null) {
String[] toArray = toString.split("\\s");
for (int i = 0; i < toArray.length; i++) {
retString = retString + s + " " + toArray[i] + "\n";
}
}
// log.addText("getfrom");
String fromString = prop.getProperty("from");
if (fromString != null) {
// log.addText("fromString " + fromString);
String[] fromArray = fromString.split("\\s");
for (int i = 0; i < fromArray.length; i++) {
retString = retString + fromArray[i] + " " + s + "\n";
}
}
}
return retString.split("\\n");
}
public String getInitialVal(String var) {
if (isContinuous(var)) {
Properties prop = variables.get(var);
return prop.getProperty("value");
}
else if (isInteger(var)) {
String integer = integers.get(var);
return integer;
}
else if (isInput(var)) {
return inputs.get(var);
}
else if (isOutput(var)) {
return outputs.get(var);
}
else {
return "";
}
}
public boolean getPlaceInitial(String var) {
return places.get(var);
}
public String getInitialRate(String var) {
Properties prop = variables.get(var);
return prop.getProperty("rate");
}
public String getEnabling(String var) {
return enablings.get(var);
}
public String[] getBooleanVars(String trans) {
if (booleanAssignments.containsKey(trans)) {
Properties prop = booleanAssignments.get(trans);
String[] assignArray = new String[prop.size()];
int i = 0;
for (Object s : prop.keySet()) {
if (prop.get(s) != null) {
if (isInput(s.toString()) || isOutput(s.toString())) {
assignArray[i] = s.toString();
i++;
}
}
}
return assignArray;
}
return null;
}
public String[] getBooleanVars() {
Object[] inArray = inputs.keySet().toArray();
Object[] outArray = outputs.keySet().toArray();
String[] vars = new String[inArray.length + outArray.length];
int i;
for (i = 0; i < inArray.length; i++) {
vars[i] = inArray[i].toString();
}
for (int j = 0; j < outArray.length; j++) {
vars[i] = outArray[j].toString();
i++;
}
return vars;
}
public String[] getContVars() {
if (!variables.isEmpty()) {
Object[] objArray = variables.keySet().toArray();
String[] vars = new String[objArray.length];
for (int i = 0; i < objArray.length; i++) {
vars[i] = objArray[i].toString();
}
return vars;
}
else {
return new String[0];
}
}
public Properties getContVars(String trans) {
Properties contVars = new Properties();
contVars = contAssignments.get(trans);
// log.addText("lhpn " + contVars.toString());
return contVars;
}
public String[] getIntVars() {
if (!integers.isEmpty()) {
Object[] objArray = integers.keySet().toArray();
String[] vars = new String[objArray.length];
for (int i = 0; i < objArray.length; i++) {
vars[i] = objArray[i].toString();
}
return vars;
}
else {
return new String[0];
}
}
public Properties getIntVars(String trans) {
// log.addText(trans);
Properties intVars = new Properties();
intVars = intAssignments.get(trans);
if (intVars != null) {
String[] tempArray = new String[intVars.keySet().size()];
int i = 0;
for (Object s : intVars.keySet()) {
String t = (String) s;
if (!isInteger(t)) {
tempArray[i] = t;
i++;
}
}
for (i = 0; i < tempArray.length; i++) {
if (tempArray[i] != null) {
intVars.remove(tempArray[i]);
}
else {
break;
}
}
return intVars;
}
return null;
}
public String[] getContAssignVars(String trans) {
// log.addText(trans);
if (contAssignments.containsKey(trans)) {
Properties prop = contAssignments.get(trans);
String[] assignArray = new String[prop.size()];
int i = 0;
for (Object s : prop.keySet()) {
if (isContinuous(s.toString())) {
assignArray[i] = s.toString();
i++;
}
}
// Properties prop = booleanAssignments.get(var);
// prop.setProperty("type", "boolean");
return assignArray;
}
else {
// log.addText("returning null");
return null;
}
}
public String[] getRateVars(String trans) {
if (rateAssignments.containsKey(trans)) {
Properties prop = rateAssignments.get(trans);
String[] assignArray = new String[prop.size()];
int i = 0;
for (Object s : prop.keySet()) {
if (isContinuous(s.toString())) {
assignArray[i] = s.toString();
i++;
}
}
// Properties prop = booleanAssignments.get(var);
// prop.setProperty("type", "boolean");
return assignArray;
}
return null;
}
public String getBoolAssign(String trans, String var) {
if (booleanAssignments.containsKey(trans)) {
Properties prop = booleanAssignments.get(trans);
if (prop != null && var != null) {
if (prop.containsKey(var)) {
return prop.getProperty(var);
}
}
}
return null;
}
public String getContAssign(String transition, String var) {
if (contAssignments.containsKey(transition) && var != null) {
Properties prop = contAssignments.get(transition);
// log.addText("lhpn " + prop.toString());
if (prop.containsKey(var)) {
return prop.getProperty(var);
}
}
return null;
}
public String getIntAssign(String transition, String var) {
if (intAssignments.containsKey(transition) && var != null) {
Properties prop = intAssignments.get(transition);
if (prop.containsKey(var)) {
return prop.getProperty(var);
}
}
return null;
}
public String getRateAssign(String transition, String var) {
Properties prop = rateAssignments.get(transition);
if (prop != null && var != null) {
return prop.getProperty(var);
}
return "";
}
public String[] getPlaceList() {
String[] placeList = new String[places.keySet().size()];
int i = 0;
for (String s : places.keySet()) {
placeList[i] = s;
i++;
}
return placeList;
}
public String[] getTransitionList() {
String[] transitionList = new String[controlFlow.keySet().size()];
int i = 0;
for (String s : controlFlow.keySet()) {
transitionList[i] = s;
i++;
}
return transitionList;
}
public boolean isContinuous(String var) {
return variables.containsKey(var);
}
public boolean isInput(String var) {
return inputs.containsKey(var);
}
public boolean isOutput(String var) {
return outputs.containsKey(var);
}
public boolean isInteger(String var) {
return integers.containsKey(var);
}
public boolean isTransition(String var) {
for (String s : controlFlow.keySet()) {
if (var.equals(s)) {
return true;
}
}
return false;
}
/*
* private void parseTransitions(StringBuffer data) { Pattern pattern =
* Pattern.compile(TRANSITION); Matcher line_matcher =
* pattern.matcher(data.toString()); Pattern output = Pattern.compile(WORD);
* Matcher matcher = output.matcher(line_matcher.group()); while
* (line_matcher.find()) { String name = matcher.group();
* controlFlow.put(name, name); } }
*/
private void parseProperty(StringBuffer data) {
Pattern pattern = Pattern.compile(PROPERTY);
Matcher lineMatcher = pattern.matcher(data.toString());
if (lineMatcher.find()) {
property = lineMatcher.group(1);
}
}
private void parseControlFlow(StringBuffer data) {
// log.addText("check2start");
Pattern pattern = Pattern.compile(TRANSITION);
Matcher lineMatcher = pattern.matcher(data.toString());
if (lineMatcher.find()) {
lineMatcher.group(1);
// log.addText("check2a-");
String name = lineMatcher.group(1).replaceAll("\\+/", "P");
name = name.replaceAll("-/", "M");
// log.addText("check2a+");
Pattern transPattern = Pattern.compile(WORD);
Matcher transMatcher = transPattern.matcher(name);
// log.addText("check2a");
while (transMatcher.find()) {
controlFlow.put(transMatcher.group(), new Properties());
}
Pattern placePattern = Pattern.compile(PLACE);
Matcher placeMatcher = placePattern.matcher(data.toString());
// log.addText("check2b");
while (placeMatcher.find()) {
// log.addText("check2 while");
String temp = placeMatcher.group(1).replaceAll("\\+", "P");
temp = temp.replaceAll("-", "M");
// String[] tempLine = tempString.split("#");
String[] tempPlace = temp.split("\\s");
// String trans = "";
if (controlFlow.containsKey(tempPlace[0])) {
// log.addText("check2 if");
Properties tempProp = new Properties();
if (controlFlow.get(tempPlace[0]) != null) {
tempProp = controlFlow.get(tempPlace[0]);
}
String tempString;
if (tempProp.containsKey("to")) {
tempString = tempProp.getProperty("to");
tempString = tempString + " " + tempPlace[1];
}
else {
tempString = tempPlace[1];
}
tempProp.setProperty("to", tempString);
controlFlow.put(tempPlace[0], tempProp);
places.put(tempPlace[1], false);
controlPlaces.put(tempPlace[0], new Properties());
// trans = tempPlace[0];
}
else if (controlFlow.containsKey(tempPlace[1])) {
Properties tempProp = controlFlow.get(tempPlace[1]);
// log.addText("check2c");
String tempString;
// Boolean temp = tempProp.containsKey("from");
// log.addText("check2c1");
// log.addText(temp.toString());
if (tempProp.containsKey("from")) {
// log.addText("check2a if");
tempString = tempProp.getProperty("from");
// log.addText("check2a if1");
tempString = tempString + " " + tempPlace[0];
}
else {
// log.addText("check2a else");
tempString = tempPlace[0];
}
// log.addText("check2d");
// log.addText("check2d1");
tempProp.setProperty("from", tempString);
// log.addText("check2e");
controlFlow.put(tempPlace[1], tempProp);
places.put(tempPlace[0], false);
controlPlaces.put(tempPlace[0], new Properties());
// trans = tempPlace[1];
}
if (controlPlaces.containsKey(tempPlace[0])) {
// log.addText("check2 if");
Properties tempProp = new Properties();
if (controlPlaces.get(tempPlace[0]) != null) {
tempProp = controlPlaces.get(tempPlace[0]);
}
String tempString;
if (tempProp.containsKey("to")) {
tempString = tempProp.getProperty("to");
tempString = tempString + " " + tempPlace[1];
}
else {
tempString = tempPlace[1];
}
tempProp.setProperty("to", tempString);
controlPlaces.put(tempPlace[0], tempProp);
// trans = tempPlace[0];
}
else if (controlPlaces.containsKey(tempPlace[1])) {
Properties tempProp = controlPlaces.get(tempPlace[1]);
// log.addText("check2c");
String tempString;
// Boolean temp = tempProp.containsKey("from");
// log.addText("check2c1");
// log.addText(temp.toString());
if (tempProp.containsKey("from")) {
// log.addText("check2a if");
tempString = tempProp.getProperty("from");
// log.addText("check2a if1");
tempString = tempString + " " + tempPlace[0];
}
else {
// log.addText("check2a else");
tempString = tempPlace[0];
}
// log.addText("check2d");
// log.addText("check2d1");
tempProp.setProperty("from", tempString);
// log.addText("check2e");
controlPlaces.put(tempPlace[1], tempProp);
// trans = tempPlace[1];
}
}
}
// for (String s : controlFlow.keySet()) {
// log.addText(s + " " + controlFlow.get(s));
// }
// log.addText("check2end");
}
private void parseInOut(StringBuffer data) {
// System.out.println("hello?");
Properties varOrder = new Properties();
// System.out.println("check1start");
// log.addText("check1start");
Pattern inLinePattern = Pattern.compile(INPUT);
Matcher inLineMatcher = inLinePattern.matcher(data.toString());
Integer i = 0;
Integer inLength = 0;
// System.out.println("check1a-");
if (inLineMatcher.find()) {
// System.out.println("checkifin");
Pattern inPattern = Pattern.compile(WORD);
Matcher inMatcher = inPattern.matcher(inLineMatcher.group(1));
while (inMatcher.find()) {
varOrder.setProperty(i.toString(), inMatcher.group());
i++;
inLength++;
}
}
// System.out.println("check1a");
Pattern outPattern = Pattern.compile(OUTPUT);
Matcher outLineMatcher = outPattern.matcher(data.toString());
if (outLineMatcher.find()) {
// log.addText("outline " + outLineMatcher.group(1));
// log.addText("check1b");
Pattern output = Pattern.compile(WORD);
Matcher outMatcher = output.matcher(outLineMatcher.group(1));
while (outMatcher.find()) {
varOrder.setProperty(i.toString(), outMatcher.group());
i++;
}
}
// System.out.println("check1e");
// log.addText("check1c");
Pattern initState = Pattern.compile(INIT_STATE);
Matcher initMatcher = initState.matcher(data.toString());
if (initMatcher.find()) {
// log.addText("check1d");
Pattern initDigit = Pattern.compile("\\d+");
Matcher digitMatcher = initDigit.matcher(initMatcher.group());
digitMatcher.find();
// log.addText("check1e");
String[] initArray = new String[digitMatcher.group().length()];
Pattern bit = Pattern.compile("[01]");
Matcher bitMatcher = bit.matcher(digitMatcher.group());
// log.addText("check1f");
i = 0;
while (bitMatcher.find()) {
initArray[i] = bitMatcher.group();
i++;
}
for (i = 0; i < inLength; i++) {
String name = varOrder.getProperty(i.toString());
if (initArray[i].equals("1")) {
inputs.put(name, "true");
}
else if (initArray[i].equals("0")) {
inputs.put(name, "false");
}
else {
inputs.put(name, "unknown");
}
}
// log.addText("check1f");
for (i = inLength; i < initArray.length; i++) {
String name = varOrder.getProperty(i.toString());
if (initArray[i].equals("1") && name != null) {
outputs.put(name, "true");
}
else if (initArray[i].equals("0") && name != null) {
outputs.put(name, "false");
}
else {
outputs.put(name, "unknown");
}
}
}
}
private void parseVars(StringBuffer data) {
// log.addText("check3 start");
// System.out.println("check3 start");
Properties initCond = new Properties();
Properties initValue = new Properties();
Properties initRate = new Properties();
// log.addText("check3a");
// System.out.println("check3a");
Pattern linePattern = Pattern.compile(CONTINUOUS);
Matcher lineMatcher = linePattern.matcher(data.toString());
if (lineMatcher.find()) {
// log.addText("check3b");
// System.out.println("check3b");
Pattern varPattern = Pattern.compile(WORD);
Matcher varMatcher = varPattern.matcher(lineMatcher.group(1));
// log.addText("check3c");
// System.out.println("check3c");
while (varMatcher.find()) {
variables.put(varMatcher.group(), initCond);
}
// log.addText("check3d " + VARS_INIT);
// System.out.println("check3c");
Pattern initLinePattern = Pattern.compile(VARS_INIT);
// log.addText("check3d1");
// System.out.println("check3d");
Matcher initLineMatcher = initLinePattern.matcher(data.toString());
// log.addText("check3d2");
// System.out.println("check3e");
initLineMatcher.find();
// log.addText("check3e");
// System.out.println("check3f");
Pattern initPattern = Pattern.compile(INIT_COND);
Matcher initMatcher = initPattern.matcher(initLineMatcher.group(1));
// log.addText("check3f");
// System.out.println("check3g");
while (initMatcher.find()) {
if (variables.containsKey(initMatcher.group(1))) {
initValue.put(initMatcher.group(1), initMatcher.group(2));
}
}
// log.addText("check3g");
// System.out.println("check3h");
Pattern rateLinePattern = Pattern.compile(INIT_RATE);
Matcher rateLineMatcher = rateLinePattern.matcher(data.toString());
if (rateLineMatcher.find()) {
// log.addText("check3h");
// System.out.println("check3i");
Pattern ratePattern = Pattern.compile(INIT_COND);
Matcher rateMatcher = ratePattern.matcher(rateLineMatcher.group(1));
// log.addText("check3i");
// System.out.println("check3j");
while (rateMatcher.find()) {
// log.addText(rateMatcher.group(1) + "value" +
// rateMatcher.group(2));
initRate.put(rateMatcher.group(1), rateMatcher.group(2));
}
}
// log.addText("check3j");
// System.out.println("check3k");
for (String s : variables.keySet()) {
// log.addText("check3for" + s);
// System.out.println("check3for " + s);
initCond.put("value", initValue.get(s));
initCond.put("rate", initRate.get(s));
// log.addText("check3for" + initCond.toString());
// System.out.println("check3for " + initCond.toString());
variables.put(s, initCond);
}
}
// log.addText("check3end");
// System.out.println("check3end");
}
private void parseIntegers(StringBuffer data) {
// log.addText("check3 start");
String initCond = "0";
Properties initValue = new Properties();
// log.addText("check3a");
Pattern linePattern = Pattern.compile(VARIABLES);
Matcher lineMatcher = linePattern.matcher(data.toString());
// log.addText("check3b");
if (lineMatcher.find()) {
Pattern varPattern = Pattern.compile(WORD);
Matcher varMatcher = varPattern.matcher(lineMatcher.group(1));
// log.addText("check3c");
while (varMatcher.find()) {
if (!variables.containsKey(varMatcher.group())) {
integers.put(varMatcher.group(), initCond);
}
}
// log.addText("check3d " + VARS_INIT);
Pattern initLinePattern = Pattern.compile(VARS_INIT);
// log.addText("check3d1");
Matcher initLineMatcher = initLinePattern.matcher(data.toString());
// log.addText("check3d2");
if (initLineMatcher.find()) {
// log.addText("check3e");
Pattern initPattern = Pattern.compile(INIT_COND);
Matcher initMatcher = initPattern.matcher(initLineMatcher.group(1));
// log.addText("check3f");
while (initMatcher.find()) {
if (integers.containsKey(initMatcher.group(1))) {
initValue.put(initMatcher.group(1), initMatcher.group(2));
}
}
}
// log.addText("check3g");
// log.addText("check3i");
// log.addText("check3j");
for (String s : integers.keySet()) {
// log.addText("check3for" + s);
if (initValue.get(s) != null) {
initCond = initValue.get(s).toString();
}
// log.addText("check3for" + initCond);
integers.put(s, initCond);
}
}
// log.addText("check3end");
}
private void parsePlaces(StringBuffer data) {
Pattern linePattern = Pattern.compile(PLACES_LINE);
Matcher lineMatcher = linePattern.matcher(data.toString());
if (lineMatcher.find()) {
// log.addText(lineMatcher.group());
Pattern markPattern = Pattern.compile(MARKING);
Matcher markMatcher = markPattern.matcher(lineMatcher.group(1));
while (markMatcher.find()) {
places.put(markMatcher.group(), false);
}
}
}
private void parseMarking(StringBuffer data) {
// log.addText("check4start");
Pattern linePattern = Pattern.compile(MARKING_LINE);
Matcher lineMatcher = linePattern.matcher(data.toString());
if (lineMatcher.find()) {
// log.addText("check4a");
Pattern markPattern = Pattern.compile(MARKING);
Matcher markMatcher = markPattern.matcher(lineMatcher.group(1));
// log.addText("check4b");
while (markMatcher.find()) {
// log.addText("check4loop");
places.put(markMatcher.group(), true);
}
}
// log.addText("check4end");
}
private void parseEnabling(StringBuffer data) {
Pattern linePattern = Pattern.compile(ENABLING_LINE);
Matcher lineMatcher = linePattern.matcher(data.toString());
if (lineMatcher.find()) {
Pattern enabPattern = Pattern.compile(ENABLING);
Matcher enabMatcher = enabPattern.matcher(lineMatcher.group(1));
while (enabMatcher.find()) {
enablings.put(enabMatcher.group(2), enabMatcher.group(4));
// log.addText(enabMatcher.group(2) + enabMatcher.group(4));
}
}
}
private void parseAssign(StringBuffer data) {
// log.addText("check6start");
Pattern linePattern = Pattern.compile(ASSIGNMENT_LINE);
Matcher lineMatcher = linePattern.matcher(data.toString());
// Boolean temp = lineMatcher.find();
// log.addText(temp.toString());
// log.addText("check6a");
if (lineMatcher.find()) {
Pattern assignPattern = Pattern.compile(ASSIGNMENT);
// log.addText("check6a1.0");
// log.addText("check6a1 " + lineMatcher.group());
Matcher assignMatcher = assignPattern.matcher(lineMatcher.group(1));
Pattern varPattern = Pattern.compile(ASSIGN_VAR);
Pattern indetPattern = Pattern.compile(INDET_ASSIGN_VAR);
Matcher varMatcher;
// log.addText("check6ab");
while (assignMatcher.find()) {
Properties assignProp = new Properties();
Properties intProp = new Properties();
// log.addText("check6while1");
varMatcher = varPattern.matcher(assignMatcher.group(2));
if (!varMatcher.find()) {
varMatcher = indetPattern.matcher(assignMatcher.group(2));
}
else {
// log.addText("check6 else");
if (isInteger(varMatcher.group(1))) {
intProp.put(varMatcher.group(1), varMatcher.group(2));
}
else {
assignProp.put(varMatcher.group(1), varMatcher.group(2));
}
}
while (varMatcher.find()) {
// log.addText("check6while2");
if (isInteger(varMatcher.group(1))) {
intProp.put(varMatcher.group(1), varMatcher.group(2));
}
else {
assignProp.put(varMatcher.group(1), varMatcher.group(2));
}
}
if (intProp.size() > 0) {
intAssignments.put(assignMatcher.group(1), intProp);
}
if (assignProp.size() > 0) {
contAssignments.put(assignMatcher.group(1), assignProp);
}
}
}
// log.addText("check6end");
}
private void parseRateAssign(StringBuffer data) {
Pattern linePattern = Pattern.compile(RATE_ASSIGNMENT_LINE);
Matcher lineMatcher = linePattern.matcher(data.toString());
if (lineMatcher.find()) {
Pattern assignPattern = Pattern.compile(ASSIGNMENT);
Matcher assignMatcher = assignPattern.matcher(lineMatcher.group(1));
Pattern varPattern = Pattern.compile(ASSIGN_VAR);
Pattern indetPattern = Pattern.compile(INDET_ASSIGN_VAR);
Matcher varMatcher;
Matcher indetMatcher;
while (assignMatcher.find()) {
Properties assignProp = new Properties();
if (rateAssignments.containsKey(assignMatcher.group(1))) {
assignProp = rateAssignments.get(assignMatcher.group(1));
}
// log.addText("here " + assignMatcher.group(2));
varMatcher = varPattern.matcher(assignMatcher.group(2));
// log.addText(assignMatcher.group(2) + " " + indetPattern);
while (varMatcher.find()) {
if (!assignProp.containsKey(varMatcher.group(1))) {
assignProp.put(varMatcher.group(1), varMatcher.group(2));
}
// log.addText("rate " + varMatcher.group(1) + ":=" +
// varMatcher.group(2));
}
indetMatcher = indetPattern.matcher(assignMatcher.group(2));
while (indetMatcher.find()) {
assignProp.put(indetMatcher.group(1), indetMatcher.group(2));
// log.addText("indet " + indetMatcher.group(1) + ":=" +
// indetMatcher.group(2));
}
// log.addText("rates for " + assignMatcher.group(1));
// for (Object o : assignProp.keySet()) {
// log.addText((String)o + " " +
// assignProp.getProperty((String)o));
// }
rateAssignments.put(assignMatcher.group(1), assignProp);
}
}
// for (String s: rateAssignments.keySet()) {
// log.addText(s + " " + rateAssignments.get(s));
// }
}
private void parseDelayAssign(StringBuffer data) {
// log.addText("check8start");
Pattern linePattern = Pattern.compile(DELAY_LINE);
Matcher lineMatcher = linePattern.matcher(data.toString());
if (lineMatcher.find()) {
// log.addText("check8a");
Pattern delayPattern = Pattern.compile(DELAY);
Matcher delayMatcher = delayPattern.matcher(lineMatcher.group(1));
// log.addText("check8b");
while (delayMatcher.find()) {
// log.addText("check8while");
delays.put(delayMatcher.group(1), delayMatcher.group(2));
}
}
// log.addText("check8end");
}
private void parseTransitionRate(StringBuffer data) {
// log.addText("check8start");
Pattern linePattern = Pattern.compile(TRANS_RATE_LINE);
Matcher lineMatcher = linePattern.matcher(data.toString());
if (lineMatcher.find()) {
// log.addText("check8a");
Pattern delayPattern = Pattern.compile(DELAY);
Matcher delayMatcher = delayPattern.matcher(lineMatcher.group(1));
// log.addText("check8b");
while (delayMatcher.find()) {
// log.addText("check8while");
transitionRates.put(delayMatcher.group(1), delayMatcher.group(2));
}
}
// log.addText("check8end");
}
private void parseBooleanAssign(StringBuffer data) {
Pattern linePattern = Pattern.compile(BOOLEAN_LINE);
Matcher lineMatcher = linePattern.matcher(data.toString());
if (lineMatcher.find()) {
Pattern transPattern = Pattern.compile(BOOLEAN_TRANS);
Matcher transMatcher = transPattern.matcher(lineMatcher.group(1));
Pattern assignPattern = Pattern.compile(BOOLEAN_ASSIGN);
while (transMatcher.find()) {
Properties prop = new Properties();
Matcher assignMatcher = assignPattern.matcher(transMatcher.group(2));
while (assignMatcher.find()) {
prop.put(assignMatcher.group(1), assignMatcher.group(2));
}
booleanAssignments.put(transMatcher.group(1), prop);
}
}
}
private void parseIntAssign(StringBuffer data) {
// log.addText("check6start");
Properties assignProp = new Properties();
Pattern linePattern = Pattern.compile(ASSIGNMENT_LINE);
Matcher lineMatcher = linePattern.matcher(data.toString());
// Boolean temp = lineMatcher.find();
// log.addText(temp.toString());
// log.addText("check6a");
if (lineMatcher.find()) {
Pattern assignPattern = Pattern.compile(ASSIGNMENT);
// log.addText("check6a1.0");
// log.addText("check6a1 " + lineMatcher.group());
Matcher assignMatcher = assignPattern.matcher(lineMatcher.group(1));
Pattern varPattern = Pattern.compile(ASSIGN_VAR);
Pattern indetPattern = Pattern.compile(INDET_ASSIGN_VAR);
Matcher varMatcher;
// log.addText("check6ab");
while (assignMatcher.find()) {
// log.addText("check6while1");
varMatcher = varPattern.matcher(assignMatcher.group(2));
if (!varMatcher.find()) {
varMatcher = indetPattern.matcher(assignMatcher.group(2));
}
else {
varMatcher = varPattern.matcher(assignMatcher.group(2));
}
// log.addText(varMatcher.toString());
while (varMatcher.find()) {
// log.addText("check6while2");
assignProp.put(varMatcher.group(1), varMatcher.group(2));
}
// log.addText(assignMatcher.group(1) + assignProp.toString());
intAssignments.put(assignMatcher.group(1), assignProp);
}
}
// log.addText("check6end");
}
private static final String PROPERTY = "#@\\.property (\\S+?)\\n";
private static final String INPUT = "\\.inputs([[\\s[^\\n]]\\w+]*?)\\n";
private static final String OUTPUT = "\\.outputs([[\\s[^\\n]]\\w+]*?)\\n";
private static final String INIT_STATE = "#@\\.init_state \\[(\\d+)\\]";
private static final String TRANSITION = "\\.dummy([^\\n]*?)\\n";
private static final String PLACE = "\\n([\\w_\\+-/&&[^\\.#]]+ [\\w_\\+-/]+)";
private static final String CONTINUOUS = "#@\\.continuous ([.[^\\n]]+)\\n";
private static final String VARIABLES = "#@\\.variables ([.[^\\n]]+)\\n";
private static final String VARS_INIT = "#@\\.init_vals \\{([\\S[^\\}]]+?)\\}";
private static final String INIT_RATE = "#@\\.init_rates \\{([\\S[^\\}]]+?)\\}";
private static final String INIT_COND = "<(\\w+)=([\\S^>]+?)>";
// private static final String INTS_INIT = "#@\\.init_ints
// \\{([\\S[^\\}]]+?)\\}";
private static final String PLACES_LINE = "#\\|\\.places ([.[^\\n]]+)\\n";
private static final String MARKING_LINE = "\\.marking \\{(.+)\\}";
private static final String MARKING = "\\w+";
private static final String ENABLING_LINE = "#@\\.enablings \\{([.[^\\}]]+?)\\}";
private static final String ENABLING = "(<([\\S[^=]]+?)=(\\[([^\\]]+?)\\])+?>)?";
private static final String ASSIGNMENT_LINE = "#@\\.assignments \\{([.[^\\}]]+?)\\}";
// private static final String INT_ASSIGNMENT_LINE = "#@\\.int_assignments
// \\{([.[^\\}]]+?)\\}";
private static final String RATE_ASSIGNMENT_LINE = "#@\\.rate_assignments \\{([.[^\\}]]+?)\\}";
private static final String ASSIGNMENT = "<([\\S[^=]]+?)=\\[([^>]+?)\\]>";
private static final String ASSIGN_VAR = "([\\S[^:]]+?):=([\\S]+)";
private static final String INDET_ASSIGN_VAR = "([\\S[^:]]+?):=(\\[[-\\d]+,[-\\d]+\\])";
private static final String DELAY_LINE = "#@\\.delay_assignments \\{([\\S[^\\}]]+?)\\}";
private static final String DELAY = "<([\\w_]+)=(\\[\\w+,\\w+\\])>";
private static final String TRANS_RATE_LINE = "#@\\.transition_rates \\{([\\S[^\\}]]+?)\\}";
private static final String BOOLEAN_LINE = "#@\\.boolean_assignments \\{([\\S[^\\}]]+?)\\}";
private static final String BOOLEAN_TRANS = "<([\\w]+?)=([\\S[^>]]+?)>";
private static final String BOOLEAN_ASSIGN = "\\[([\\w_]+):=([\\S^\\]]+)\\]";
private static final String WORD = "(\\S+)";
} | gui/src/lhpn2sbml/parser/LHPNFile.java | package lhpn2sbml.parser;
//import gcm2sbml.util.GlobalConstants;
import java.io.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
//import javax.swing.JOptionPane;
import biomodelsim.Log;
/**
* This class describes an LHPN file
*
* @author Kevin Jones
* @organization University of Utah
*/
public class LHPNFile {
private HashMap<String, Boolean> places;
private HashMap<String, String> inputs;
private HashMap<String, String> outputs;
private HashMap<String, String> enablings;
private HashMap<String, Properties> controlFlow;
private HashMap<String, Properties> controlPlaces;
private HashMap<String, Properties> variables;
private HashMap<String, String> integers;
private HashMap<String, Properties> rateAssignments;
private HashMap<String, Properties> contAssignments;
private HashMap<String, Properties> intAssignments;
private HashMap<String, String> delays;
private HashMap<String, String> transitionRates;
private HashMap<String, Properties> booleanAssignments;
private String property;
private Log log;
public LHPNFile(Log log) {
this.log = log;
places = new HashMap<String, Boolean>();
inputs = new HashMap<String, String>();
outputs = new HashMap<String, String>();
enablings = new HashMap<String, String>();
delays = new HashMap<String, String>();
transitionRates = new HashMap<String, String>();
booleanAssignments = new HashMap<String, Properties>();
controlFlow = new HashMap<String, Properties>();
controlPlaces= new HashMap<String, Properties>();
variables = new HashMap<String, Properties>();
integers = new HashMap<String, String>();
rateAssignments = new HashMap<String, Properties>();
contAssignments = new HashMap<String, Properties>();
intAssignments = new HashMap<String, Properties>();
}
public LHPNFile() {
places = new HashMap<String, Boolean>();
inputs = new HashMap<String, String>();
outputs = new HashMap<String, String>();
enablings = new HashMap<String, String>();
delays = new HashMap<String, String>();
transitionRates = new HashMap<String, String>();
booleanAssignments = new HashMap<String, Properties>();
controlFlow = new HashMap<String, Properties>();
controlPlaces= new HashMap<String, Properties>();
variables = new HashMap<String, Properties>();
integers = new HashMap<String, String>();
rateAssignments = new HashMap<String, Properties>();
contAssignments = new HashMap<String, Properties>();
intAssignments = new HashMap<String, Properties>();
}
public void save(String filename) {
try {
String file = filename;
PrintStream p = new PrintStream(new FileOutputStream(filename));
StringBuffer buffer = new StringBuffer();
HashMap<String, Integer> boolOrder = new HashMap<String, Integer>();
int i = 0;
if (!inputs.isEmpty()) {
buffer.append(".inputs ");
for (String s : inputs.keySet()) {
if (inputs.get(s) != null) {
buffer.append(s + " ");
boolOrder.put(s, i);
i++;
}
}
buffer.append("\n");
}
if (!outputs.isEmpty()) {
buffer.append(".outputs ");
for (String s : outputs.keySet()) {
if (outputs.get(s) != null) {
buffer.append(s + " ");
boolOrder.put(s, i);
i++;
}
}
buffer.append("\n");
}
if (!controlFlow.isEmpty()) {
buffer.append(".dummy ");
for (String s : controlFlow.keySet()) {
buffer.append(s + " ");
}
buffer.append("\n");
}
if (!variables.isEmpty() || !integers.isEmpty()) {
buffer.append("#@.variables ");
for (String s : variables.keySet()) {
buffer.append(s + " ");
}
for (String s : integers.keySet()) {
buffer.append(s + " ");
}
buffer.append("\n");
}
if (!places.isEmpty()) {
buffer.append("#|.places ");
for (String s : places.keySet()) {
buffer.append(s + " ");
}
buffer.append("\n");
}
if (!inputs.isEmpty() || !outputs.isEmpty()) {
boolean flag = false;
for (i = 0; i < boolOrder.size(); i++) {
for (String s : inputs.keySet()) {
if (boolOrder.get(s).equals(i)) {
if (!flag) {
buffer.append("#@.init_state [");
flag = true;
}
if (inputs.get(s).equals("true")) {
buffer.append("1");
}
else if (inputs.get(s).equals("false")) {
buffer.append("0");
}
else {
buffer.append("X");
}
}
}
for (String s : outputs.keySet()) {
if (s != null && boolOrder.get(s) != null) {
// log.addText(s);
if (boolOrder.get(s).equals(i) && outputs.get(s) != null) {
if (!flag) {
buffer.append("#@.init_state [");
flag = true;
}
if (outputs.get(s).equals("true")) {
buffer.append("1");
}
else if (outputs.get(s).equals("false")) {
buffer.append("0");
}
else {
buffer.append("X");
}
}
}
}
}
if (flag) {
buffer.append("]\n");
}
}
if (!controlFlow.isEmpty()) {
buffer.append(".graph\n");
for (String s : controlFlow.keySet()) {
// log.addText(s);
if (controlFlow.get(s) != null) {
Properties prop = controlFlow.get(s);
// log.addText(s + prop.getProperty("to"));
if (prop.getProperty("to") != null) {
String toString = prop.getProperty("to");
if (toString != null) {
// log.addText("to " + toString);
String[] toArray = toString.split("\\s");
for (i = 0; i < toArray.length; i++) {
if (toArray[i] != null && !toArray[i].equals("null")) {
buffer.append(s + " " + toArray[i] + "\n");
}
}
}
}
if (prop.getProperty("from") != null) {
String fromString = prop.getProperty("from");
if (fromString != null) {
// log.addText("from "+ fromString);
String[] fromArray = fromString.split("\\s");
for (i = 0; i < fromArray.length; i++) {
if (fromArray[i] != null && !fromArray[i].equals("null")) {
buffer.append(fromArray[i] + " " + s + "\n");
}
}
}
}
}
}
}
boolean flag = false;
if (!places.keySet().isEmpty()) {
for (String s : places.keySet()) {
if (places.get(s).equals(true)) {
if (!flag) {
buffer.append(".marking {");
flag = true;
}
buffer.append(s + " ");
}
}
if (flag) {
buffer.append("}\n");
}
}
if (property != null && !property.equals("")) {
buffer.append("#@.property " + property + "\n");
}
if (!variables.isEmpty() || !integers.isEmpty()) {
buffer.append("#@.init_vals {");
for (String s : variables.keySet()) {
Properties prop = variables.get(s);
buffer.append("<" + s + "=" + prop.getProperty("value") + ">");
}
for (String s : integers.keySet()) {
String ic = integers.get(s);
buffer.append("<" + s + "=" + ic + ">");
}
if (!variables.isEmpty()) {
buffer.append("}\n#@.init_rates {");
for (String s : variables.keySet()) {
Properties prop = variables.get(s);
buffer.append("<" + s + "=" + prop.getProperty("rate") + ">");
}
}
buffer.append("}\n");
}
if (!enablings.isEmpty()) {
flag = false;
for (String s : enablings.keySet()) {
if (s != null && !enablings.get(s).equals("")) {
if (!flag) {
buffer.append("#@.enablings {");
flag = true;
}
// log.addText("here " + enablings.get(s));
buffer.append("<" + s + "=[" + enablings.get(s) + "]>");
}
}
if (flag) {
buffer.append("}\n");
}
}
if (!contAssignments.isEmpty() || !intAssignments.isEmpty()) {
flag = false;
for (String s : contAssignments.keySet()) {
Properties prop = contAssignments.get(s);
//log.addText(prop.toString());
if (!prop.isEmpty()) {
if (!flag) {
buffer.append("#@.assignments {");
flag = true;
}
buffer.append("<" + s + "=");
for (Object key : prop.keySet()) {
String t = (String) key;
buffer.append("[" + t + ":=" + prop.getProperty(t) + "]");
}
buffer.append(">");
}
}
for (String s : intAssignments.keySet()) {
Properties prop = intAssignments.get(s);
if (!prop.isEmpty()) {
if (!flag) {
buffer.append("#@.assignments {");
flag = true;
}
buffer.append("<" + s + "=");
for (Object key : prop.keySet()) {
String t = (String) key;
// log.addText("key " + t);
buffer.append("[" + t + ":=" + prop.getProperty(t) + "]");
}
buffer.append(">");
}
}
if (flag) {
buffer.append("}\n");
}
}
if (!rateAssignments.isEmpty()) {
flag = false;
for (String s : rateAssignments.keySet()) {
boolean varFlag = false;
Properties prop = rateAssignments.get(s);
for (Object key : prop.keySet()) {
String t = (String) key;
if (!t.equals("")) {
if (!flag) {
buffer.append("#@.rate_assignments {");
flag = true;
}
if (!varFlag) {
buffer.append("<" + s + "=");
varFlag = true;
}
buffer.append("[" + t + ":=" + prop.getProperty(t) + "]");
}
}
if (varFlag) {
buffer.append(">");
}
}
if (flag) {
buffer.append("}\n");
}
}
if (!delays.isEmpty()) {
buffer.append("#@.delay_assignments {");
for (String s : delays.keySet()) {
buffer.append("<" + s + "=" + delays.get(s) + ">");
}
buffer.append("}\n");
}
if (!transitionRates.isEmpty()) {
buffer.append("#@.transition_rates {");
for (String s : transitionRates.keySet()) {
buffer.append("<" + s + "=" + transitionRates.get(s) + ">");
}
buffer.append("}\n");
}
if (!booleanAssignments.isEmpty()) {
flag = false;
for (String s : booleanAssignments.keySet()) {
if (!s.equals("")) {
boolean varFlag = false;
Properties prop = booleanAssignments.get(s);
for (Object key : prop.keySet()) {
String t = (String) key;
if (!t.equals("") && (isInput(t) || isOutput(t))) {
if (!flag) {
buffer.append("#@.boolean_assignments {");
flag = true;
}
if (!varFlag) {
buffer.append("<" + s + "=");
varFlag = true;
}
buffer.append("[" + t + ":=" + prop.getProperty(t) + "]");
}
}
if (varFlag) {
buffer.append(">");
}
}
}
if (flag) {
buffer.append("}\n");
}
}
if (!variables.isEmpty()) {
buffer.append("#@.continuous ");
for (String s : variables.keySet()) {
buffer.append(s + " ");
}
buffer.append("\n");
}
if (buffer.toString().length() > 0) {
buffer.append(".end\n");
}
// System.out.print(buffer);
p.print(buffer);
p.close();
if (log != null) {
log.addText("Saving:\n" + file + "\n");
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public void load(String filename) {
places = new HashMap<String, Boolean>();
inputs = new HashMap<String, String>();
outputs = new HashMap<String, String>();
enablings = new HashMap<String, String>();
controlFlow = new HashMap<String, Properties>();
controlPlaces = new HashMap<String, Properties>();
variables = new HashMap<String, Properties>();
contAssignments = new HashMap<String, Properties>();
rateAssignments = new HashMap<String, Properties>();
StringBuffer data = new StringBuffer();
try {
BufferedReader in = new BufferedReader(new FileReader(filename));
String str;
while ((str = in.readLine()) != null) {
data.append(str + "\n");
// System.out.println(str);
}
in.close();
}
catch (IOException e) {
e.printStackTrace();
throw new IllegalStateException("Error opening file");
}
try {
parseProperty(data);
// System.out.println("check1");
// log.addText("check1");
parseInOut(data);
// System.out.println("check2");
// log.addText("check2");
// parseTransitions(data);
parseControlFlow(data);
// System.out.println("check3");
// log.addText("check3");
parseVars(data);
// System.out.println("check4");
// log.addText("check");
parseIntegers(data);
// parseInitialVals(data);
// System.out.println("check5");
// log.addText("check4");
parsePlaces(data);
parseMarking(data);
// System.out.println("check6");
// log.addText("check5");
parseEnabling(data);
// System.out.println("check7");
// log.addText("check6");
parseAssign(data);
// System.out.println("check8");
// log.addText("check7");
parseRateAssign(data);
// System.out.println("check9");
// log.addText("check8");
parseDelayAssign(data);
parseTransitionRate(data);
// parseIntAssign(data);
// System.out.println("check0");
// log.addText("check9");
parseBooleanAssign(data);
// System.out.println("check11");
// log.addText("check0");
//log.addText(intAssignments.toString());
}
catch (Exception e) {
e.printStackTrace();
throw new IllegalArgumentException("Unable to parse LHPN");
}
}
public void addPlace(String name, Boolean ic) {
places.put(name, ic);
}
public void removePlace(String name) {
if (name != null && places.containsKey(name)) {
places.remove(name);
}
}
public void addInput(String name, String ic) {
inputs.put(name, ic);
}
public void removeInput(String name) {
if (name != null && inputs.containsKey(name)) {
inputs.remove(name);
}
}
public void addOutput(String name, String ic) {
outputs.put(name, ic);
}
public void removeOutput(String name) {
if (name != null && outputs.containsKey(name)) {
outputs.remove(name);
}
}
// public void addFlow(String from, String to) {
// String name = "";
// Properties flow = new Properties();
// if (controlFlow.containsKey(from)) {
// name = from;
// flow = controlFlow.get(from);
// flow.setProperty(name + "to", flow.getProperty(name + "to") + to + " ");
// }
// else if (controlFlow.containsKey(to)) {
// name = to;
// flow = controlFlow.get(to);
// flow.setProperty(name + "from", flow.getProperty(name + "from") + to + "
// ");
// }
// controlFlow.put(name, flow);
// }
// public void removeFlow(String from, String to) {
// String name = "";
// Properties flow = new Properties();
// if (controlFlow.containsKey(from)) {
// name = from;
// flow = controlFlow.get(from);
// String toString = flow.getProperty("to");
// String[] toArray = toString.split("\\s");
// boolean flag = false;
// for (int i = 0; i < toArray.length; i++) {
// if (flag) {
// toArray[i - 1] = toArray[i];
// }
// if (toArray[i].equals(to)) {
// flag = true;
// }
// }
// flow.setProperty(name + "to", "");
// for (int i = 0; i < toArray.length - 1; i++) {
// flow.setProperty("to", flow.getProperty("to") + toArray[i] + " ");
// }
// }
// else if (controlFlow.containsKey(to)) {
// name = to;
// flow = controlFlow.get(to);
// String fromString = flow.getProperty("from");
// String[] fromArray = fromString.split("\\s");
// boolean flag = false;
// for (int i = 0; i < fromArray.length; i++) {
// if (flag) {
// fromArray[i - 1] = fromArray[i];
// }
// if (fromArray[i].equals(to)) {
// flag = true;
// }
// }
// flow.setProperty("from", "");
// for (int i = 0; i < fromArray.length - 1; i++) {
// flow.setProperty("from", flow.getProperty("from") + fromArray[i] + " ");
// }
// }
// }
public void addTransition(String name) {
controlFlow.put(name, null);
}
public void addTransition(String name, Properties prop) {
controlFlow.put(name, prop);
}
public void addControlFlow(String fromName, String toName) {
// log.addText(fromName+toName);
if (isTransition(fromName)) {
Properties prop = new Properties();
String list = "";
String placeList = "";
if (controlFlow.containsKey(fromName)) {
if (controlFlow.get(fromName) != null) {
prop = controlFlow.get(fromName);
list = prop.getProperty("to");
list = list + " " + toName;
}
}
else {
list = toName;
}
if (controlPlaces.containsKey(fromName)) {
if (controlPlaces.get(fromName) != null) {
prop = controlPlaces.get(fromName);
placeList = prop.getProperty("to");
placeList = placeList + " " + toName;
}
}
else {
placeList = toName;
}
// log.addText(list);
// System.out.println(prop == null);
prop.setProperty("to", list);
controlFlow.put(fromName, prop);
prop.setProperty("to", placeList);
controlPlaces.put(fromName, prop);
}
else {
Properties prop = new Properties();
String list = "";
String placeList = "";
if (controlFlow.containsKey(toName)) {
if (controlFlow.get(toName) != null) {
prop = controlFlow.get(toName);
list = prop.getProperty("from");
list = list + " " + fromName;
}
else {
list = fromName;
}
}
else {
list = fromName;
}
if (controlPlaces.containsKey(toName)) {
if (controlPlaces.get(toName) != null) {
prop = controlPlaces.get(toName);
placeList = prop.getProperty("from");
placeList = placeList + " " + fromName;
}
else {
placeList = fromName;
}
}
else {
placeList = fromName;
}
prop.setProperty("from", list);
controlFlow.put(toName, prop);
prop.setProperty("from", list);
controlPlaces.put(toName, prop);
}
}
public void removeControlFlow(String fromName, String toName) {
if (isTransition(fromName)) {
Properties prop = controlFlow.get(fromName);
String[] list = prop.getProperty("to").split("\\s");
String[] toList = new String[list.length - 1];
Boolean flag = false;
for (int i = 0; i < list.length - 1; i++) {
if (toName.equals(list[i])) {
flag = true;
}
else {
if (flag) {
toList[i - 1] = list[i];
}
else {
toList[i] = list[i];
}
}
}
if (toList.length > 0) {
prop.put("to", toList);
}
else {
prop.remove("to");
}
controlFlow.put(fromName, prop);
prop = controlPlaces.get(toName);
list = prop.getProperty("from").split("\\s");
String[] fromList = new String[list.length - 1];
flag = false;
for (int i = 0; i < list.length - 1; i++) {
if (toName.equals(list[i])) {
flag = true;
}
else {
if (flag) {
fromList[i - 1] = list[i];
}
else {
fromList[i] = list[i];
}
}
}
if (fromList.length > 0) {
prop.put("from", fromList);
}
else {
prop.remove("from");
}
controlPlaces.put(toName, prop);
}
else {
Properties prop = controlFlow.get(toName);
String[] list = prop.getProperty("from").split("\\s");
String[] fromList = new String[list.length - 1];
Boolean flag = false;
for (int i = 0; i < list.length - 1; i++) {
if (toName.equals(list[i])) {
flag = true;
}
else {
if (flag) {
fromList[i - 1] = list[i];
}
else {
fromList[i] = list[i];
}
}
}
if (fromList.length > 0) {
prop.put("from", fromList);
}
else {
prop.remove("from");
}
controlPlaces.put(toName, prop);
prop = controlPlaces.get(fromName);
list = prop.getProperty("to").split("\\s");
String[] toList = new String[list.length - 1];
flag = false;
for (int i = 0; i < list.length - 1; i++) {
if (toName.equals(list[i])) {
flag = true;
}
else {
if (flag) {
toList[i - 1] = list[i];
}
else {
toList[i] = list[i];
}
}
}
if (toList.length > 0) {
prop.put("to", toList);
}
else {
prop.remove("to");
}
controlPlaces.put(fromName, prop);
}
}
public boolean containsFlow(String fromName, String toName) {
if (isTransition(fromName)) {
Properties prop = controlFlow.get(fromName);
if (prop != null) {
if (prop.getProperty("to") != null) {
String[] list = prop.getProperty("to").split("\\s");
for (int i = 0; i < list.length; i++) {
if (list[i].equals(toName)) {
return true;
}
}
}
}
return false;
}
else {
Properties prop = controlFlow.get(toName);
if (prop != null) {
if (prop.getProperty("from") != null) {
String[] list = prop.getProperty("from").split("\\s");
for (int i = 0; i < list.length; i++) {
if (list[i].equals(fromName)) {
return true;
}
}
}
}
return false;
}
}
public boolean containsFlow(String place) {
if (controlFlow.containsKey(place)) {
if (!controlFlow.get(place).isEmpty()) {
return true;
}
}
for (String s : controlFlow.keySet()) {
Properties prop = controlFlow.get(s);
if (prop.containsKey("to")) {
String[] toList = prop.get("to").toString().split(" ");
for (int i = 0; i < toList.length; i++) {
if (toList[i].equals(place)) {
return true;
}
}
}
if (prop.containsKey("from")) {
String[] fromList = prop.get("from").toString().split(" ");
for (int i = 0; i < fromList.length; i++) {
if (fromList[i].equals(place)) {
return true;
}
}
}
}
return false;
}
public void addTransition(String name, String delay, String transitionRate, Properties rateAssign,
Properties booleanAssign, String enabling) {
addTransition(name);
delays.put(name, delay);
transitionRates.put(name, transitionRate);
rateAssignments.put(name, rateAssign);
booleanAssignments.put(name, booleanAssign);
enablings.put(name, enabling);
}
public void removeTransition(String name) {
controlFlow.remove(name);
delays.remove(name);
transitionRates.remove(name);
rateAssignments.remove(name);
booleanAssignments.remove(name);
enablings.remove(name);
}
public void addEnabling(String name, String cond) {
enablings.put(name, cond);
}
public void removeEnabling(String name) {
if (name != null && enablings.containsKey(name)) {
enablings.remove(name);
}
}
public void addVar(String name, Properties initCond) {
variables.put(name, initCond);
}
public int removeVar(String name) {
int flag = 0;
for (String s : booleanAssignments.keySet()) {
Properties prop = booleanAssignments.get(s);
for (Object object : prop.keySet()) {
String propName = object.toString();
if (propName.equals(name)) {
flag = 1;
}
}
}
for (String s : contAssignments.keySet()) {
Properties prop = contAssignments.get(s);
for (Object object : prop.keySet()) {
String propName = object.toString();
if (propName.equals(name)) {
flag = 1;
}
}
}
for (String s : rateAssignments.keySet()) {
Properties prop = rateAssignments.get(s);
for (Object object : prop.keySet()) {
String propName = object.toString();
if (propName.equals(name)) {
flag = 1;
}
}
}
for (String s : integers.keySet()) {
Properties prop = intAssignments.get(s);
if (prop != null) {
for (Object object : prop.keySet()) {
String propName = object.toString();
if (propName.equals(name)) {
flag = 1;
}
}
}
}
if (flag == 0 && name != null && variables.containsKey(name)) {
variables.remove(name);
}
else if (flag == 0 && name != null && inputs.containsKey(name)) {
inputs.remove(name);
}
else if (flag == 0 && name != null && outputs.containsKey(name)) {
outputs.remove(name);
}
else if (flag == 0 && name != null && integers.containsKey(name)) {
integers.remove(name);
}
return flag;
}
public void addInteger(String name, String ic) {
integers.put(name, ic);
}
public void addRateAssign(String transition, String name, String value) {
Properties prop = new Properties();
if (rateAssignments.get(transition) != null) {
prop = rateAssignments.get(transition);
}
prop.setProperty(name, value);
rateAssignments.put(transition, prop);
}
public void removeRateAssign(String transition, String name) {
if (rateAssignments.containsKey(transition)) {
Properties prop = rateAssignments.get(transition);
if (name != null && prop.containsKey(name)) {
prop.remove(name);
}
rateAssignments.put(transition, prop);
}
}
public void addBoolAssign(String transition, String name, String value) {
Properties prop = new Properties();
if (booleanAssignments.get(transition) != null) {
prop = booleanAssignments.get(transition);
}
prop.setProperty(name, value);
booleanAssignments.put(transition, prop);
}
public void removeBoolAssign(String transition, String name) {
Properties prop = booleanAssignments.get(transition);
if (name != null && prop.containsKey(name)) {
prop.remove(name);
}
booleanAssignments.put(transition, prop);
}
public void addContAssign(String transition, String name, String value) {
Properties prop = new Properties();
if (contAssignments.get(transition) != null) {
prop = contAssignments.get(transition);
}
//System.out.println("here " + transition + name + value);
prop.setProperty(name, value);
//log.addText("lhpn " + prop.toString());
contAssignments.put(transition, prop);
}
public void removeContAssign(String transition, String name) {
if (contAssignments.containsKey(transition)) {
Properties prop = contAssignments.get(transition);
if (name != null && prop.containsKey(name)) {
prop.remove(name);
}
//log.addText("lhpn " + prop.toString());
contAssignments.put(transition, prop);
}
}
public void addIntAssign(String transition, String name, String value) {
Properties prop = new Properties();
if (intAssignments.get(transition) != null) {
prop = intAssignments.get(transition);
}
// System.out.println("here " + transition + name + value);
prop.setProperty(name, value);
intAssignments.put(transition, prop);
}
public void removeIntAssign(String transition, String name) {
if (intAssignments.containsKey(transition)) {
Properties prop = intAssignments.get(transition);
if (name != null && prop.containsKey(name)) {
prop.remove(name);
}
intAssignments.put(transition, prop);
}
}
public void removeAllAssign(String transition) {
if (booleanAssignments.containsKey(transition)) {
Properties prop = new Properties();
booleanAssignments.put(transition, prop);
}
if (contAssignments.containsKey(transition)) {
Properties prop = new Properties();
contAssignments.put(transition, prop);
}
if (rateAssignments.containsKey(transition)) {
Properties prop = new Properties();
rateAssignments.put(transition, prop);
}
if (intAssignments.containsKey(transition)) {
Properties prop = new Properties();
intAssignments.put(transition, prop);
}
}
public void addProperty(String newProperty) {
property = newProperty;
}
public void removeProperty() {
property = "";
}
public String getProperty() {
return property;
}
public void changeVariableName(String oldName, String newName) {
if (isContinuous(oldName)) {
variables.put(newName, variables.get(oldName));
variables.remove(oldName);
}
else if (isInput(oldName)) {
inputs.put(newName, inputs.get(oldName));
inputs.remove(oldName);
}
else if (isInteger(oldName)) {
integers.put(newName, integers.get(oldName));
integers.remove(oldName);
}
else {
outputs.put(newName, outputs.get(oldName));
outputs.remove(oldName);
}
}
public void changeTransitionName(String oldName, String newName) {
controlFlow.put(newName, controlFlow.get(oldName));
controlFlow.remove(oldName);
delays.put(newName, delays.get(oldName));
delays.remove(oldName);
transitionRates.put(newName, transitionRates.get(oldName));
transitionRates.remove(oldName);
rateAssignments.put(newName, rateAssignments.get(oldName));
rateAssignments.remove(oldName);
booleanAssignments.put(newName, booleanAssignments.get(oldName));
booleanAssignments.remove(oldName);
enablings.put(newName, enablings.get(oldName));
enablings.remove(oldName);
}
public void changeDelay(String transition, String delay) {
if (delays.containsKey(transition)) {
delays.remove(transition);
}
// log.addText(transition + delay);
delays.put(transition, delay);
}
public void changeTransitionRate(String transition, String rate) {
if (transitionRates.containsKey(transition)) {
transitionRates.remove(transition);
}
// log.addText(transition + delay);
transitionRates.put(transition, rate);
}
public void changeEnabling(String transition, String enabling) {
if (enablings.containsKey(transition)) {
enablings.remove(transition);
}
enablings.put(transition, enabling);
}
public String[] getAllIDs() {
String[] allVariables = new String[variables.size() + integers.size() + inputs.size()
+ outputs.size() + delays.size() + places.size()];
int i = 0;
for (String s : variables.keySet()) {
allVariables[i] = s;
i++;
}
for (String s : integers.keySet()) {
allVariables[i] = s;
i++;
}
for (String s : inputs.keySet()) {
allVariables[i] = s;
i++;
}
for (String s : outputs.keySet()) {
allVariables[i] = s;
i++;
}
for (String s : delays.keySet()) {
allVariables[i] = s;
i++;
}
for (String s : places.keySet()) {
allVariables[i] = s;
i++;
}
return allVariables;
}
public HashMap<String, Properties> getVariables() {
return variables;
}
public HashMap<String, String> getIntegers() {
return integers;
}
public HashMap<String, String> getInputs() {
return inputs;
}
public HashMap<String, String> getOutputs() {
return outputs;
}
public HashMap<String, Boolean> getPlaces() {
return places;
}
public HashMap<String, String> getDelays() {
return delays;
}
public String getDelay(String var) {
return delays.get(var);
}
public HashMap<String, String> getTransitionRates() {
return transitionRates;
}
public String getTransitionRate(String var) {
return transitionRates.get(var);
}
public String[] getControlFlow() {
String retString = "";
for (String s : controlFlow.keySet()) {
// log.addText("key: " + s);
Properties prop = controlFlow.get(s);
String toString = prop.getProperty("to");
// log.addText("toString " + toString);
if (toString != null) {
String[] toArray = toString.split("\\s");
for (int i = 0; i < toArray.length; i++) {
retString = retString + s + " " + toArray[i] + "\n";
}
}
// log.addText("getfrom");
String fromString = prop.getProperty("from");
if (fromString != null) {
// log.addText("fromString " + fromString);
String[] fromArray = fromString.split("\\s");
for (int i = 0; i < fromArray.length; i++) {
retString = retString + fromArray[i] + " " + s + "\n";
}
}
}
return retString.split("\\n");
}
public String getInitialVal(String var) {
if (isContinuous(var)) {
Properties prop = variables.get(var);
return prop.getProperty("value");
}
else if (isInteger(var)) {
String integer = integers.get(var);
return integer;
}
else if (isInput(var)) {
return inputs.get(var);
}
else if (isOutput(var)) {
return outputs.get(var);
}
else {
return "";
}
}
public boolean getPlaceInitial(String var) {
return places.get(var);
}
public String getInitialRate(String var) {
Properties prop = variables.get(var);
return prop.getProperty("rate");
}
public String getEnabling(String var) {
return enablings.get(var);
}
public String[] getBooleanVars(String trans) {
if (booleanAssignments.containsKey(trans)) {
Properties prop = booleanAssignments.get(trans);
String[] assignArray = new String[prop.size()];
int i = 0;
for (Object s : prop.keySet()) {
if (prop.get(s) != null) {
if (isInput(s.toString()) || isOutput(s.toString())) {
assignArray[i] = s.toString();
i++;
}
}
}
return assignArray;
}
return null;
}
public String[] getBooleanVars() {
Object[] inArray = inputs.keySet().toArray();
Object[] outArray = outputs.keySet().toArray();
String[] vars = new String[inArray.length + outArray.length];
int i;
for (i = 0; i < inArray.length; i++) {
vars[i] = inArray[i].toString();
}
for (int j = 0; j < outArray.length; j++) {
vars[i] = outArray[j].toString();
i++;
}
return vars;
}
public String[] getContVars() {
if (!variables.isEmpty()) {
Object[] objArray = variables.keySet().toArray();
String[] vars = new String[objArray.length];
for (int i = 0; i < objArray.length; i++) {
vars[i] = objArray[i].toString();
}
return vars;
}
else {
return new String[0];
}
}
public Properties getContVars(String trans) {
Properties contVars = new Properties();
contVars = contAssignments.get(trans);
//log.addText("lhpn " + contVars.toString());
return contVars;
}
public String[] getIntVars() {
if (!integers.isEmpty()) {
Object[] objArray = integers.keySet().toArray();
String[] vars = new String[objArray.length];
for (int i = 0; i < objArray.length; i++) {
vars[i] = objArray[i].toString();
}
return vars;
}
else {
return new String[0];
}
}
public Properties getIntVars(String trans) {
// log.addText(trans);
Properties intVars = new Properties();
intVars = intAssignments.get(trans);
if (intVars != null) {
String[] tempArray = new String[intVars.keySet().size()];
int i = 0;
for (Object s : intVars.keySet()) {
String t = (String) s;
if (!isInteger(t)) {
tempArray[i] = t;
i++;
}
}
for (i = 0; i < tempArray.length; i++) {
if (tempArray[i] != null) {
intVars.remove(tempArray[i]);
}
else {
break;
}
}
return intVars;
}
return null;
}
public String[] getContAssignVars(String trans) {
// log.addText(trans);
if (contAssignments.containsKey(trans)) {
Properties prop = contAssignments.get(trans);
String[] assignArray = new String[prop.size()];
int i = 0;
for (Object s : prop.keySet()) {
if (isContinuous(s.toString())) {
assignArray[i] = s.toString();
i++;
}
}
// Properties prop = booleanAssignments.get(var);
// prop.setProperty("type", "boolean");
return assignArray;
}
else {
// log.addText("returning null");
return null;
}
}
public String[] getRateVars(String trans) {
if (rateAssignments.containsKey(trans)) {
Properties prop = rateAssignments.get(trans);
String[] assignArray = new String[prop.size()];
int i = 0;
for (Object s : prop.keySet()) {
if (isContinuous(s.toString())) {
assignArray[i] = s.toString();
i++;
}
}
// Properties prop = booleanAssignments.get(var);
// prop.setProperty("type", "boolean");
return assignArray;
}
return null;
}
public String getBoolAssign(String trans, String var) {
if (booleanAssignments.containsKey(trans)) {
Properties prop = booleanAssignments.get(trans);
if (prop != null && var != null) {
if (prop.containsKey(var)) {
return prop.getProperty(var);
}
}
}
return null;
}
public String getContAssign(String transition, String var) {
if (contAssignments.containsKey(transition) && var != null) {
Properties prop = contAssignments.get(transition);
//log.addText("lhpn " + prop.toString());
if (prop.containsKey(var)) {
return prop.getProperty(var);
}
}
return null;
}
public String getIntAssign(String transition, String var) {
if (intAssignments.containsKey(transition) && var != null) {
Properties prop = intAssignments.get(transition);
if (prop.containsKey(var)) {
return prop.getProperty(var);
}
}
return null;
}
public String getRateAssign(String transition, String var) {
Properties prop = rateAssignments.get(transition);
if (prop != null && var != null) {
return prop.getProperty(var);
}
return "";
}
public String[] getPlaceList() {
String[] placeList = new String[places.keySet().size()];
int i = 0;
for (String s : places.keySet()) {
placeList[i] = s;
i++;
}
return placeList;
}
public String[] getTransitionList() {
String[] transitionList = new String[controlFlow.keySet().size()];
int i = 0;
for (String s : controlFlow.keySet()) {
transitionList[i] = s;
i++;
}
return transitionList;
}
public boolean isContinuous(String var) {
return variables.containsKey(var);
}
public boolean isInput(String var) {
return inputs.containsKey(var);
}
public boolean isOutput(String var) {
return outputs.containsKey(var);
}
public boolean isInteger(String var) {
return integers.containsKey(var);
}
public boolean isTransition(String var) {
for (String s : controlFlow.keySet()) {
if (var.equals(s)) {
return true;
}
}
return false;
}
/*
* private void parseTransitions(StringBuffer data) { Pattern pattern =
* Pattern.compile(TRANSITION); Matcher line_matcher =
* pattern.matcher(data.toString()); Pattern output = Pattern.compile(WORD);
* Matcher matcher = output.matcher(line_matcher.group()); while
* (line_matcher.find()) { String name = matcher.group();
* controlFlow.put(name, name); } }
*/
private void parseProperty(StringBuffer data) {
Pattern pattern = Pattern.compile(PROPERTY);
Matcher lineMatcher = pattern.matcher(data.toString());
if (lineMatcher.find()) {
property = lineMatcher.group(1);
}
}
private void parseControlFlow(StringBuffer data) {
// log.addText("check2start");
Pattern pattern = Pattern.compile(TRANSITION);
Matcher lineMatcher = pattern.matcher(data.toString());
if (lineMatcher.find()) {
lineMatcher.group(1);
// log.addText("check2a-");
String name = lineMatcher.group(1).replaceAll("\\+/", "P");
name = name.replaceAll("-/", "M");
// log.addText("check2a+");
Pattern transPattern = Pattern.compile(WORD);
Matcher transMatcher = transPattern.matcher(name);
// log.addText("check2a");
while (transMatcher.find()) {
controlFlow.put(transMatcher.group(), new Properties());
}
Pattern placePattern = Pattern.compile(PLACE);
Matcher placeMatcher = placePattern.matcher(data.toString());
// log.addText("check2b");
while (placeMatcher.find()) {
// log.addText("check2 while");
String temp = placeMatcher.group(1).replaceAll("\\+", "P");
temp = temp.replaceAll("-", "M");
// String[] tempLine = tempString.split("#");
String[] tempPlace = temp.split("\\s");
// String trans = "";
if (controlFlow.containsKey(tempPlace[0])) {
// log.addText("check2 if");
Properties tempProp = new Properties();
if (controlFlow.get(tempPlace[0]) != null) {
tempProp = controlFlow.get(tempPlace[0]);
}
String tempString;
if (tempProp.containsKey("to")) {
tempString = tempProp.getProperty("to");
tempString = tempString + " " + tempPlace[1];
}
else {
tempString = tempPlace[1];
}
tempProp.setProperty("to", tempString);
controlFlow.put(tempPlace[0], tempProp);
places.put(tempPlace[1], false);
controlPlaces.put(tempPlace[0], new Properties());
// trans = tempPlace[0];
}
else if (controlFlow.containsKey(tempPlace[1])) {
Properties tempProp = controlFlow.get(tempPlace[1]);
// log.addText("check2c");
String tempString;
// Boolean temp = tempProp.containsKey("from");
// log.addText("check2c1");
// log.addText(temp.toString());
if (tempProp.containsKey("from")) {
// log.addText("check2a if");
tempString = tempProp.getProperty("from");
// log.addText("check2a if1");
tempString = tempString + " " + tempPlace[0];
}
else {
// log.addText("check2a else");
tempString = tempPlace[0];
}
// log.addText("check2d");
// log.addText("check2d1");
tempProp.setProperty("from", tempString);
// log.addText("check2e");
controlFlow.put(tempPlace[1], tempProp);
places.put(tempPlace[0], false);
controlPlaces.put(tempPlace[0], new Properties());
// trans = tempPlace[1];
}
if (controlPlaces.containsKey(tempPlace[0])) {
// log.addText("check2 if");
Properties tempProp = new Properties();
if (controlPlaces.get(tempPlace[0]) != null) {
tempProp = controlPlaces.get(tempPlace[0]);
}
String tempString;
if (tempProp.containsKey("to")) {
tempString = tempProp.getProperty("to");
tempString = tempString + " " + tempPlace[1];
}
else {
tempString = tempPlace[1];
}
tempProp.setProperty("to", tempString);
controlPlaces.put(tempPlace[0], tempProp);
// trans = tempPlace[0];
}
else if (controlPlaces.containsKey(tempPlace[1])) {
Properties tempProp = controlPlaces.get(tempPlace[1]);
// log.addText("check2c");
String tempString;
// Boolean temp = tempProp.containsKey("from");
// log.addText("check2c1");
// log.addText(temp.toString());
if (tempProp.containsKey("from")) {
// log.addText("check2a if");
tempString = tempProp.getProperty("from");
// log.addText("check2a if1");
tempString = tempString + " " + tempPlace[0];
}
else {
// log.addText("check2a else");
tempString = tempPlace[0];
}
// log.addText("check2d");
// log.addText("check2d1");
tempProp.setProperty("from", tempString);
// log.addText("check2e");
controlPlaces.put(tempPlace[1], tempProp);
// trans = tempPlace[1];
}
}
}
// for (String s : controlFlow.keySet()) {
// log.addText(s + " " + controlFlow.get(s));
// }
// log.addText("check2end");
}
private void parseInOut(StringBuffer data) {
// System.out.println("hello?");
Properties varOrder = new Properties();
// System.out.println("check1start");
// log.addText("check1start");
Pattern inLinePattern = Pattern.compile(INPUT);
Matcher inLineMatcher = inLinePattern.matcher(data.toString());
Integer i = 0;
Integer inLength = 0;
// System.out.println("check1a-");
if (inLineMatcher.find()) {
// System.out.println("checkifin");
Pattern inPattern = Pattern.compile(WORD);
Matcher inMatcher = inPattern.matcher(inLineMatcher.group(1));
while (inMatcher.find()) {
varOrder.setProperty(i.toString(), inMatcher.group());
i++;
inLength++;
}
}
// System.out.println("check1a");
Pattern outPattern = Pattern.compile(OUTPUT);
Matcher outLineMatcher = outPattern.matcher(data.toString());
if (outLineMatcher.find()) {
// log.addText("outline " + outLineMatcher.group(1));
// log.addText("check1b");
Pattern output = Pattern.compile(WORD);
Matcher outMatcher = output.matcher(outLineMatcher.group(1));
while (outMatcher.find()) {
varOrder.setProperty(i.toString(), outMatcher.group());
i++;
}
}
// System.out.println("check1e");
// log.addText("check1c");
Pattern initState = Pattern.compile(INIT_STATE);
Matcher initMatcher = initState.matcher(data.toString());
if (initMatcher.find()) {
// log.addText("check1d");
Pattern initDigit = Pattern.compile("\\d+");
Matcher digitMatcher = initDigit.matcher(initMatcher.group());
digitMatcher.find();
// log.addText("check1e");
String[] initArray = new String[digitMatcher.group().length()];
Pattern bit = Pattern.compile("[01]");
Matcher bitMatcher = bit.matcher(digitMatcher.group());
// log.addText("check1f");
i = 0;
while (bitMatcher.find()) {
initArray[i] = bitMatcher.group();
i++;
}
for (i = 0; i < inLength; i++) {
String name = varOrder.getProperty(i.toString());
if (initArray[i].equals("1")) {
inputs.put(name, "true");
}
else if (initArray[i].equals("0")) {
inputs.put(name, "false");
}
else {
inputs.put(name, "unknown");
}
}
// log.addText("check1f");
for (i = inLength; i < initArray.length; i++) {
String name = varOrder.getProperty(i.toString());
if (initArray[i].equals("1") && name != null) {
outputs.put(name, "true");
}
else if (initArray[i].equals("0") && name != null) {
outputs.put(name, "false");
}
else {
outputs.put(name, "unknown");
}
}
}
}
private void parseVars(StringBuffer data) {
// log.addText("check3 start");
// System.out.println("check3 start");
Properties initCond = new Properties();
Properties initValue = new Properties();
Properties initRate = new Properties();
// log.addText("check3a");
// System.out.println("check3a");
Pattern linePattern = Pattern.compile(CONTINUOUS);
Matcher lineMatcher = linePattern.matcher(data.toString());
if (lineMatcher.find()) {
// log.addText("check3b");
// System.out.println("check3b");
Pattern varPattern = Pattern.compile(WORD);
Matcher varMatcher = varPattern.matcher(lineMatcher.group(1));
// log.addText("check3c");
// System.out.println("check3c");
while (varMatcher.find()) {
variables.put(varMatcher.group(), initCond);
}
// log.addText("check3d " + VARS_INIT);
// System.out.println("check3c");
Pattern initLinePattern = Pattern.compile(VARS_INIT);
// log.addText("check3d1");
// System.out.println("check3d");
Matcher initLineMatcher = initLinePattern.matcher(data.toString());
// log.addText("check3d2");
// System.out.println("check3e");
initLineMatcher.find();
// log.addText("check3e");
// System.out.println("check3f");
Pattern initPattern = Pattern.compile(INIT_COND);
Matcher initMatcher = initPattern.matcher(initLineMatcher.group(1));
// log.addText("check3f");
// System.out.println("check3g");
while (initMatcher.find()) {
if (variables.containsKey(initMatcher.group(1))) {
initValue.put(initMatcher.group(1), initMatcher.group(2));
}
}
// log.addText("check3g");
// System.out.println("check3h");
Pattern rateLinePattern = Pattern.compile(INIT_RATE);
Matcher rateLineMatcher = rateLinePattern.matcher(data.toString());
if (rateLineMatcher.find()) {
// log.addText("check3h");
// System.out.println("check3i");
Pattern ratePattern = Pattern.compile(INIT_COND);
Matcher rateMatcher = ratePattern.matcher(rateLineMatcher.group(1));
// log.addText("check3i");
// System.out.println("check3j");
while (rateMatcher.find()) {
// log.addText(rateMatcher.group(1) + "value" +
// rateMatcher.group(2));
initRate.put(rateMatcher.group(1), rateMatcher.group(2));
}
}
// log.addText("check3j");
// System.out.println("check3k");
for (String s : variables.keySet()) {
// log.addText("check3for" + s);
// System.out.println("check3for " + s);
initCond.put("value", initValue.get(s));
initCond.put("rate", initRate.get(s));
// log.addText("check3for" + initCond.toString());
// System.out.println("check3for " + initCond.toString());
variables.put(s, initCond);
}
}
// log.addText("check3end");
// System.out.println("check3end");
}
private void parseIntegers(StringBuffer data) {
// log.addText("check3 start");
String initCond = "0";
Properties initValue = new Properties();
// log.addText("check3a");
Pattern linePattern = Pattern.compile(VARIABLES);
Matcher lineMatcher = linePattern.matcher(data.toString());
// log.addText("check3b");
if (lineMatcher.find()) {
Pattern varPattern = Pattern.compile(WORD);
Matcher varMatcher = varPattern.matcher(lineMatcher.group(1));
// log.addText("check3c");
while (varMatcher.find()) {
if (!variables.containsKey(varMatcher.group())) {
integers.put(varMatcher.group(), initCond);
}
}
// log.addText("check3d " + VARS_INIT);
Pattern initLinePattern = Pattern.compile(VARS_INIT);
// log.addText("check3d1");
Matcher initLineMatcher = initLinePattern.matcher(data.toString());
// log.addText("check3d2");
if (initLineMatcher.find()) {
// log.addText("check3e");
Pattern initPattern = Pattern.compile(INIT_COND);
Matcher initMatcher = initPattern.matcher(initLineMatcher.group(1));
// log.addText("check3f");
while (initMatcher.find()) {
if (integers.containsKey(initMatcher.group(1))) {
initValue.put(initMatcher.group(1), initMatcher.group(2));
}
}
}
// log.addText("check3g");
// log.addText("check3i");
// log.addText("check3j");
for (String s : integers.keySet()) {
// log.addText("check3for" + s);
if (initValue.get(s) != null) {
initCond = initValue.get(s).toString();
}
// log.addText("check3for" + initCond);
integers.put(s, initCond);
}
}
// log.addText("check3end");
}
private void parsePlaces(StringBuffer data) {
Pattern linePattern = Pattern.compile(PLACES_LINE);
Matcher lineMatcher = linePattern.matcher(data.toString());
if (lineMatcher.find()) {
//log.addText(lineMatcher.group());
Pattern markPattern = Pattern.compile(MARKING);
Matcher markMatcher = markPattern.matcher(lineMatcher.group(1));
while (markMatcher.find()) {
places.put(markMatcher.group(), false);
}
}
}
private void parseMarking(StringBuffer data) {
// log.addText("check4start");
Pattern linePattern = Pattern.compile(MARKING_LINE);
Matcher lineMatcher = linePattern.matcher(data.toString());
if (lineMatcher.find()) {
// log.addText("check4a");
Pattern markPattern = Pattern.compile(MARKING);
Matcher markMatcher = markPattern.matcher(lineMatcher.group(1));
// log.addText("check4b");
while (markMatcher.find()) {
// log.addText("check4loop");
places.put(markMatcher.group(), true);
}
}
// log.addText("check4end");
}
private void parseEnabling(StringBuffer data) {
Pattern linePattern = Pattern.compile(ENABLING_LINE);
Matcher lineMatcher = linePattern.matcher(data.toString());
if (lineMatcher.find()) {
Pattern enabPattern = Pattern.compile(ENABLING);
Matcher enabMatcher = enabPattern.matcher(lineMatcher.group(1));
while (enabMatcher.find()) {
enablings.put(enabMatcher.group(2), enabMatcher.group(4));
// log.addText(enabMatcher.group(2) + enabMatcher.group(4));
}
}
}
private void parseAssign(StringBuffer data) {
// log.addText("check6start");
Pattern linePattern = Pattern.compile(ASSIGNMENT_LINE);
Matcher lineMatcher = linePattern.matcher(data.toString());
// Boolean temp = lineMatcher.find();
// log.addText(temp.toString());
// log.addText("check6a");
if (lineMatcher.find()) {
Pattern assignPattern = Pattern.compile(ASSIGNMENT);
// log.addText("check6a1.0");
// log.addText("check6a1 " + lineMatcher.group());
Matcher assignMatcher = assignPattern.matcher(lineMatcher.group(1));
Pattern varPattern = Pattern.compile(ASSIGN_VAR);
Pattern indetPattern = Pattern.compile(INDET_ASSIGN_VAR);
Matcher varMatcher;
// log.addText("check6ab");
while (assignMatcher.find()) {
Properties assignProp = new Properties();
Properties intProp = new Properties();
// log.addText("check6while1");
varMatcher = varPattern.matcher(assignMatcher.group(2));
if (!varMatcher.find()) {
varMatcher = indetPattern.matcher(assignMatcher.group(2));
}
else {
// log.addText("check6 else");
if (isInteger(varMatcher.group(1))) {
intProp.put(varMatcher.group(1), varMatcher.group(2));
}
else {
assignProp.put(varMatcher.group(1), varMatcher.group(2));
}
}
while (varMatcher.find()) {
// log.addText("check6while2");
if (isInteger(varMatcher.group(1))) {
intProp.put(varMatcher.group(1), varMatcher.group(2));
}
else {
assignProp.put(varMatcher.group(1), varMatcher.group(2));
}
}
if (intProp.size() > 0) {
intAssignments.put(assignMatcher.group(1), intProp);
}
if (assignProp.size() > 0) {
contAssignments.put(assignMatcher.group(1), assignProp);
}
}
}
// log.addText("check6end");
}
private void parseRateAssign(StringBuffer data) {
Pattern linePattern = Pattern.compile(RATE_ASSIGNMENT_LINE);
Matcher lineMatcher = linePattern.matcher(data.toString());
if (lineMatcher.find()) {
Pattern assignPattern = Pattern.compile(ASSIGNMENT);
Matcher assignMatcher = assignPattern.matcher(lineMatcher.group(1));
Pattern varPattern = Pattern.compile(ASSIGN_VAR);
Pattern indetPattern = Pattern.compile(INDET_ASSIGN_VAR);
Matcher varMatcher;
Matcher indetMatcher;
while (assignMatcher.find()) {
Properties assignProp = new Properties();
if (rateAssignments.containsKey(assignMatcher.group(1))) {
assignProp = rateAssignments.get(assignMatcher.group(1));
}
// log.addText("here " + assignMatcher.group(2));
varMatcher = varPattern.matcher(assignMatcher.group(2));
// log.addText(assignMatcher.group(2) + " " + indetPattern);
while (varMatcher.find()) {
if (!assignProp.containsKey(varMatcher.group(1))) {
assignProp.put(varMatcher.group(1), varMatcher.group(2));
}
// log.addText("rate " + varMatcher.group(1) + ":=" +
// varMatcher.group(2));
}
indetMatcher = indetPattern.matcher(assignMatcher.group(2));
while (indetMatcher.find()) {
assignProp.put(indetMatcher.group(1), indetMatcher.group(2));
// log.addText("indet " + indetMatcher.group(1) + ":=" +
// indetMatcher.group(2));
}
// log.addText("rates for " + assignMatcher.group(1));
// for (Object o : assignProp.keySet()) {
// log.addText((String)o + " " +
// assignProp.getProperty((String)o));
// }
rateAssignments.put(assignMatcher.group(1), assignProp);
}
}
// for (String s: rateAssignments.keySet()) {
// log.addText(s + " " + rateAssignments.get(s));
// }
}
private void parseDelayAssign(StringBuffer data) {
// log.addText("check8start");
Pattern linePattern = Pattern.compile(DELAY_LINE);
Matcher lineMatcher = linePattern.matcher(data.toString());
if (lineMatcher.find()) {
// log.addText("check8a");
Pattern delayPattern = Pattern.compile(DELAY);
Matcher delayMatcher = delayPattern.matcher(lineMatcher.group(1));
// log.addText("check8b");
while (delayMatcher.find()) {
// log.addText("check8while");
delays.put(delayMatcher.group(1), delayMatcher.group(2));
}
}
// log.addText("check8end");
}
private void parseTransitionRate(StringBuffer data) {
// log.addText("check8start");
Pattern linePattern = Pattern.compile(TRANS_RATE_LINE);
Matcher lineMatcher = linePattern.matcher(data.toString());
if (lineMatcher.find()) {
// log.addText("check8a");
Pattern delayPattern = Pattern.compile(DELAY);
Matcher delayMatcher = delayPattern.matcher(lineMatcher.group(1));
// log.addText("check8b");
while (delayMatcher.find()) {
// log.addText("check8while");
transitionRates.put(delayMatcher.group(1), delayMatcher.group(2));
}
}
// log.addText("check8end");
}
private void parseBooleanAssign(StringBuffer data) {
Pattern linePattern = Pattern.compile(BOOLEAN_LINE);
Matcher lineMatcher = linePattern.matcher(data.toString());
if (lineMatcher.find()) {
Pattern transPattern = Pattern.compile(BOOLEAN_TRANS);
Matcher transMatcher = transPattern.matcher(lineMatcher.group(1));
Pattern assignPattern = Pattern.compile(BOOLEAN_ASSIGN);
while (transMatcher.find()) {
Properties prop = new Properties();
Matcher assignMatcher = assignPattern.matcher(transMatcher.group(2));
while (assignMatcher.find()) {
prop.put(assignMatcher.group(1), assignMatcher.group(2));
}
booleanAssignments.put(transMatcher.group(1), prop);
}
}
}
private void parseIntAssign(StringBuffer data) {
// log.addText("check6start");
Properties assignProp = new Properties();
Pattern linePattern = Pattern.compile(ASSIGNMENT_LINE);
Matcher lineMatcher = linePattern.matcher(data.toString());
// Boolean temp = lineMatcher.find();
// log.addText(temp.toString());
// log.addText("check6a");
if (lineMatcher.find()) {
Pattern assignPattern = Pattern.compile(ASSIGNMENT);
// log.addText("check6a1.0");
// log.addText("check6a1 " + lineMatcher.group());
Matcher assignMatcher = assignPattern.matcher(lineMatcher.group(1));
Pattern varPattern = Pattern.compile(ASSIGN_VAR);
Pattern indetPattern = Pattern.compile(INDET_ASSIGN_VAR);
Matcher varMatcher;
// log.addText("check6ab");
while (assignMatcher.find()) {
// log.addText("check6while1");
varMatcher = varPattern.matcher(assignMatcher.group(2));
if (!varMatcher.find()) {
varMatcher = indetPattern.matcher(assignMatcher.group(2));
}
else {
varMatcher = varPattern.matcher(assignMatcher.group(2));
}
// log.addText(varMatcher.toString());
while (varMatcher.find()) {
// log.addText("check6while2");
assignProp.put(varMatcher.group(1), varMatcher.group(2));
}
// log.addText(assignMatcher.group(1) + assignProp.toString());
intAssignments.put(assignMatcher.group(1), assignProp);
}
}
// log.addText("check6end");
}
private static final String PROPERTY = "#@\\.property (\\S+?)\\n";
private static final String INPUT = "\\.inputs([[\\s[^\\n]]\\w+]*?)\\n";
private static final String OUTPUT = "\\.outputs([[\\s[^\\n]]\\w+]*?)\\n";
private static final String INIT_STATE = "#@\\.init_state \\[(\\d+)\\]";
private static final String TRANSITION = "\\.dummy([^\\n]*?)\\n";
private static final String PLACE = "\\n([\\w_\\+-/&&[^\\.#]]+ [\\w_\\+-/]+)";
private static final String CONTINUOUS = "#@\\.continuous ([.[^\\n]]+)\\n";
private static final String VARIABLES = "#@\\.variables ([.[^\\n]]+)\\n";
private static final String VARS_INIT = "#@\\.init_vals \\{([\\S[^\\}]]+?)\\}";
private static final String INIT_RATE = "#@\\.init_rates \\{([\\S[^\\}]]+?)\\}";
private static final String INIT_COND = "<(\\w+)=([\\S^>]+?)>";
// private static final String INTS_INIT = "#@\\.init_ints
// \\{([\\S[^\\}]]+?)\\}";
private static final String PLACES_LINE = "#\\|\\.places ([.[^\\n]]+)\\n";
private static final String MARKING_LINE = "\\.marking \\{(.+)\\}";
private static final String MARKING = "\\w+";
private static final String ENABLING_LINE = "#@\\.enablings \\{([.[^\\}]]+?)\\}";
private static final String ENABLING = "(<([\\S[^=]]+?)=(\\[([^\\]]+?)\\])+?>)?";
private static final String ASSIGNMENT_LINE = "#@\\.assignments \\{([.[^\\}]]+?)\\}";
// private static final String INT_ASSIGNMENT_LINE = "#@\\.int_assignments
// \\{([.[^\\}]]+?)\\}";
private static final String RATE_ASSIGNMENT_LINE = "#@\\.rate_assignments \\{([.[^\\}]]+?)\\}";
private static final String ASSIGNMENT = "<([\\S[^=]]+?)=\\[([^>]+?)\\]>";
private static final String ASSIGN_VAR = "([\\S[^:]]+?):=([\\S]+)";
private static final String INDET_ASSIGN_VAR = "([\\S[^:]]+?):=(\\[[-\\d]+,[-\\d]+\\])";
private static final String DELAY_LINE = "#@\\.delay_assignments \\{([\\S[^\\}]]+?)\\}";
private static final String DELAY = "<([\\w_]+)=(\\[\\w+,\\w+\\])>";
private static final String TRANS_RATE_LINE = "#@\\.transition_rates \\{([\\S[^\\}]]+?)\\}";
private static final String BOOLEAN_LINE = "#@\\.boolean_assignments \\{([\\S[^\\}]]+?)\\}";
private static final String BOOLEAN_TRANS = "<([\\w]+?)=([\\S[^>]]+?)>";
private static final String BOOLEAN_ASSIGN = "\\[([\\w_]+):=([\\S^\\]]+)\\]";
private static final String WORD = "(\\S+)";
} | Fixed bug at removal of transition from petri net.
| gui/src/lhpn2sbml/parser/LHPNFile.java | Fixed bug at removal of transition from petri net. | <ide><path>ui/src/lhpn2sbml/parser/LHPNFile.java
<ide> private HashMap<String, String> enablings;
<ide>
<ide> private HashMap<String, Properties> controlFlow;
<del>
<add>
<ide> private HashMap<String, Properties> controlPlaces;
<ide>
<ide> private HashMap<String, Properties> variables;
<ide> private HashMap<String, Properties> intAssignments;
<ide>
<ide> private HashMap<String, String> delays;
<del>
<add>
<ide> private HashMap<String, String> transitionRates;
<ide>
<ide> private HashMap<String, Properties> booleanAssignments;
<ide> transitionRates = new HashMap<String, String>();
<ide> booleanAssignments = new HashMap<String, Properties>();
<ide> controlFlow = new HashMap<String, Properties>();
<del> controlPlaces= new HashMap<String, Properties>();
<add> controlPlaces = new HashMap<String, Properties>();
<ide> variables = new HashMap<String, Properties>();
<ide> integers = new HashMap<String, String>();
<ide> rateAssignments = new HashMap<String, Properties>();
<ide> transitionRates = new HashMap<String, String>();
<ide> booleanAssignments = new HashMap<String, Properties>();
<ide> controlFlow = new HashMap<String, Properties>();
<del> controlPlaces= new HashMap<String, Properties>();
<add> controlPlaces = new HashMap<String, Properties>();
<ide> variables = new HashMap<String, Properties>();
<ide> integers = new HashMap<String, String>();
<ide> rateAssignments = new HashMap<String, Properties>();
<ide> flag = false;
<ide> for (String s : contAssignments.keySet()) {
<ide> Properties prop = contAssignments.get(s);
<del> //log.addText(prop.toString());
<add> // log.addText(prop.toString());
<ide> if (!prop.isEmpty()) {
<ide> if (!flag) {
<ide> buffer.append("#@.assignments {");
<ide> parseBooleanAssign(data);
<ide> // System.out.println("check11");
<ide> // log.addText("check0");
<del> //log.addText(intAssignments.toString());
<add> // log.addText(intAssignments.toString());
<ide> }
<ide> catch (Exception e) {
<ide> e.printStackTrace();
<ide> }
<ide>
<ide> public boolean containsFlow(String place) {
<del> if (controlFlow.containsKey(place)) {
<del> if (!controlFlow.get(place).isEmpty()) {
<del> return true;
<del> }
<add> if (controlFlow.containsKey(place) && controlFlow.get(place) != null) {
<add> if (!controlFlow.get(place).isEmpty()) {
<add> return true;
<add> }
<ide> }
<ide> for (String s : controlFlow.keySet()) {
<del> Properties prop = controlFlow.get(s);
<del> if (prop.containsKey("to")) {
<del> String[] toList = prop.get("to").toString().split(" ");
<del> for (int i = 0; i < toList.length; i++) {
<del> if (toList[i].equals(place)) {
<del> return true;
<del> }
<del> }
<del> }
<del> if (prop.containsKey("from")) {
<del> String[] fromList = prop.get("from").toString().split(" ");
<del> for (int i = 0; i < fromList.length; i++) {
<del> if (fromList[i].equals(place)) {
<del> return true;
<add> if (controlFlow.get(s) != null) {
<add> Properties prop = controlFlow.get(s);
<add> if (prop.containsKey("to")) {
<add> String[] toList = prop.get("to").toString().split(" ");
<add> for (int i = 0; i < toList.length; i++) {
<add> if (toList[i].equals(place)) {
<add> return true;
<add> }
<add> }
<add> }
<add> if (prop.containsKey("from")) {
<add> String[] fromList = prop.get("from").toString().split(" ");
<add> for (int i = 0; i < fromList.length; i++) {
<add> if (fromList[i].equals(place)) {
<add> return true;
<add> }
<ide> }
<ide> }
<ide> }
<ide> return false;
<ide> }
<ide>
<del> public void addTransition(String name, String delay, String transitionRate, Properties rateAssign,
<del> Properties booleanAssign, String enabling) {
<add> public void addTransition(String name, String delay, String transitionRate,
<add> Properties rateAssign, Properties booleanAssign, String enabling) {
<ide> addTransition(name);
<ide> delays.put(name, delay);
<ide> transitionRates.put(name, transitionRate);
<ide> if (contAssignments.get(transition) != null) {
<ide> prop = contAssignments.get(transition);
<ide> }
<del> //System.out.println("here " + transition + name + value);
<add> // System.out.println("here " + transition + name + value);
<ide> prop.setProperty(name, value);
<del> //log.addText("lhpn " + prop.toString());
<add> // log.addText("lhpn " + prop.toString());
<ide> contAssignments.put(transition, prop);
<ide> }
<ide>
<ide> if (name != null && prop.containsKey(name)) {
<ide> prop.remove(name);
<ide> }
<del> //log.addText("lhpn " + prop.toString());
<add> // log.addText("lhpn " + prop.toString());
<ide> contAssignments.put(transition, prop);
<ide> }
<ide> }
<ide> // log.addText(transition + delay);
<ide> delays.put(transition, delay);
<ide> }
<del>
<add>
<ide> public void changeTransitionRate(String transition, String rate) {
<ide> if (transitionRates.containsKey(transition)) {
<ide> transitionRates.remove(transition);
<ide> public String getDelay(String var) {
<ide> return delays.get(var);
<ide> }
<del>
<add>
<ide> public HashMap<String, String> getTransitionRates() {
<ide> return transitionRates;
<ide> }
<ide> public Properties getContVars(String trans) {
<ide> Properties contVars = new Properties();
<ide> contVars = contAssignments.get(trans);
<del> //log.addText("lhpn " + contVars.toString());
<add> // log.addText("lhpn " + contVars.toString());
<ide> return contVars;
<ide> }
<ide>
<ide> public String getContAssign(String transition, String var) {
<ide> if (contAssignments.containsKey(transition) && var != null) {
<ide> Properties prop = contAssignments.get(transition);
<del> //log.addText("lhpn " + prop.toString());
<add> // log.addText("lhpn " + prop.toString());
<ide> if (prop.containsKey(var)) {
<ide> return prop.getProperty(var);
<ide> }
<ide> }
<ide> // log.addText("check3end");
<ide> }
<del>
<add>
<ide> private void parsePlaces(StringBuffer data) {
<ide> Pattern linePattern = Pattern.compile(PLACES_LINE);
<ide> Matcher lineMatcher = linePattern.matcher(data.toString());
<ide> if (lineMatcher.find()) {
<del> //log.addText(lineMatcher.group());
<add> // log.addText(lineMatcher.group());
<ide> Pattern markPattern = Pattern.compile(MARKING);
<ide> Matcher markMatcher = markPattern.matcher(lineMatcher.group(1));
<ide> while (markMatcher.find()) {
<ide> }
<ide> // log.addText("check8end");
<ide> }
<del>
<add>
<ide> private void parseTransitionRate(StringBuffer data) {
<ide> // log.addText("check8start");
<ide> Pattern linePattern = Pattern.compile(TRANS_RATE_LINE);
<ide> // \\{([\\S[^\\}]]+?)\\}";
<ide>
<ide> private static final String PLACES_LINE = "#\\|\\.places ([.[^\\n]]+)\\n";
<del>
<add>
<ide> private static final String MARKING_LINE = "\\.marking \\{(.+)\\}";
<ide>
<ide> private static final String MARKING = "\\w+";
<ide> private static final String DELAY_LINE = "#@\\.delay_assignments \\{([\\S[^\\}]]+?)\\}";
<ide>
<ide> private static final String DELAY = "<([\\w_]+)=(\\[\\w+,\\w+\\])>";
<del>
<add>
<ide> private static final String TRANS_RATE_LINE = "#@\\.transition_rates \\{([\\S[^\\}]]+?)\\}";
<ide>
<ide> private static final String BOOLEAN_LINE = "#@\\.boolean_assignments \\{([\\S[^\\}]]+?)\\}"; |
|
Java | bsd-3-clause | c6437debb4ff61877488d792022d765085a4ce8e | 0 | frc-4931/2014-Robot,frc-4931/2014-Robot,frc-4931/2014-Robot | CompetitionRobot/src/org/frc4931/robot/Toggable.java | package org.frc4931.robot;
public interface Toggable {
public void setStateOne();
public void setStateTwo();
public void getState();
}
| Remove abandoned Toggable.java
| CompetitionRobot/src/org/frc4931/robot/Toggable.java | Remove abandoned Toggable.java | <ide><path>ompetitionRobot/src/org/frc4931/robot/Toggable.java
<del>package org.frc4931.robot;
<del>
<del>public interface Toggable {
<del> public void setStateOne();
<del> public void setStateTwo();
<del> public void getState();
<del>} |
||
JavaScript | mit | fdd46f147961249783fc1bcb77765c018e4eeacf | 0 | aitorcarrera/ngbp-material,aitorcarrera/ngbp-material | module.exports = function ( karma ) {
karma.set({
/**
* From where to look for files, starting with the location of this file.
*/
basePath: '../',
/**
* This is the list of file patterns to load into the browser during testing.
*/
files: [
<% scripts.forEach( function ( file ) { %>'<%= file %>',
<% }); %>
'src/**/*.js',
'src/**/*.coffee',
],
exclude: [
'src/assets/**/*.js'
],
frameworks: [ 'jasmine' ],
plugins: [ 'karma-jasmine', 'karma-firefox-launcher', 'karma-coffee-preprocessor' ],
preprocessors: {
'**/*.coffee': 'coffee',
},
/**
* How to report, by default.
*/
reporters: 'dots',
/**
* On which port should the browser connect, on which port is the test runner
* operating, and what is the URL path for the browser to use.
*/
port: 9018,
runnerPort: 9100,
urlRoot: '/',
/**
* Disable file watching by default.
*/
autoWatch: false,
/**
* The list of browsers to launch to test on. This includes only "Firefox" by
* default, but other browser names include:
* Chrome, ChromeCanary, Firefox, Opera, Safari, PhantomJS
*
* Note that you can also use the executable name of the browser, like "chromium"
* or "firefox", but that these vary based on your operating system.
*
* You may also leave this blank and manually navigate your browser to
* http://localhost:9018/ when you're running tests. The window/tab can be left
* open and the tests will automatically occur there during the build. This has
* the aesthetic advantage of not launching a browser every time you save.
*/
browsers: [
'PhantomJS'
]
});
};
| karma/karma-unit.tpl.js | module.exports = function ( karma ) {
karma.set({
/**
* From where to look for files, starting with the location of this file.
*/
basePath: '../',
/**
* This is the list of file patterns to load into the browser during testing.
*/
files: [
<% scripts.forEach( function ( file ) { %>'<%= file %>',
<% }); %>
'src/**/*.js',
'src/**/*.coffee',
],
exclude: [
'src/assets/**/*.js'
],
frameworks: [ 'jasmine' ],
plugins: [ 'karma-jasmine', 'karma-firefox-launcher', 'karma-coffee-preprocessor' ],
preprocessors: {
'**/*.coffee': 'coffee',
},
/**
* How to report, by default.
*/
reporters: 'dots',
/**
* On which port should the browser connect, on which port is the test runner
* operating, and what is the URL path for the browser to use.
*/
port: 9018,
runnerPort: 9100,
urlRoot: '/',
/**
* Disable file watching by default.
*/
autoWatch: false,
/**
* The list of browsers to launch to test on. This includes only "Firefox" by
* default, but other browser names include:
* Chrome, ChromeCanary, Firefox, Opera, Safari, PhantomJS
*
* Note that you can also use the executable name of the browser, like "chromium"
* or "firefox", but that these vary based on your operating system.
*
* You may also leave this blank and manually navigate your browser to
* http://localhost:9018/ when you're running tests. The window/tab can be left
* open and the tests will automatically occur there during the build. This has
* the aesthetic advantage of not launching a browser every time you save.
*/
browsers: [
'Firefox'
]
});
};
| Set default karma browser to PhantomJS
| karma/karma-unit.tpl.js | Set default karma browser to PhantomJS | <ide><path>arma/karma-unit.tpl.js
<ide> * the aesthetic advantage of not launching a browser every time you save.
<ide> */
<ide> browsers: [
<del> 'Firefox'
<add> 'PhantomJS'
<ide> ]
<ide> });
<ide> }; |
|
JavaScript | mit | 0524e9ef11c12365ff071ddf0444eefd701c93b0 | 0 | haganbt/DataSift-UG-Filter-Workflow | var ds_user = '';
var ds_key = '';
//init
$(function() {
NProgress.configure({
trickle: false
});
// cookies
if($.cookie('un') && $.cookie('key')){
$('#un').val($.cookie('un')) === $.cookie('un');
$('#key').val($.cookie('key')) === $.cookie('key');
}
$('#jcsdl-edit').jcsdlGui({
save : function(code) {
$('#intro').text('Estimating data volume...');
log('DEBUG: CSDL generated: ' + code);
// validate the DS creds
if(validateCreds() === true){
doCompile(code);
}
$('#jcsdl-edit').slideUp(300);
},
hideTargets : ['twitter.status', 'twitter.place', 'twitter.retweet', 'twitter.mention_ids', 'twitter.domains', 'twitter.in_reply_to_screen_name', 'twitter.links', 'twitter.user', 'twitter.retweeted', 'interaction', '2ch', 'lexisnexis', 'intensedebate', 'sinaweibo', 'tencentweibo', 'tumblr', 'facebook_page', 'googleplus','instagram', 'wordpress', 'wikipedia', 'yammer', 'imdb','facebook', '2channel', 'myspace', 'digg', 'amazon', 'blog', 'board', 'bitly', 'dailymotion', 'flickr', 'newscred', 'reddit', 'topix', 'video', 'youtube', 'imdb.author', 'imdb.type', 'imdb.contenttype', 'imdb.thread']
});
});
/*
* validateCreds - validate the user has entered
* DS creds, and set cookies.
*
* @return boolean
*
*/
function validateCreds(){
ds_user = $.trim($('#un').val());
ds_key = $.trim($('#key').val());
if(ds_user ==='' || ds_key === ''){
alert('Please enter a DataSift username and API key.');
return false;
}
// set cookie
$.cookie('un', ds_user, { expires: 60 });
$.cookie('key', ds_key, { expires: 60 });
return true;
};
/*
* initPreview - build params and calls
* historic preview
*
*/
function initPreview (hash){
var params = {};
params.start = Math.floor((Date.now() / 1000) - (60 * 60 * 2)); // start is 2 hours ago
params.end = Math.floor((Date.now() / 1000) - (60 * 60 * 2)); // end is 2 hours ago
params.hash = hash;
params.sources = 'twitter';
params.parameters = 'interaction.id,targetVol';
doCreate(serialize(params));
}
/*
* doCompile
*
* @return void
*
*/
function doCompile (csdl) {
log('DEBUG: Compiling CSDL...');
jQuery.ajax({
type: "POST",
url: "http://dsfilter.herokuapp.com/api/compile",
contentType: "application/json; charset=utf-8",
data: 'csdl='+encodeURIComponent(csdl),
dataType: "json",
headers: {
"Authorization": ds_user + ':' + ds_key
},
success: function (data, status, jqXHR) {
log('DEBUG: Compile success - ' + JSON.stringify(jqXHR.responseJSON));
if(jqXHR.responseJSON.hash && jqXHR.responseJSON.hash !== undefined){
// start historic preview
initPreview(jqXHR.responseJSON.hash);
} else {
log('ERROR: Compile failed - no hash received: ' + JSON.stringify(jqXHR.responseJSON));
}
},
error: function (jqXHR, status) {
log('ERROR: Compile failed: ' + JSON.stringify(jqXHR.responseJSON));
}
});
}
/*
* doCreate
*
* @return void
*
*/
function doCreate (params) {
log('DEBUG: Staring preview...');
jQuery.ajax({
type: "POST",
url: "http://dsfilter.herokuapp.com/api/create",
contentType: "application/json; charset=utf-8",
data: params,
dataType: "json",
headers: {
"Authorization": ds_user + ':' + ds_key
},
success: function (data, status, jqXHR) {
log('DEBUG: Historic preview create success: ' + JSON.stringify(jqXHR.responseJSON));
NProgress.start();
log('DEBUG: Waiting for preview to complete...');
getPreview(jqXHR.responseJSON.id);
},
error: function (jqXHR, status) {
log('ERROR: historic preview create failed: ' + JSON.stringify(jqXHR.responseJSON));
}
});
}
/*
* log
*
* @return void
*
*/
function log(update){
$('#debug').val($('#debug').val() + "\n" + update);
}
/*
* serialize - obj to URI encoded string
*
* @param - obj - {foo: "hi there", bar: "100%" }
* @return - string - foo=hi%20there&bar=100%25
*/
function serialize(obj) {
var str = [];
for(var p in obj) {
if (obj.hasOwnProperty(p)) {
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
}
}
return str.join("&");
}
/*
* getPreview - poll historic preview
* until a 200 is received.
*
* @param - string
*
*/
function getPreview (id) {
var intervalID = setInterval(function() {
jQuery.ajax({
type: "GET",
url: "http://dsfilter.herokuapp.com/api/preview/"+id,
contentType: "application/json; charset=utf-8",
dataType: "json",
headers: {
"Authorization": ds_user + ':' + ds_key
},
success: function (data, status, jqXHR) {
//log('DEBUG: Preview status: ' + JSON.stringify(jqXHR.responseJSON.progress));
NProgress.set(jqXHR.responseJSON.progress / 100);
if(jqXHR.status === 200) {
log('DEBUG: Preview complete: '+ JSON.stringify(jqXHR.responseJSON));
clearInterval(intervalID);
NProgress.done();
calcStats(jqXHR.responseJSON);
}
},
error: function (jqXHR, status) {
log('ERROR: failed to get preview status.');
}
});
}, 4000);
}
/*
* calcStats - calc and display results from
* historic preview output.
*
* @param obj
* @return void
*
*/
function calcStats(obj){
var hour = JSON.parse(obj.data[0].summary.count);
var minute = ((hour / 60) * 100).toFixed(0);
$('#intro').text('Estimated volume: ' + minute + ' per minute.');
}
| public/js/app.js | var ds_user = '';
var ds_key = '';
//init
$(function() {
NProgress.configure({
trickle: false
});
// cookies
if($.cookie('un') && $.cookie('key')){
$('#un').val($.cookie('un')) === $.cookie('un');
$('#key').val($.cookie('key')) === $.cookie('key');
}
$('#jcsdl-edit').jcsdlGui({
save : function(code) {
$('#intro').text('Estimating data volume...');
log('DEBUG: CSDL generated: ' + code);
// validate the DS creds
if(validateCreds() === true){
doCompile(code);
}
$('#jcsdl-edit').slideUp(300);
},
hideTargets : ['twitter.status', 'twitter.place', 'twitter.retweet', 'twitter.mention_ids', 'twitter.domains', 'twitter.in_reply_to_screen_name', 'twitter.links', 'twitter.user', 'twitter.retweeted', 'interaction', '2ch', 'lexisnexis', 'intensedebate', 'sinaweibo', 'tencentweibo', 'tumblr', 'facebook_page', 'googleplus','instagram', 'wordpress', 'wikipedia', 'yammer', 'imdb','facebook', '2channel', 'myspace', 'digg', 'amazon', 'blog', 'board', 'bitly', 'dailymotion', 'flickr', 'newscred', 'reddit', 'topix', 'video', 'youtube', 'imdb.author', 'imdb.type', 'imdb.contenttype', 'imdb.thread']
});
});
/*
* validateCreds - validate the user has entered
* DS creds, and set cookies.
*
* @return boolean
*
*/
function validateCreds(){
ds_user = $.trim($('#un').val());
ds_key = $.trim($('#key').val());
if(ds_user ==='' || ds_key === ''){
alert('Please enter a DataSift username and API key.');
return false;
}
// set cookie
$.cookie('un', ds_user, { expires: 60 });
$.cookie('key', ds_key, { expires: 60 });
return true;
};
/*
* initPreview - build params and calls
* historic preview
*
*/
function initPreview (hash){
var params = {};
params.start = Math.floor((Date.now() / 1000) - (60 * 60 * 2)); // start is 2 hours ago
params.end = Math.floor((Date.now() / 1000) - (60 * 60 * 2)); // end is 2 hours ago
params.hash = hash;
params.sources = 'twitter';
params.parameters = 'interaction.id,targetVol';
doCreate(serialize(params));
}
/*
* doCompile
*
* @return void
*
*/
function doCompile (csdl) {
log('DEBUG: Compiling CSDL...');
jQuery.ajax({
type: "POST",
url: "http://localhost:3000/api/compile",
contentType: "application/json; charset=utf-8",
data: 'csdl='+encodeURIComponent(csdl),
dataType: "json",
headers: {
"Authorization": ds_user + ':' + ds_key
},
success: function (data, status, jqXHR) {
log('DEBUG: Compile success - ' + JSON.stringify(jqXHR.responseJSON));
if(jqXHR.responseJSON.hash && jqXHR.responseJSON.hash !== undefined){
// start historic preview
initPreview(jqXHR.responseJSON.hash);
} else {
log('ERROR: Compile failed - no hash received: ' + JSON.stringify(jqXHR.responseJSON));
}
},
error: function (jqXHR, status) {
log('ERROR: Compile failed: ' + JSON.stringify(jqXHR.responseJSON));
}
});
}
/*
* doCreate
*
* @return void
*
*/
function doCreate (params) {
log('DEBUG: Staring preview...');
jQuery.ajax({
type: "POST",
url: "http://localhost:3000/api/create",
contentType: "application/json; charset=utf-8",
data: params,
dataType: "json",
headers: {
"Authorization": ds_user + ':' + ds_key
},
success: function (data, status, jqXHR) {
log('DEBUG: Historic preview create success: ' + JSON.stringify(jqXHR.responseJSON));
NProgress.start();
log('DEBUG: Waiting for preview to complete...');
getPreview(jqXHR.responseJSON.id);
},
error: function (jqXHR, status) {
log('ERROR: historic preview create failed: ' + JSON.stringify(jqXHR.responseJSON));
}
});
}
/*
* log
*
* @return void
*
*/
function log(update){
$('#debug').val($('#debug').val() + "\n" + update);
}
/*
* serialize - obj to URI encoded string
*
* @param - obj - {foo: "hi there", bar: "100%" }
* @return - string - foo=hi%20there&bar=100%25
*/
function serialize(obj) {
var str = [];
for(var p in obj) {
if (obj.hasOwnProperty(p)) {
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
}
}
return str.join("&");
}
/*
* getPreview - poll historic preview
* until a 200 is received.
*
* @param - string
*
*/
function getPreview (id) {
var intervalID = setInterval(function() {
jQuery.ajax({
type: "GET",
url: "http://localhost:3000/api/preview/"+id,
contentType: "application/json; charset=utf-8",
dataType: "json",
headers: {
"Authorization": ds_user + ':' + ds_key
},
success: function (data, status, jqXHR) {
//log('DEBUG: Preview status: ' + JSON.stringify(jqXHR.responseJSON.progress));
NProgress.set(jqXHR.responseJSON.progress / 100);
if(jqXHR.status === 200) {
log('DEBUG: Preview complete: '+ JSON.stringify(jqXHR.responseJSON));
clearInterval(intervalID);
NProgress.done();
calcStats(jqXHR.responseJSON);
}
},
error: function (jqXHR, status) {
log('ERROR: failed to get preview status.');
}
});
}, 4000);
}
/*
* calcStats - calc and display results from
* historic preview output.
*
* @param obj
* @return void
*
*/
function calcStats(obj){
var hour = JSON.parse(obj.data[0].summary.count);
var minute = ((hour / 60) * 100).toFixed(0);
$('#intro').text('Estimated volume: ' + minute + ' per minute.');
}
| Heroku routes.
| public/js/app.js | Heroku routes. | <ide><path>ublic/js/app.js
<ide>
<ide> jQuery.ajax({
<ide> type: "POST",
<del> url: "http://localhost:3000/api/compile",
<add> url: "http://dsfilter.herokuapp.com/api/compile",
<ide> contentType: "application/json; charset=utf-8",
<ide> data: 'csdl='+encodeURIComponent(csdl),
<ide> dataType: "json",
<ide>
<ide> jQuery.ajax({
<ide> type: "POST",
<del> url: "http://localhost:3000/api/create",
<add> url: "http://dsfilter.herokuapp.com/api/create",
<ide> contentType: "application/json; charset=utf-8",
<ide> data: params,
<ide> dataType: "json",
<ide> var intervalID = setInterval(function() {
<ide> jQuery.ajax({
<ide> type: "GET",
<del> url: "http://localhost:3000/api/preview/"+id,
<add> url: "http://dsfilter.herokuapp.com/api/preview/"+id,
<ide> contentType: "application/json; charset=utf-8",
<ide> dataType: "json",
<ide> headers: { |
|
Java | apache-2.0 | 69885c64b60985a04239aa37b72469c8e6b86813 | 0 | gfelisberto/asterisk-java,010Minds/asterisk-java,thuliumcc/asterisk-java,elara-leitstellentechnik/asterisk-java,milesje/asterisk-java,jaunis/asterisk-java,gfelisberto/asterisk-java,michaelrice/asterisk-java,010Minds/asterisk-java,jaunis/asterisk-java,filius/asterisk-java,scgm11/asterisk-java,thuliumcc/asterisk-java,polachok/asterisk-java,trulywireless/asterisk-java,gfelisberto/asterisk-java,trulywireless/asterisk-java,jaunis/asterisk-java,filius/asterisk-java,scgm11/asterisk-java,pk1057/asterisk-java,seanbright/asterisk-java,asterisk-java/asterisk-java,trulywireless/asterisk-java,gfelisberto/asterisk-java,milesje/asterisk-java,alexscott/asterisk-java,michaelrice/asterisk-java,yamajun/asterisk-java,milesje/asterisk-java,thuliumcc/asterisk-java,alexscott/asterisk-java,alexscott/asterisk-java,yamajun/asterisk-java,michaelrice/asterisk-java,polachok/asterisk-java,filius/asterisk-java,thuliumcc/asterisk-java,filius/asterisk-java,seanbright/asterisk-java,elara-leitstellentechnik/asterisk-java,pk1057/asterisk-java,polachok/asterisk-java,asterisk-java/asterisk-java,michaelrice/asterisk-java,elara-leitstellentechnik/asterisk-java,trulywireless/asterisk-java,xvart/asterisk-java,jaunis/asterisk-java,elara-leitstellentechnik/asterisk-java,010Minds/asterisk-java,pk1057/asterisk-java,xvart/asterisk-java,polachok/asterisk-java | /*
* Copyright 2004-2006 Stefan Reuter
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.asteriskjava.fastagi;
import java.io.IOException;
import org.asteriskjava.fastagi.command.VerboseCommand;
import org.asteriskjava.fastagi.impl.AgiChannelImpl;
import org.asteriskjava.fastagi.impl.AgiReaderImpl;
import org.asteriskjava.fastagi.impl.AgiWriterImpl;
import org.asteriskjava.io.SocketConnectionFacade;
import org.asteriskjava.util.Log;
import org.asteriskjava.util.LogFactory;
/**
* An AgiConnectionHandler is created and run by the AgiServer whenever a new
* socket connection from an Asterisk Server is received.<br>
* It reads the request using an AgiReader and runs the AgiScript configured to
* handle this type of request. Finally it closes the socket connection.
*
* @author srt
* @version $Id$
*/
public class AgiConnectionHandler implements Runnable
{
private final Log logger = LogFactory.getLog(getClass());
private static final ThreadLocal<AgiChannel> channel = new ThreadLocal<AgiChannel>();
/**
* The socket connection.
*/
private SocketConnectionFacade socket;
/**
* The strategy to use to determine which script to run.
*/
private MappingStrategy mappingStrategy;
/**
* Creates a new AGIConnectionHandler to handle the given socket connection.
*
* @param socket the socket connection to handle.
* @param mappingStrategy the strategy to use to determine which script to
* run.
*/
public AgiConnectionHandler(SocketConnectionFacade socket,
MappingStrategy mappingStrategy)
{
this.socket = socket;
this.mappingStrategy = mappingStrategy;
}
protected AgiReader createReader()
{
return new AgiReaderImpl(socket);
}
protected AgiWriter createWriter()
{
return new AgiWriterImpl(socket);
}
public void run()
{
try
{
AgiReader reader;
AgiWriter writer;
AgiRequest request;
AgiChannel channel;
AgiScript script;
Thread thread;
String threadName;
reader = createReader();
writer = createWriter();
request = reader.readRequest();
channel = new AgiChannelImpl(writer, reader);
script = mappingStrategy.determineScript(request);
thread = Thread.currentThread();
threadName = thread.getName();
AgiConnectionHandler.channel.set(channel);
if (script != null)
{
logger.info("Begin AGIScript " + script.getClass().getName()
+ " on " + threadName);
script.service(request, channel);
logger.info("End AGIScript " + script.getClass().getName()
+ " on " + threadName);
}
else
{
String error;
error = "No script configured for URL '"
+ request.getRequestURL() + "' (script '"
+ request.getScript() + "')";
logger.error(error);
try
{
channel.sendCommand(new VerboseCommand(error, 1));
}
catch (AgiException e)
{
// do nothing
}
}
}
catch (AgiException e)
{
logger.error("AgiException while handling request", e);
}
catch (Exception e)
{
logger.error("Unexpected Exception while handling request", e);
}
finally
{
AgiConnectionHandler.channel.set(null);
try
{
socket.close();
}
catch (IOException e)
{
// swallow
}
}
}
/**
* Returns the AGIChannel associated with the current thread.
*
* @return the AGIChannel associated with the current thread or
* <code>null</code> if none is associated.
*/
static AgiChannel getChannel()
{
return AgiConnectionHandler.channel.get();
}
}
| src/main/java/org/asteriskjava/fastagi/AgiConnectionHandler.java | /*
* Copyright 2004-2006 Stefan Reuter
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.asteriskjava.fastagi;
import java.io.IOException;
import org.asteriskjava.fastagi.command.VerboseCommand;
import org.asteriskjava.fastagi.impl.AgiChannelImpl;
import org.asteriskjava.fastagi.impl.AgiReaderImpl;
import org.asteriskjava.fastagi.impl.AgiWriterImpl;
import org.asteriskjava.io.SocketConnectionFacade;
import org.asteriskjava.util.Log;
import org.asteriskjava.util.LogFactory;
/**
* An AgiConnectionHandler is created and run by the AgiServer whenever a new
* socket connection from an Asterisk Server is received.<br>
* It reads the request using an AgiReader and runs the AgiScript configured to
* handle this type of request. Finally it closes the socket connection.
*
* @author srt
* @version $Id$
*/
public class AgiConnectionHandler implements Runnable
{
private final Log logger = LogFactory.getLog(getClass());
private static final ThreadLocal<AgiChannel> channel = new ThreadLocal<AgiChannel>();
/**
* The socket connection.
*/
private SocketConnectionFacade socket;
/**
* The strategy to use to determine which script to run.
*/
private MappingStrategy mappingStrategy;
/**
* Creates a new AGIConnectionHandler to handle the given socket connection.
*
* @param socket the socket connection to handle.
* @param mappingStrategy the strategy to use to determine which script to
* run.
*/
public AgiConnectionHandler(SocketConnectionFacade socket,
MappingStrategy mappingStrategy)
{
this.socket = socket;
this.mappingStrategy = mappingStrategy;
}
protected AgiReader createReader()
{
return new AgiReaderImpl(socket);
}
protected AgiWriter createWriter()
{
return new AgiWriterImpl(socket);
}
public void run()
{
try
{
AgiReader reader;
AgiWriter writer;
AgiRequest request;
AgiChannel channel;
AgiScript script;
Thread thread;
String threadName;
reader = createReader();
writer = createWriter();
request = reader.readRequest();
channel = new AgiChannelImpl(writer, reader);
script = mappingStrategy.determineScript(request);
thread = Thread.currentThread();
threadName = thread.getName();
AgiConnectionHandler.channel.set(channel);
if (script != null)
{
logger.info("Begin AGIScript " + script.getClass().getName()
+ " on " + threadName);
script.service(request, channel);
logger.info("End AGIScript " + script.getClass().getName()
+ " on " + threadName);
}
else
{
String error;
error = "No script configured for URL '"
+ request.getRequestURL() + "' (script '"
+ request.getScript() + "')";
logger.error(error);
try
{
channel.sendCommand(new VerboseCommand(error, 1));
}
catch (AgiException e)
{
// do nothing
}
}
}
catch (AgiException e)
{
logger.error("AgiException while handling request", e);
}
catch (Exception e)
{
logger.error("Unexpected Exception while handling request", e);
}
finally
{
AgiConnectionHandler.channel.set(null);
try
{
socket.close();
}
catch (IOException e)
{
// swallow
}
}
}
/**
* Returns the AGIChannel associated with the current thread.<br>
*
* @return the AGIChannel associated with the current thread or
* <code>null</code> if none is associated.
*/
static AgiChannel getChannel()
{
return (AgiChannel) AgiConnectionHandler.channel.get();
}
}
| Removed explicit type cast that is no longer needed
| src/main/java/org/asteriskjava/fastagi/AgiConnectionHandler.java | Removed explicit type cast that is no longer needed | <ide><path>rc/main/java/org/asteriskjava/fastagi/AgiConnectionHandler.java
<ide> import org.asteriskjava.io.SocketConnectionFacade;
<ide> import org.asteriskjava.util.Log;
<ide> import org.asteriskjava.util.LogFactory;
<del>
<del>
<ide>
<ide> /**
<ide> * An AgiConnectionHandler is created and run by the AgiServer whenever a new
<ide> }
<ide>
<ide> /**
<del> * Returns the AGIChannel associated with the current thread.<br>
<add> * Returns the AGIChannel associated with the current thread.
<ide> *
<ide> * @return the AGIChannel associated with the current thread or
<ide> * <code>null</code> if none is associated.
<ide> */
<ide> static AgiChannel getChannel()
<ide> {
<del> return (AgiChannel) AgiConnectionHandler.channel.get();
<add> return AgiConnectionHandler.channel.get();
<ide> }
<ide> } |
|
Java | apache-2.0 | 9db21707a8b51cbfb8a6869a44edafe64cd0c602 | 0 | janinko/dependency-analysis,janinko/dependency-analysis,janinko/dependency-analysis,janinko/dependency-analysis,janinko/dependency-analysis,project-ncl/dependency-analysis,project-ncl/dependency-analysis,project-ncl/dependency-analysis | package org.jboss.da.reports.api;
import org.jboss.da.model.rest.GAV;
import java.util.HashSet;
import java.util.Set;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
@EqualsAndHashCode
public class BuiltReportModule {
public BuiltReportModule(GAV gav) {
this.groupId = gav.getGroupId();
this.artifactId = gav.getArtifactId();
this.version = gav.getVersion();
}
@Getter
private String groupId;
@Getter
private String artifactId;
@Getter
private String version;
@Getter
@Setter
private String builtVersion;
@Getter
@Setter
private Set<String> availableVersions = new HashSet<>();
}
| reports-backend/src/main/java/org/jboss/da/reports/api/BuiltReportModule.java | package org.jboss.da.reports.api;
import org.jboss.da.model.rest.GAV;
import java.util.HashSet;
import java.util.Set;
import lombok.Getter;
import lombok.Setter;
public class BuiltReportModule {
public BuiltReportModule(GAV gav) {
this.groupId = gav.getGroupId();
this.artifactId = gav.getArtifactId();
this.version = gav.getVersion();
}
@Getter
private String groupId;
@Getter
private String artifactId;
@Getter
private String version;
@Getter
@Setter
private String builtVersion;
@Getter
@Setter
private Set<String> availableVersions = new HashSet<>();
}
| [NCL-2011] Endpoint for analyzing built artifacts contains duplicates
| reports-backend/src/main/java/org/jboss/da/reports/api/BuiltReportModule.java | [NCL-2011] Endpoint for analyzing built artifacts contains duplicates | <ide><path>eports-backend/src/main/java/org/jboss/da/reports/api/BuiltReportModule.java
<ide> import java.util.HashSet;
<ide> import java.util.Set;
<ide>
<add>import lombok.EqualsAndHashCode;
<ide> import lombok.Getter;
<ide> import lombok.Setter;
<ide>
<add>@EqualsAndHashCode
<ide> public class BuiltReportModule {
<ide>
<ide> public BuiltReportModule(GAV gav) { |
|
Java | apache-2.0 | 6e04365fe6f17d74c8726981561b59b1a6b3d62c | 0 | CrazyOrr/NewMoviesExpress | package com.github.crazyorr.newmoviesexpress;
import android.app.Application;
import com.facebook.stetho.Stetho;
import timber.log.Timber;
/**
* Created by wanglei02 on 2016/3/4.
*/
public class MainApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
Stetho.initializeWithDefaults(this);
Timber.plant(new Timber.DebugTree());
}
}
| app/src/main/java/com/github/crazyorr/newmoviesexpress/MainApplication.java | package com.github.crazyorr.newmoviesexpress;
import android.app.Application;
import com.facebook.stetho.Stetho;
/**
* Created by wanglei02 on 2016/3/4.
*/
public class MainApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
Stetho.initializeWithDefaults(this);
}
}
| Plant Timber tree.
| app/src/main/java/com/github/crazyorr/newmoviesexpress/MainApplication.java | Plant Timber tree. | <ide><path>pp/src/main/java/com/github/crazyorr/newmoviesexpress/MainApplication.java
<ide> import android.app.Application;
<ide>
<ide> import com.facebook.stetho.Stetho;
<add>
<add>import timber.log.Timber;
<ide>
<ide> /**
<ide> * Created by wanglei02 on 2016/3/4.
<ide> public void onCreate() {
<ide> super.onCreate();
<ide> Stetho.initializeWithDefaults(this);
<add> Timber.plant(new Timber.DebugTree());
<ide> }
<ide> } |
|
JavaScript | apache-2.0 | 28a47c64d243583fdfd0597dcd1ed95c45872b33 | 0 | phonegap-build/cordova-lib,surajpindoria/cordova-lib,stevengill/cordova-lib,csantanapr/cordova-lib,marcuspridham/cordova-lib,driftyco/cordova-lib,jasongin/cordova-lib,surajpindoria/cordova-lib,AxelNennker/cordova-lib,jasongin/cordova-lib,stevengill/cordova-lib,shazron/cordova-lib,tony--/cordova-lib,phonegap-build/cordova-lib,surajpindoria/cordova-lib,shazron/cordova-lib,ogoguel/cordova-lib,csantanapr/cordova-lib,csantanapr/cordova-lib,filmaj/cordova-lib,ktop/cordova-lib,vladimir-kotikov/cordova-lib,tripodsan/cordova-lib,shazron/cordova-lib,phonegap-build/cordova-lib,carynbear/cordova-lib,purplecabbage/cordova-lib,stevengill/cordova-lib,shazron/cordova-lib,purplecabbage/cordova-lib,matrosov-nikita/cordova-lib,vladimir-kotikov/cordova-lib,vladimir-kotikov/cordova-lib,purplecabbage/cordova-lib,surajpindoria/cordova-lib,ogoguel/cordova-lib,tripodsan/cordova-lib,vladimir-kotikov/cordova-lib,purplecabbage/cordova-lib,surajpindoria/cordova-lib,tony--/cordova-lib,apache/cordova-lib,carynbear/cordova-lib,ogoguel/cordova-lib,matrosov-nikita/cordova-lib,AxelNennker/cordova-lib,apache/cordova-lib,driftyco/cordova-lib,matrosov-nikita/cordova-lib,tripodsan/cordova-lib,vladimir-kotikov/cordova-lib,purplecabbage/cordova-lib,stevengill/cordova-lib,marcuspridham/cordova-lib,apache/cordova-lib,filmaj/cordova-lib,AxelNennker/cordova-lib,carynbear/cordova-lib,ogoguel/cordova-lib,AxelNennker/cordova-lib,ogoguel/cordova-lib,tony--/cordova-lib,ktop/cordova-lib,ktop/cordova-lib,surajpindoria/cordova-lib,dpogue/cordova-lib,driftyco/cordova-lib,apache/cordova-lib,shazron/cordova-lib,marcuspridham/cordova-lib,matrosov-nikita/cordova-lib,ogoguel/cordova-lib,apache/cordova-lib,vladimir-kotikov/cordova-lib,vladimir-kotikov/cordova-lib,tripodsan/cordova-lib,jasongin/cordova-lib,csantanapr/cordova-lib,phonegap-build/cordova-lib,tony--/cordova-lib,csantanapr/cordova-lib,driftyco/cordova-lib,carynbear/cordova-lib,phonegap-build/cordova-lib,driftyco/cordova-lib,jasongin/cordova-lib,carynbear/cordova-lib,dpogue/cordova-lib,AxelNennker/cordova-lib,csantanapr/cordova-lib,dpogue/cordova-lib,dpogue/cordova-lib,csantanapr/cordova-lib,dpogue/cordova-lib,ktop/cordova-lib,jasongin/cordova-lib,surajpindoria/cordova-lib,dpogue/cordova-lib,driftyco/cordova-lib,filmaj/cordova-lib,ktop/cordova-lib,matrosov-nikita/cordova-lib,ktop/cordova-lib,marcuspridham/cordova-lib,tony--/cordova-lib,shazron/cordova-lib,AxelNennker/cordova-lib,stevengill/cordova-lib,tony--/cordova-lib,tripodsan/cordova-lib,driftyco/cordova-lib,marcuspridham/cordova-lib,filmaj/cordova-lib,tripodsan/cordova-lib,purplecabbage/cordova-lib,stevengill/cordova-lib,marcuspridham/cordova-lib,jasongin/cordova-lib,matrosov-nikita/cordova-lib,filmaj/cordova-lib,tripodsan/cordova-lib,jasongin/cordova-lib,tony--/cordova-lib,carynbear/cordova-lib,carynbear/cordova-lib,AxelNennker/cordova-lib,ogoguel/cordova-lib,filmaj/cordova-lib,marcuspridham/cordova-lib,phonegap-build/cordova-lib | /**
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
var fs = require('fs'),
path = require('path'),
et = require('elementtree'),
xml = require('cordova-common').xmlHelpers,
util = require('../util'),
events = require('cordova-common').events,
shell = require('shelljs'),
Q = require('q'),
Parser = require('./parser'),
ConfigParser = require('cordova-common').ConfigParser,
CordovaError = require('cordova-common').CordovaError;
function android_parser(project) {
if (!fs.existsSync(path.join(project, 'AndroidManifest.xml'))) {
throw new CordovaError('The provided path "' + project + '" is not an Android project.');
}
// Call the base class constructor
Parser.call(this, 'android', project);
this.path = project;
this.strings = path.join(this.path, 'res', 'values', 'strings.xml');
this.manifest = path.join(this.path, 'AndroidManifest.xml');
this.android_config = path.join(this.path, 'res', 'xml', 'config.xml');
}
require('util').inherits(android_parser, Parser);
module.exports = android_parser;
android_parser.prototype.findAndroidLaunchModePreference = function(config) {
var launchMode = config.getPreference('AndroidLaunchMode');
if (!launchMode) {
// Return a default value
return 'singleTop';
}
var expectedValues = ['standard', 'singleTop', 'singleTask', 'singleInstance'];
var valid = expectedValues.indexOf(launchMode) !== -1;
if (!valid) {
events.emit('warn', 'Unrecognized value for AndroidLaunchMode preference: ' + launchMode);
events.emit('warn', ' Expected values are: ' + expectedValues.join(', '));
// Note: warn, but leave the launch mode as developer wanted, in case the list of options changes in the future
}
return launchMode;
};
// remove the default resource name from all drawable folders
// return the array of the densities in this project
android_parser.prototype.deleteDefaultResource = function(name) {
var res = path.join(this.path, 'res');
var dirs = fs.readdirSync(res);
for (var i=0; i<dirs.length; i++) {
var filename = dirs[i];
if (filename.indexOf('drawable-') === 0) {
var imgPath = path.join(res, filename, name);
if (fs.existsSync(imgPath)) {
shell.chmod('u+w', imgPath);
fs.unlinkSync(imgPath);
events.emit('verbose', 'deleted: ' + imgPath);
}
imgPath = imgPath.replace(/\.png$/, '.9.png');
if (fs.existsSync(imgPath)) {
shell.chmod('u+w', imgPath);
fs.unlinkSync(imgPath);
events.emit('verbose', 'deleted: ' + imgPath);
}
}
}
};
android_parser.prototype.copyImage = function(src, density, name) {
var destFolder = path.join(this.path, 'res', (density ? 'drawable-': 'drawable') + density);
var isNinePatch = !!/\.9\.png$/.exec(src);
var ninePatchName = name.replace(/\.png$/, '.9.png');
// default template does not have default asset for this density
if (!fs.existsSync(destFolder)) {
fs.mkdirSync(destFolder);
}
var destFilePath = path.join(destFolder, isNinePatch ? ninePatchName : name);
events.emit('verbose', 'copying image from ' + src + ' to ' + destFilePath);
shell.cp('-f', src, destFilePath);
};
android_parser.prototype.handleSplashes = function(config) {
var resources = config.getSplashScreens('android');
var me = this;
// if there are "splash" elements in config.xml
if (resources.length > 0) {
this.deleteDefaultResource('screen.png');
events.emit('verbose', 'splash screens: ' + JSON.stringify(resources));
var projectRoot = util.isCordova(this.path);
var hadMdpi = false;
resources.forEach(function (resource) {
if (!resource.density) {
return;
}
if (resource.density == 'mdpi') {
hadMdpi = true;
}
me.copyImage(path.join(projectRoot, resource.src), resource.density, 'screen.png');
});
// There's no "default" drawable, so assume default == mdpi.
if (!hadMdpi && resources.defaultResource) {
me.copyImage(path.join(projectRoot, resources.defaultResource.src), 'mdpi', 'screen.png');
}
}
};
android_parser.prototype.handleIcons = function(config) {
var icons = config.getIcons('android');
// if there are icon elements in config.xml
if (icons.length === 0) {
events.emit('verbose', 'This app does not have launcher icons defined');
return;
}
this.deleteDefaultResource('icon.png');
var android_icons = {};
var default_icon;
// http://developer.android.com/design/style/iconography.html
var sizeToDensityMap = {
36: 'ldpi',
48: 'mdpi',
72: 'hdpi',
96: 'xhdpi',
144: 'xxhdpi',
192: 'xxxhdpi'
};
// find the best matching icon for a given density or size
// @output android_icons
var parseIcon = function(icon, icon_size) {
// do I have a platform icon for that density already
var density = icon.density || sizeToDensityMap[icon_size];
if (!density) {
// invalid icon defition ( or unsupported size)
return;
}
var previous = android_icons[density];
if (previous && previous.platform) {
return;
}
android_icons[density] = icon;
};
// iterate over all icon elements to find the default icon and call parseIcon
for (var i=0; i<icons.length; i++) {
var icon = icons[i];
var size = icon.width;
if (!size) {
size = icon.height;
}
if (!size && !icon.density) {
if (default_icon) {
events.emit('verbose', 'more than one default icon: ' + JSON.stringify(icon));
} else {
default_icon = icon;
}
} else {
parseIcon(icon, size);
}
}
var projectRoot = util.isCordova(this.path);
for (var density in android_icons) {
this.copyImage(path.join(projectRoot, android_icons[density].src), density, 'icon.png');
}
// There's no "default" drawable, so assume default == mdpi.
if (default_icon && !android_icons.mdpi) {
this.copyImage(path.join(projectRoot, default_icon.src), 'mdpi', 'icon.png');
}
};
android_parser.prototype.update_from_config = function(config) {
// TODO: share code for this func with Android. Or fix it and remove
// the below JSHint hacks line.
// jshint unused:false, indent:false, undef:true, loopfunc:true, shadow:true, quotmark:false
if (config instanceof ConfigParser) {
} else throw new Error('update_from_config requires a ConfigParser object');
// Update app name by editing res/values/strings.xml
var name = config.name();
var strings = xml.parseElementtreeSync(this.strings);
strings.find('string[@name="app_name"]').text = name;
fs.writeFileSync(this.strings, strings.write({indent: 4}), 'utf-8');
events.emit('verbose', 'Wrote out Android application name to "' + name + '"');
this.handleSplashes(config);
this.handleIcons(config);
var manifest = xml.parseElementtreeSync(this.manifest);
// Update the version by changing the AndroidManifest android:versionName
var version = config.version();
var versionCode = config.android_versionCode() || default_versionCode(version);
manifest.getroot().attrib["android:versionName"] = version;
manifest.getroot().attrib["android:versionCode"] = versionCode;
// Update package name by changing the AndroidManifest id and moving the entry class around to the proper package directory
var pkg = config.android_packageName() || config.packageName();
pkg = pkg.replace(/-/g, '_'); // Java packages cannot support dashes
var orig_pkg = manifest.getroot().attrib.package;
manifest.getroot().attrib.package = pkg;
var act = manifest.getroot().find('./application/activity');
// Set the android:screenOrientation in the AndroidManifest
var orientation = this.helper.getOrientation(config);
if (orientation && !this.helper.isDefaultOrientation(orientation)) {
act.attrib['android:screenOrientation'] = orientation;
} else {
delete act.attrib['android:screenOrientation'];
}
// Set android:launchMode in AndroidManifest
var androidLaunchModePref = this.findAndroidLaunchModePreference(config);
if (androidLaunchModePref) {
act.attrib["android:launchMode"] = androidLaunchModePref;
} else { // User has (explicitly) set an invalid value for AndroidLaunchMode preference
delete act.attrib["android:launchMode"]; // use Android default value (standard)
}
// Set min/max/target SDK version
//<uses-sdk android:minSdkVersion="10" android:targetSdkVersion="19" ... />
var usesSdk = manifest.getroot().find('./uses-sdk');
['minSdkVersion', 'maxSdkVersion', 'targetSdkVersion'].forEach(function(sdkPrefName) {
var sdkPrefValue = config.getPreference('android-' + sdkPrefName, 'android');
if (!sdkPrefValue) return;
if (!usesSdk) { // if there is no required uses-sdk element, we should create it first
usesSdk = new et.Element('uses-sdk');
manifest.getroot().append(usesSdk);
}
usesSdk.attrib['android:' + sdkPrefName] = sdkPrefValue;
});
// Write out AndroidManifest.xml
fs.writeFileSync(this.manifest, manifest.write({indent: 4}), 'utf-8');
var orig_pkgDir = path.join(this.path, 'src', path.join.apply(null, orig_pkg.split('.')));
var java_files = fs.readdirSync(orig_pkgDir).filter(function(f) {
return f.indexOf('.svn') == -1 && f.indexOf('.java') >= 0 && fs.readFileSync(path.join(orig_pkgDir, f), 'utf-8').match(/extends\s+CordovaActivity/);
});
if (java_files.length === 0) {
throw new Error('No Java files found which extend CordovaActivity.');
} else if(java_files.length > 1) {
events.emit('log', 'Multiple candidate Java files (.java files which extend CordovaActivity) found. Guessing at the first one, ' + java_files[0]);
}
var orig_java_class = java_files[0];
var pkgDir = path.join(this.path, 'src', path.join.apply(null, pkg.split('.')));
shell.mkdir('-p', pkgDir);
var orig_javs = path.join(orig_pkgDir, orig_java_class);
var new_javs = path.join(pkgDir, orig_java_class);
var javs_contents = fs.readFileSync(orig_javs, 'utf-8');
javs_contents = javs_contents.replace(/package [\w\.]*;/, 'package ' + pkg + ';');
events.emit('verbose', 'Wrote out Android package name to "' + pkg + '"');
fs.writeFileSync(new_javs, javs_contents, 'utf-8');
// remove the original if different from the new.
if(orig_pkgDir !== pkgDir){
shell.rm('-Rf',orig_javs);
// remove any empty directories
var curDir = path.dirname(orig_javs);
while(curDir !== path.resolve(this.path, 'src')) {
if(fs.existsSync(curDir) && fs.readdirSync(curDir).length === 0) {
fs.rmdirSync(curDir);
curDir = path.resolve(curDir, '..');
} else {
break;
}
}
}
};
// Returns the platform-specific www directory.
android_parser.prototype.www_dir = function() {
return path.join(this.path, 'assets', 'www');
};
android_parser.prototype.config_xml = function(){
return this.android_config;
};
// Used for creating platform_www in projects created by older versions.
android_parser.prototype.cordovajs_path = function(libDir) {
var jsPath = path.join(libDir, 'framework', 'assets', 'www', 'cordova.js');
return path.resolve(jsPath);
};
android_parser.prototype.cordovajs_src_path = function(libDir) {
var jsPath = path.join(libDir, 'cordova-js-src');
return path.resolve(jsPath);
};
// Replace the www dir with contents of platform_www and app www.
android_parser.prototype.update_www = function() {
var projectRoot = util.isCordova(this.path);
var app_www = util.projectWww(projectRoot);
var platform_www = path.join(this.path, 'platform_www');
// Clear the www dir
shell.rm('-rf', this.www_dir());
shell.mkdir(this.www_dir());
// Copy over all app www assets
shell.cp('-rf', path.join(app_www, '*'), this.www_dir());
// Copy over stock platform www assets (cordova.js)
shell.cp('-rf', path.join(platform_www, '*'), this.www_dir());
};
// update the overrides folder into the www folder
android_parser.prototype.update_overrides = function() {
var projectRoot = util.isCordova(this.path);
var merges_path = path.join(util.appDir(projectRoot), 'merges', 'android');
if (fs.existsSync(merges_path)) {
var overrides = path.join(merges_path, '*');
shell.cp('-rf', overrides, this.www_dir());
}
};
// Returns a promise.
android_parser.prototype.update_project = function(cfg) {
var platformWww = path.join(this.path, 'assets');
try {
this.update_from_config(cfg);
this.update_overrides();
} catch(e) {
return Q.reject(e);
}
// delete any .svn folders copied over
util.deleteSvnFolders(platformWww);
return Q();
};
// Consturct the default value for versionCode as
// PATCH + MINOR * 100 + MAJOR * 10000
// see http://developer.android.com/tools/publishing/versioning.html
function default_versionCode(version) {
var nums = version.split('-')[0].split('.');
var versionCode = 0;
if (+nums[0]) {
versionCode += +nums[0] * 10000;
}
if (+nums[1]) {
versionCode += +nums[1] * 100;
}
if (+nums[2]) {
versionCode += +nums[2];
}
return versionCode;
}
| cordova-lib/src/cordova/metadata/android_parser.js | /**
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
var fs = require('fs'),
path = require('path'),
et = require('elementtree'),
xml = require('cordova-common').xmlHelpers,
util = require('../util'),
events = require('cordova-common').events,
shell = require('shelljs'),
Q = require('q'),
Parser = require('./parser'),
ConfigParser = require('cordova-common').ConfigParser,
CordovaError = require('cordova-common').CordovaError;
function android_parser(project) {
if (!fs.existsSync(path.join(project, 'AndroidManifest.xml'))) {
throw new CordovaError('The provided path "' + project + '" is not an Android project.');
}
// Call the base class constructor
Parser.call(this, 'android', project);
this.path = project;
this.strings = path.join(this.path, 'res', 'values', 'strings.xml');
this.manifest = path.join(this.path, 'AndroidManifest.xml');
this.android_config = path.join(this.path, 'res', 'xml', 'config.xml');
}
require('util').inherits(android_parser, Parser);
module.exports = android_parser;
android_parser.prototype.findAndroidLaunchModePreference = function(config) {
var launchMode = config.getPreference('AndroidLaunchMode');
if (!launchMode) {
// Return a default value
return 'singleTop';
}
var expectedValues = ['standard', 'singleTop', 'singleTask', 'singleInstance'];
var valid = expectedValues.indexOf(launchMode) !== -1;
if (!valid) {
events.emit('warn', 'Unrecognized value for AndroidLaunchMode preference: ' + launchMode);
events.emit('warn', ' Expected values are: ' + expectedValues.join(', '));
// Note: warn, but leave the launch mode as developer wanted, in case the list of options changes in the future
}
return launchMode;
};
// remove the default resource name from all drawable folders
// return the array of the densities in this project
android_parser.prototype.deleteDefaultResource = function(name) {
var res = path.join(this.path, 'res');
var dirs = fs.readdirSync(res);
for (var i=0; i<dirs.length; i++) {
var filename = dirs[i];
if (filename.indexOf('drawable-') === 0) {
var imgPath = path.join(res, filename, name);
if (fs.existsSync(imgPath)) {
fs.unlinkSync(imgPath);
events.emit('verbose', 'deleted: ' + imgPath);
}
imgPath = imgPath.replace(/\.png$/, '.9.png');
if (fs.existsSync(imgPath)) {
fs.unlinkSync(imgPath);
events.emit('verbose', 'deleted: ' + imgPath);
}
}
}
};
android_parser.prototype.copyImage = function(src, density, name) {
var destFolder = path.join(this.path, 'res', (density ? 'drawable-': 'drawable') + density);
var isNinePatch = !!/\.9\.png$/.exec(src);
var ninePatchName = name.replace(/\.png$/, '.9.png');
// default template does not have default asset for this density
if (!fs.existsSync(destFolder)) {
fs.mkdirSync(destFolder);
}
var destFilePath = path.join(destFolder, isNinePatch ? ninePatchName : name);
events.emit('verbose', 'copying image from ' + src + ' to ' + destFilePath);
shell.cp('-f', src, destFilePath);
};
android_parser.prototype.handleSplashes = function(config) {
var resources = config.getSplashScreens('android');
var me = this;
// if there are "splash" elements in config.xml
if (resources.length > 0) {
this.deleteDefaultResource('screen.png');
events.emit('verbose', 'splash screens: ' + JSON.stringify(resources));
var projectRoot = util.isCordova(this.path);
var hadMdpi = false;
resources.forEach(function (resource) {
if (!resource.density) {
return;
}
if (resource.density == 'mdpi') {
hadMdpi = true;
}
me.copyImage(path.join(projectRoot, resource.src), resource.density, 'screen.png');
});
// There's no "default" drawable, so assume default == mdpi.
if (!hadMdpi && resources.defaultResource) {
me.copyImage(path.join(projectRoot, resources.defaultResource.src), 'mdpi', 'screen.png');
}
}
};
android_parser.prototype.handleIcons = function(config) {
var icons = config.getIcons('android');
// if there are icon elements in config.xml
if (icons.length === 0) {
events.emit('verbose', 'This app does not have launcher icons defined');
return;
}
this.deleteDefaultResource('icon.png');
var android_icons = {};
var default_icon;
// http://developer.android.com/design/style/iconography.html
var sizeToDensityMap = {
36: 'ldpi',
48: 'mdpi',
72: 'hdpi',
96: 'xhdpi',
144: 'xxhdpi',
192: 'xxxhdpi'
};
// find the best matching icon for a given density or size
// @output android_icons
var parseIcon = function(icon, icon_size) {
// do I have a platform icon for that density already
var density = icon.density || sizeToDensityMap[icon_size];
if (!density) {
// invalid icon defition ( or unsupported size)
return;
}
var previous = android_icons[density];
if (previous && previous.platform) {
return;
}
android_icons[density] = icon;
};
// iterate over all icon elements to find the default icon and call parseIcon
for (var i=0; i<icons.length; i++) {
var icon = icons[i];
var size = icon.width;
if (!size) {
size = icon.height;
}
if (!size && !icon.density) {
if (default_icon) {
events.emit('verbose', 'more than one default icon: ' + JSON.stringify(icon));
} else {
default_icon = icon;
}
} else {
parseIcon(icon, size);
}
}
var projectRoot = util.isCordova(this.path);
for (var density in android_icons) {
this.copyImage(path.join(projectRoot, android_icons[density].src), density, 'icon.png');
}
// There's no "default" drawable, so assume default == mdpi.
if (default_icon && !android_icons.mdpi) {
this.copyImage(path.join(projectRoot, default_icon.src), 'mdpi', 'icon.png');
}
};
android_parser.prototype.update_from_config = function(config) {
// TODO: share code for this func with Android. Or fix it and remove
// the below JSHint hacks line.
// jshint unused:false, indent:false, undef:true, loopfunc:true, shadow:true, quotmark:false
if (config instanceof ConfigParser) {
} else throw new Error('update_from_config requires a ConfigParser object');
// Update app name by editing res/values/strings.xml
var name = config.name();
var strings = xml.parseElementtreeSync(this.strings);
strings.find('string[@name="app_name"]').text = name;
fs.writeFileSync(this.strings, strings.write({indent: 4}), 'utf-8');
events.emit('verbose', 'Wrote out Android application name to "' + name + '"');
this.handleSplashes(config);
this.handleIcons(config);
var manifest = xml.parseElementtreeSync(this.manifest);
// Update the version by changing the AndroidManifest android:versionName
var version = config.version();
var versionCode = config.android_versionCode() || default_versionCode(version);
manifest.getroot().attrib["android:versionName"] = version;
manifest.getroot().attrib["android:versionCode"] = versionCode;
// Update package name by changing the AndroidManifest id and moving the entry class around to the proper package directory
var pkg = config.android_packageName() || config.packageName();
pkg = pkg.replace(/-/g, '_'); // Java packages cannot support dashes
var orig_pkg = manifest.getroot().attrib.package;
manifest.getroot().attrib.package = pkg;
var act = manifest.getroot().find('./application/activity');
// Set the android:screenOrientation in the AndroidManifest
var orientation = this.helper.getOrientation(config);
if (orientation && !this.helper.isDefaultOrientation(orientation)) {
act.attrib['android:screenOrientation'] = orientation;
} else {
delete act.attrib['android:screenOrientation'];
}
// Set android:launchMode in AndroidManifest
var androidLaunchModePref = this.findAndroidLaunchModePreference(config);
if (androidLaunchModePref) {
act.attrib["android:launchMode"] = androidLaunchModePref;
} else { // User has (explicitly) set an invalid value for AndroidLaunchMode preference
delete act.attrib["android:launchMode"]; // use Android default value (standard)
}
// Set min/max/target SDK version
//<uses-sdk android:minSdkVersion="10" android:targetSdkVersion="19" ... />
var usesSdk = manifest.getroot().find('./uses-sdk');
['minSdkVersion', 'maxSdkVersion', 'targetSdkVersion'].forEach(function(sdkPrefName) {
var sdkPrefValue = config.getPreference('android-' + sdkPrefName, 'android');
if (!sdkPrefValue) return;
if (!usesSdk) { // if there is no required uses-sdk element, we should create it first
usesSdk = new et.Element('uses-sdk');
manifest.getroot().append(usesSdk);
}
usesSdk.attrib['android:' + sdkPrefName] = sdkPrefValue;
});
// Write out AndroidManifest.xml
fs.writeFileSync(this.manifest, manifest.write({indent: 4}), 'utf-8');
var orig_pkgDir = path.join(this.path, 'src', path.join.apply(null, orig_pkg.split('.')));
var java_files = fs.readdirSync(orig_pkgDir).filter(function(f) {
return f.indexOf('.svn') == -1 && f.indexOf('.java') >= 0 && fs.readFileSync(path.join(orig_pkgDir, f), 'utf-8').match(/extends\s+CordovaActivity/);
});
if (java_files.length === 0) {
throw new Error('No Java files found which extend CordovaActivity.');
} else if(java_files.length > 1) {
events.emit('log', 'Multiple candidate Java files (.java files which extend CordovaActivity) found. Guessing at the first one, ' + java_files[0]);
}
var orig_java_class = java_files[0];
var pkgDir = path.join(this.path, 'src', path.join.apply(null, pkg.split('.')));
shell.mkdir('-p', pkgDir);
var orig_javs = path.join(orig_pkgDir, orig_java_class);
var new_javs = path.join(pkgDir, orig_java_class);
var javs_contents = fs.readFileSync(orig_javs, 'utf-8');
javs_contents = javs_contents.replace(/package [\w\.]*;/, 'package ' + pkg + ';');
events.emit('verbose', 'Wrote out Android package name to "' + pkg + '"');
fs.writeFileSync(new_javs, javs_contents, 'utf-8');
// remove the original if different from the new.
if(orig_pkgDir !== pkgDir){
shell.rm('-Rf',orig_javs);
// remove any empty directories
var curDir = path.dirname(orig_javs);
while(curDir !== path.resolve(this.path, 'src')) {
if(fs.existsSync(curDir) && fs.readdirSync(curDir).length === 0) {
fs.rmdirSync(curDir);
curDir = path.resolve(curDir, '..');
} else {
break;
}
}
}
};
// Returns the platform-specific www directory.
android_parser.prototype.www_dir = function() {
return path.join(this.path, 'assets', 'www');
};
android_parser.prototype.config_xml = function(){
return this.android_config;
};
// Used for creating platform_www in projects created by older versions.
android_parser.prototype.cordovajs_path = function(libDir) {
var jsPath = path.join(libDir, 'framework', 'assets', 'www', 'cordova.js');
return path.resolve(jsPath);
};
android_parser.prototype.cordovajs_src_path = function(libDir) {
var jsPath = path.join(libDir, 'cordova-js-src');
return path.resolve(jsPath);
};
// Replace the www dir with contents of platform_www and app www.
android_parser.prototype.update_www = function() {
var projectRoot = util.isCordova(this.path);
var app_www = util.projectWww(projectRoot);
var platform_www = path.join(this.path, 'platform_www');
// Clear the www dir
shell.rm('-rf', this.www_dir());
shell.mkdir(this.www_dir());
// Copy over all app www assets
shell.cp('-rf', path.join(app_www, '*'), this.www_dir());
// Copy over stock platform www assets (cordova.js)
shell.cp('-rf', path.join(platform_www, '*'), this.www_dir());
};
// update the overrides folder into the www folder
android_parser.prototype.update_overrides = function() {
var projectRoot = util.isCordova(this.path);
var merges_path = path.join(util.appDir(projectRoot), 'merges', 'android');
if (fs.existsSync(merges_path)) {
var overrides = path.join(merges_path, '*');
shell.cp('-rf', overrides, this.www_dir());
}
};
// Returns a promise.
android_parser.prototype.update_project = function(cfg) {
var platformWww = path.join(this.path, 'assets');
try {
this.update_from_config(cfg);
this.update_overrides();
} catch(e) {
return Q.reject(e);
}
// delete any .svn folders copied over
util.deleteSvnFolders(platformWww);
return Q();
};
// Consturct the default value for versionCode as
// PATCH + MINOR * 100 + MAJOR * 10000
// see http://developer.android.com/tools/publishing/versioning.html
function default_versionCode(version) {
var nums = version.split('-')[0].split('.');
var versionCode = 0;
if (+nums[0]) {
versionCode += +nums[0] * 10000;
}
if (+nums[1]) {
versionCode += +nums[1] * 100;
}
if (+nums[2]) {
versionCode += +nums[2];
}
return versionCode;
}
| CB-10125: Android build fails on read-only files. This closes #351
| cordova-lib/src/cordova/metadata/android_parser.js | CB-10125: Android build fails on read-only files. This closes #351 | <ide><path>ordova-lib/src/cordova/metadata/android_parser.js
<ide> if (filename.indexOf('drawable-') === 0) {
<ide> var imgPath = path.join(res, filename, name);
<ide> if (fs.existsSync(imgPath)) {
<add> shell.chmod('u+w', imgPath);
<ide> fs.unlinkSync(imgPath);
<ide> events.emit('verbose', 'deleted: ' + imgPath);
<ide> }
<ide> imgPath = imgPath.replace(/\.png$/, '.9.png');
<ide> if (fs.existsSync(imgPath)) {
<add> shell.chmod('u+w', imgPath);
<ide> fs.unlinkSync(imgPath);
<ide> events.emit('verbose', 'deleted: ' + imgPath);
<ide> } |
|
Java | apache-2.0 | 27ee183c290a241860423eb826356a1302f67ccb | 0 | puneetjaiswal/sql-parser,rimig/sql-parser,gnubila-france/sql-parser,mattyb149/sql-parser,storyeah/sql-parser,fivetran/sql-parser,hudak/sql-parser,brosander/sql-parser,storyeah/sql-parser,cswaroop/sql-parser,xiexingguang/sql-parser,puneetjaiswal/sql-parser,fengshao0907/sql-parser,brosander/sql-parser | /**
* END USER LICENSE AGREEMENT (“EULA”)
*
* READ THIS AGREEMENT CAREFULLY (date: 9/13/2011):
* http://www.akiban.com/licensing/20110913
*
* BY INSTALLING OR USING ALL OR ANY PORTION OF THE SOFTWARE, YOU ARE ACCEPTING
* ALL OF THE TERMS AND CONDITIONS OF THIS AGREEMENT. YOU AGREE THAT THIS
* AGREEMENT IS ENFORCEABLE LIKE ANY WRITTEN AGREEMENT SIGNED BY YOU.
*
* IF YOU HAVE PAID A LICENSE FEE FOR USE OF THE SOFTWARE AND DO NOT AGREE TO
* THESE TERMS, YOU MAY RETURN THE SOFTWARE FOR A FULL REFUND PROVIDED YOU (A) DO
* NOT USE THE SOFTWARE AND (B) RETURN THE SOFTWARE WITHIN THIRTY (30) DAYS OF
* YOUR INITIAL PURCHASE.
*
* IF YOU WISH TO USE THE SOFTWARE AS AN EMPLOYEE, CONTRACTOR, OR AGENT OF A
* CORPORATION, PARTNERSHIP OR SIMILAR ENTITY, THEN YOU MUST BE AUTHORIZED TO SIGN
* FOR AND BIND THE ENTITY IN ORDER TO ACCEPT THE TERMS OF THIS AGREEMENT. THE
* LICENSES GRANTED UNDER THIS AGREEMENT ARE EXPRESSLY CONDITIONED UPON ACCEPTANCE
* BY SUCH AUTHORIZED PERSONNEL.
*
* IF YOU HAVE ENTERED INTO A SEPARATE WRITTEN LICENSE AGREEMENT WITH AKIBAN FOR
* USE OF THE SOFTWARE, THE TERMS AND CONDITIONS OF SUCH OTHER AGREEMENT SHALL
* PREVAIL OVER ANY CONFLICTING TERMS OR CONDITIONS IN THIS AGREEMENT.
*/
package com.akiban.sql.parser;
import com.akiban.sql.StandardException;
public class GroupConcatNode extends AggregateNode
{
private String sep;
private OrderByList orderCols;
@Override
public void init(Object value,
Object aggClass,
Object distinct,
Object aggName,
Object orderCols,
Object sep)
throws StandardException
{
super.init(value,
aggClass,
distinct,
aggName);
this.orderCols = (OrderByList) orderCols;
this.sep = (String) sep;
}
@Override
public void copyFrom(QueryTreeNode node) throws StandardException
{
super.copyFrom(node);
GroupConcatNode other = (GroupConcatNode) node;
this.sep = other.sep;
this.orderCols = (OrderByList) getNodeFactory().copyNode(other.orderCols,
getParserContext());
}
@Override
void acceptChildren(Visitor v) throws StandardException
{
super.accept(v);
if (orderCols != null)
orderCols.accept(v);
}
/**
* @inheritDoc
*/
@Override
protected boolean isEquivalent(ValueNode o) throws StandardException
{
if (!isSameNodeType(o))
return false;
GroupConcatNode other = (GroupConcatNode) o;
return this.sep.equals(other.sep)
&& this.orderCols.equals(other.orderCols);
}
@Override
public String toString()
{
return super.toString() +
"\nseparator: " + sep +
"\norderyByList: "+ orderCols;
}
public String getSeparator()
{
return sep;
}
public OrderByList getOrderBy()
{
return orderCols;
}
}
| src/main/java/com/akiban/sql/parser/GroupConcatNode.java | /**
* END USER LICENSE AGREEMENT (“EULA”)
*
* READ THIS AGREEMENT CAREFULLY (date: 9/13/2011):
* http://www.akiban.com/licensing/20110913
*
* BY INSTALLING OR USING ALL OR ANY PORTION OF THE SOFTWARE, YOU ARE ACCEPTING
* ALL OF THE TERMS AND CONDITIONS OF THIS AGREEMENT. YOU AGREE THAT THIS
* AGREEMENT IS ENFORCEABLE LIKE ANY WRITTEN AGREEMENT SIGNED BY YOU.
*
* IF YOU HAVE PAID A LICENSE FEE FOR USE OF THE SOFTWARE AND DO NOT AGREE TO
* THESE TERMS, YOU MAY RETURN THE SOFTWARE FOR A FULL REFUND PROVIDED YOU (A) DO
* NOT USE THE SOFTWARE AND (B) RETURN THE SOFTWARE WITHIN THIRTY (30) DAYS OF
* YOUR INITIAL PURCHASE.
*
* IF YOU WISH TO USE THE SOFTWARE AS AN EMPLOYEE, CONTRACTOR, OR AGENT OF A
* CORPORATION, PARTNERSHIP OR SIMILAR ENTITY, THEN YOU MUST BE AUTHORIZED TO SIGN
* FOR AND BIND THE ENTITY IN ORDER TO ACCEPT THE TERMS OF THIS AGREEMENT. THE
* LICENSES GRANTED UNDER THIS AGREEMENT ARE EXPRESSLY CONDITIONED UPON ACCEPTANCE
* BY SUCH AUTHORIZED PERSONNEL.
*
* IF YOU HAVE ENTERED INTO A SEPARATE WRITTEN LICENSE AGREEMENT WITH AKIBAN FOR
* USE OF THE SOFTWARE, THE TERMS AND CONDITIONS OF SUCH OTHER AGREEMENT SHALL
* PREVAIL OVER ANY CONFLICTING TERMS OR CONDITIONS IN THIS AGREEMENT.
*/
package com.akiban.sql.parser;
import com.akiban.sql.StandardException;
public class GroupConcatNode extends AggregateNode
{
private String sep;
private OrderByList orderCols;
@Override
public void init(Object value,
Object aggClass,
Object distinct,
Object aggName,
Object orderCols,
Object sep)
throws StandardException
{
super.init(value,
aggClass,
distinct,
aggName);
this.orderCols = (OrderByList) orderCols;
this.sep = (String) sep;
}
@Override
public void copyFrom(QueryTreeNode node) throws StandardException
{
super.copyFrom(node);
GroupConcatNode other = (GroupConcatNode) node;
this.sep = other.sep;
this.orderCols = (OrderByList) getNodeFactory().copyNode(other.orderCols,
getParserContext());
}
@Override
void acceptChildren(Visitor v) throws StandardException
{
super.accept(v);
orderCols.accept(v);
}
/**
* @inheritDoc
*/
@Override
protected boolean isEquivalent(ValueNode o) throws StandardException
{
if (!isSameNodeType(o))
return false;
GroupConcatNode other = (GroupConcatNode) o;
return this.sep.equals(other.sep)
&& this.orderCols.equals(other.orderCols);
}
@Override
public String toString()
{
return super.toString() +
"\nseparator: " + sep +
"\norderyByList: "+ orderCols;
}
public String getSeparator()
{
return sep;
}
public OrderByList getOrderBy()
{
return orderCols;
}
}
| checking null | src/main/java/com/akiban/sql/parser/GroupConcatNode.java | checking null | <ide><path>rc/main/java/com/akiban/sql/parser/GroupConcatNode.java
<ide> void acceptChildren(Visitor v) throws StandardException
<ide> {
<ide> super.accept(v);
<del> orderCols.accept(v);
<add> if (orderCols != null)
<add> orderCols.accept(v);
<ide> }
<ide>
<ide> /** |
|
Java | apache-2.0 | 18ddaa302eb958456054e27885199992deccb176 | 0 | allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community,allotria/intellij-community | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.gradle.service.project;
import com.intellij.build.events.MessageEvent;
import com.intellij.build.events.impl.BuildIssueEventImpl;
import com.intellij.build.issue.BuildIssue;
import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskId;
import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskNotificationListener;
import com.intellij.openapi.externalSystem.model.task.event.ExternalSystemBuildEvent;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.util.UserDataHolderBase;
import org.gradle.initialization.BuildLayoutParameters;
import org.gradle.tooling.CancellationTokenSource;
import org.gradle.tooling.GradleConnector;
import org.gradle.tooling.ProjectConnection;
import org.gradle.tooling.model.build.BuildEnvironment;
import org.gradle.tooling.model.idea.IdeaModule;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.plugins.gradle.model.ProjectImportAction;
import org.jetbrains.plugins.gradle.settings.GradleExecutionSettings;
import java.io.File;
/**
* @author Vladislav.Soroka
*/
public class DefaultProjectResolverContext extends UserDataHolderBase implements ProjectResolverContext {
@NotNull private final ExternalSystemTaskId myExternalSystemTaskId;
@NotNull private final String myProjectPath;
@Nullable private final GradleExecutionSettings mySettings;
@NotNull private final ExternalSystemTaskNotificationListener myListener;
private final boolean myIsPreviewMode;
@NotNull private final CancellationTokenSource myCancellationTokenSource;
private ProjectConnection myConnection;
@NotNull
private ProjectImportAction.AllModels myModels;
private File myGradleUserHome;
@Nullable private String myProjectGradleVersion;
@Nullable private String myBuildSrcGroup;
@Nullable private BuildEnvironment myBuildEnvironment;
@Nullable private final GradleIncrementalResolverPolicy myPolicy;
public DefaultProjectResolverContext(@NotNull final ExternalSystemTaskId externalSystemTaskId,
@NotNull final String projectPath,
@Nullable final GradleExecutionSettings settings,
@NotNull final ExternalSystemTaskNotificationListener listener,
@Nullable GradleIncrementalResolverPolicy resolverPolicy,
final boolean isPreviewMode) {
this(externalSystemTaskId, projectPath, settings, null, listener, resolverPolicy, isPreviewMode);
}
public DefaultProjectResolverContext(@NotNull final ExternalSystemTaskId externalSystemTaskId,
@NotNull final String projectPath,
@Nullable final GradleExecutionSettings settings,
final ProjectConnection connection,
@NotNull final ExternalSystemTaskNotificationListener listener,
@Nullable GradleIncrementalResolverPolicy resolverPolicy,
final boolean isPreviewMode) {
myExternalSystemTaskId = externalSystemTaskId;
myProjectPath = projectPath;
mySettings = settings;
myConnection = connection;
myListener = listener;
myPolicy = resolverPolicy;
myIsPreviewMode = isPreviewMode;
myCancellationTokenSource = GradleConnector.newCancellationTokenSource();
}
@NotNull
@Override
public ExternalSystemTaskId getExternalSystemTaskId() {
return myExternalSystemTaskId;
}
@Nullable
@Override
public String getIdeProjectPath() {
return mySettings != null ? mySettings.getIdeProjectPath() : null;
}
@NotNull
@Override
public String getProjectPath() {
return myProjectPath;
}
@Nullable
@Override
public GradleExecutionSettings getSettings() {
return mySettings;
}
@NotNull
@Override
public ProjectConnection getConnection() {
return myConnection;
}
public void setConnection(@NotNull ProjectConnection connection) {
myConnection = connection;
}
@NotNull
@Override
public CancellationTokenSource getCancellationTokenSource() {
return myCancellationTokenSource;
}
@NotNull
@Override
public ExternalSystemTaskNotificationListener getListener() {
return myListener;
}
@Override
public boolean isPreviewMode() {
return myIsPreviewMode;
}
@Override
public boolean isResolveModulePerSourceSet() {
return mySettings == null || mySettings.isResolveModulePerSourceSet();
}
@Override
public boolean isUseQualifiedModuleNames() {
return mySettings != null && mySettings.isUseQualifiedModuleNames();
}
@Override
public boolean isDelegatedBuild() {
return mySettings == null || mySettings.isDelegatedBuild();
}
public File getGradleUserHome() {
if (myGradleUserHome == null) {
String serviceDirectory = mySettings == null ? null : mySettings.getServiceDirectory();
myGradleUserHome = serviceDirectory != null ? new File(serviceDirectory) : new BuildLayoutParameters().getGradleUserHomeDir();
}
return myGradleUserHome;
}
@NotNull
@Override
public ProjectImportAction.AllModels getModels() {
return myModels;
}
@Override
public void setModels(@NotNull ProjectImportAction.AllModels models) {
myModels = models;
}
@Nullable
@Override
public <T> T getExtraProject(Class<T> modelClazz) {
return myModels.getModel(modelClazz);
}
@Nullable
@Override
public <T> T getExtraProject(@Nullable IdeaModule module, Class<T> modelClazz) {
return module == null ? myModels.getModel(modelClazz) : myModels.getModel(module, modelClazz);
}
@Override
public boolean hasModulesWithModel(@NotNull Class modelClazz) {
return myModels.hasModulesWithModel(modelClazz);
}
@Override
public void checkCancelled() {
if (myCancellationTokenSource.token().isCancellationRequested()) {
throw new ProcessCanceledException();
}
}
@Override
public String getProjectGradleVersion() {
if (myProjectGradleVersion == null) {
if (myBuildEnvironment == null) {
myBuildEnvironment = getModels().getBuildEnvironment();
}
if (myBuildEnvironment != null) {
myProjectGradleVersion = myBuildEnvironment.getGradle().getGradleVersion();
}
}
return myProjectGradleVersion;
}
public void setBuildSrcGroup(@Nullable String groupId) {
myBuildSrcGroup = groupId;
}
@Nullable
@Override
public String getBuildSrcGroup() {
return myBuildSrcGroup;
}
@Override
public void report(@NotNull MessageEvent.Kind kind, @NotNull BuildIssue buildIssue) {
BuildIssueEventImpl buildIssueEvent = new BuildIssueEventImpl(myExternalSystemTaskId, buildIssue, kind);
myListener.onStatusChange(new ExternalSystemBuildEvent(myExternalSystemTaskId, buildIssueEvent));
}
void setBuildEnvironment(@NotNull BuildEnvironment buildEnvironment) {
myBuildEnvironment = buildEnvironment;
}
@Nullable
public BuildEnvironment getBuildEnvironment() {
return myBuildEnvironment;
}
@Nullable
@ApiStatus.Experimental
public GradleIncrementalResolverPolicy getPolicy() {
return myPolicy;
}
}
| plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/DefaultProjectResolverContext.java | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.gradle.service.project;
import com.intellij.build.events.MessageEvent;
import com.intellij.build.events.impl.BuildIssueEventImpl;
import com.intellij.build.issue.BuildIssue;
import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskId;
import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskNotificationListener;
import com.intellij.openapi.externalSystem.model.task.event.ExternalSystemBuildEvent;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.util.UserDataHolderBase;
import org.gradle.initialization.BuildLayoutParameters;
import org.gradle.tooling.CancellationTokenSource;
import org.gradle.tooling.GradleConnector;
import org.gradle.tooling.ProjectConnection;
import org.gradle.tooling.model.build.BuildEnvironment;
import org.gradle.tooling.model.idea.IdeaModule;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.plugins.gradle.model.ProjectImportAction;
import org.jetbrains.plugins.gradle.settings.GradleExecutionSettings;
import java.io.File;
/**
* @author Vladislav.Soroka
*/
public class DefaultProjectResolverContext extends UserDataHolderBase implements ProjectResolverContext {
@NotNull private final ExternalSystemTaskId myExternalSystemTaskId;
@NotNull private final String myProjectPath;
@Nullable private final GradleExecutionSettings mySettings;
@NotNull private final ExternalSystemTaskNotificationListener myListener;
private final boolean myIsPreviewMode;
@NotNull private final CancellationTokenSource myCancellationTokenSource;
private ProjectConnection myConnection;
@NotNull
private ProjectImportAction.AllModels myModels;
private File myGradleUserHome;
@Nullable private String myProjectGradleVersion;
@Nullable private String myBuildSrcGroup;
@Nullable private BuildEnvironment myBuildEnvironment;
private final GradleIncrementalResolverPolicy myPolicy;
public DefaultProjectResolverContext(@NotNull final ExternalSystemTaskId externalSystemTaskId,
@NotNull final String projectPath,
@Nullable final GradleExecutionSettings settings,
@NotNull final ExternalSystemTaskNotificationListener listener,
@Nullable GradleIncrementalResolverPolicy resolverPolicy,
final boolean isPreviewMode) {
this(externalSystemTaskId, projectPath, settings, null, listener, resolverPolicy, isPreviewMode);
}
public DefaultProjectResolverContext(@NotNull final ExternalSystemTaskId externalSystemTaskId,
@NotNull final String projectPath,
@Nullable final GradleExecutionSettings settings,
final ProjectConnection connection,
@NotNull final ExternalSystemTaskNotificationListener listener,
@Nullable GradleIncrementalResolverPolicy resolverPolicy,
final boolean isPreviewMode) {
myExternalSystemTaskId = externalSystemTaskId;
myProjectPath = projectPath;
mySettings = settings;
myConnection = connection;
myListener = listener;
myPolicy = resolverPolicy;
myIsPreviewMode = isPreviewMode;
myCancellationTokenSource = GradleConnector.newCancellationTokenSource();
}
@NotNull
@Override
public ExternalSystemTaskId getExternalSystemTaskId() {
return myExternalSystemTaskId;
}
@Nullable
@Override
public String getIdeProjectPath() {
return mySettings != null ? mySettings.getIdeProjectPath() : null;
}
@NotNull
@Override
public String getProjectPath() {
return myProjectPath;
}
@Nullable
@Override
public GradleExecutionSettings getSettings() {
return mySettings;
}
@NotNull
@Override
public ProjectConnection getConnection() {
return myConnection;
}
public void setConnection(@NotNull ProjectConnection connection) {
myConnection = connection;
}
@NotNull
@Override
public CancellationTokenSource getCancellationTokenSource() {
return myCancellationTokenSource;
}
@NotNull
@Override
public ExternalSystemTaskNotificationListener getListener() {
return myListener;
}
@Override
public boolean isPreviewMode() {
return myIsPreviewMode;
}
@Override
public boolean isResolveModulePerSourceSet() {
return mySettings == null || mySettings.isResolveModulePerSourceSet();
}
@Override
public boolean isUseQualifiedModuleNames() {
return mySettings != null && mySettings.isUseQualifiedModuleNames();
}
@Override
public boolean isDelegatedBuild() {
return mySettings == null || mySettings.isDelegatedBuild();
}
public File getGradleUserHome() {
if (myGradleUserHome == null) {
String serviceDirectory = mySettings == null ? null : mySettings.getServiceDirectory();
myGradleUserHome = serviceDirectory != null ? new File(serviceDirectory) : new BuildLayoutParameters().getGradleUserHomeDir();
}
return myGradleUserHome;
}
@NotNull
@Override
public ProjectImportAction.AllModels getModels() {
return myModels;
}
@Override
public void setModels(@NotNull ProjectImportAction.AllModels models) {
myModels = models;
}
@Nullable
@Override
public <T> T getExtraProject(Class<T> modelClazz) {
return myModels.getModel(modelClazz);
}
@Nullable
@Override
public <T> T getExtraProject(@Nullable IdeaModule module, Class<T> modelClazz) {
return module == null ? myModels.getModel(modelClazz) : myModels.getModel(module, modelClazz);
}
@Override
public boolean hasModulesWithModel(@NotNull Class modelClazz) {
return myModels.hasModulesWithModel(modelClazz);
}
@Override
public void checkCancelled() {
if (myCancellationTokenSource.token().isCancellationRequested()) {
throw new ProcessCanceledException();
}
}
@Override
public String getProjectGradleVersion() {
if (myProjectGradleVersion == null) {
if (myBuildEnvironment == null) {
myBuildEnvironment = getModels().getBuildEnvironment();
}
if (myBuildEnvironment != null) {
myProjectGradleVersion = myBuildEnvironment.getGradle().getGradleVersion();
}
}
return myProjectGradleVersion;
}
public void setBuildSrcGroup(@Nullable String groupId) {
myBuildSrcGroup = groupId;
}
@Nullable
@Override
public String getBuildSrcGroup() {
return myBuildSrcGroup;
}
@Override
public void report(@NotNull MessageEvent.Kind kind, @NotNull BuildIssue buildIssue) {
BuildIssueEventImpl buildIssueEvent = new BuildIssueEventImpl(myExternalSystemTaskId, buildIssue, kind);
myListener.onStatusChange(new ExternalSystemBuildEvent(myExternalSystemTaskId, buildIssueEvent));
}
void setBuildEnvironment(@NotNull BuildEnvironment buildEnvironment) {
myBuildEnvironment = buildEnvironment;
}
@Nullable
public BuildEnvironment getBuildEnvironment() {
return myBuildEnvironment;
}
@ApiStatus.Experimental
public GradleIncrementalResolverPolicy getPolicy() {
return myPolicy;
}
}
| [Gradle] nullable incremental resolver policy IDEA-222274
GitOrigin-RevId: 56f247567be70130da8e393ea3e94001fc2d8769 | plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/DefaultProjectResolverContext.java | [Gradle] nullable incremental resolver policy IDEA-222274 | <ide><path>lugins/gradle/src/org/jetbrains/plugins/gradle/service/project/DefaultProjectResolverContext.java
<ide> @Nullable private String myProjectGradleVersion;
<ide> @Nullable private String myBuildSrcGroup;
<ide> @Nullable private BuildEnvironment myBuildEnvironment;
<del> private final GradleIncrementalResolverPolicy myPolicy;
<add> @Nullable private final GradleIncrementalResolverPolicy myPolicy;
<ide>
<ide> public DefaultProjectResolverContext(@NotNull final ExternalSystemTaskId externalSystemTaskId,
<ide> @NotNull final String projectPath,
<ide> return myBuildEnvironment;
<ide> }
<ide>
<add> @Nullable
<ide> @ApiStatus.Experimental
<ide> public GradleIncrementalResolverPolicy getPolicy() {
<ide> return myPolicy; |
|
JavaScript | mit | 61f1c05fb2e1efddf466dacca82eb524a9fbe7a8 | 0 | AEDA-Solutions/matweb,AEDA-Solutions/matweb,AEDA-Solutions/matweb,AEDA-Solutions/matweb,AEDA-Solutions/matweb | angular.
module('Exibir').
component('materiaInfo', {
templateUrl: '/app/Exibir/exibir.template.html',
controller: ['ApiExibir', 'MatWebGlobals',function Entrar(ApiExibir,MatWebGlobals) {
if (MatWebGlobals.hasOwnProperty('usuarioOferta')) {
$scope.idMateria = MatWebGlobals.usuarioOferta.id;
$scope.codigoMateria = MatWebGlobals.usuarioOferta.codigo;
} else {
$location.path('/Sexo');
}
this.nome_disciplina = "";
var ctrl = this;
ctrl.disciplinas = [];
this.pesquisar = function()
{
ApiExibir.Listar(this.formulario,function(resultado) {
MatWebGlobals.usuarioOferta = resultado.corpo.oferta;
$http.defaults.headers.common.Authorization = resultado.corpo.token;
console.log(ctrl.disciplinas)
}, function(erro){
ctrl.erro = erro.data.mensagem
console.log(ctrl.erro)
} );
}
}]
}); | frontend/app/Exibir/exibir.component.js | angular.
module('Exibir').
component('ofertaDisciplina', {
templateUrl: '/app/Exibir/exibir.template.html',
controller: ['ApiExibir', 'MatWebGlobals',function Entrar(ApiExibir,MatWebGlobals) {
if (MatWebGlobals.hasOwnProperty('usuarioOferta')) {
$scope.idMateria = MatWebGlobals.usuarioOferta.id;
$scope.codigoMateria = MatWebGlobals.usuarioOferta.codigo;
} else {
$location.path('/Sexo');
}
this.nome_disciplina = "";
var ctrl = this;
ctrl.disciplinas = [];
this.pesquisar = function()
{
ApiExibir.Listar(this.formulario,function(resultado) {
MatWebGlobals.usuarioOferta = resultado.corpo.oferta;
$http.defaults.headers.common.Authorization = resultado.corpo.token;
console.log(ctrl.disciplinas)
}, function(erro){
ctrl.erro = erro.data.mensagem
console.log(ctrl.erro)
} );
}
}]
}); | lol 2017-05-31
| frontend/app/Exibir/exibir.component.js | lol 2017-05-31 | <ide><path>rontend/app/Exibir/exibir.component.js
<ide> angular.
<ide> module('Exibir').
<del> component('ofertaDisciplina', {
<add> component('materiaInfo', {
<ide> templateUrl: '/app/Exibir/exibir.template.html',
<ide> controller: ['ApiExibir', 'MatWebGlobals',function Entrar(ApiExibir,MatWebGlobals) {
<ide> if (MatWebGlobals.hasOwnProperty('usuarioOferta')) { |
|
Java | apache-2.0 | 8ad453bac6cd98d6400e830de0df8a4ebab87512 | 0 | MICommunity/psi-jami,MICommunity/psi-jami,MICommunity/psi-jami | package psidev.psi.mi.jami.datasource;
/**
* This enum is giving topics for different parsing error types
*
* @author Marine Dumousseau ([email protected])
* @version $Id$
* @since <pre>15/03/13</pre>
*/
public enum FileParsingErrorType {
invalid_syntax, multiple_experimental_roles, multiple_host_organisms, multiple_experiments, multiple_expressed_in,
multiple_participant_identification_methods, multiple_interaction_types, missing_biological_role, missing_experimental_role, missing_cv, clustered_content,
missing_database, missing_database_accession, invalid_feature_range, feature_without_ranges, missing_publication, missing_interaction_detection_method,
interaction_without_any_participants, missing_interactor_type, missing_alias_name, missing_annotation_topic,
missing_confidence_type, missing_confidence_value, interaction_evidence_without_experiment, missing_parameter_type, missing_parameter_factor,
participant_without_interactor, missing_range_status, missing_range_position
}
| src/main/java/psidev/psi/mi/jami/datasource/FileParsingErrorType.java | package psidev.psi.mi.jami.datasource;
/**
* This enum is giving topics for different parsing error types
*
* @author Marine Dumousseau ([email protected])
* @version $Id$
* @since <pre>15/03/13</pre>
*/
public enum FileParsingErrorType {
invalid_syntax, multiple_experimental_roles, multiple_host_organisms, multiple_experiments, multiple_expressed_in,
multiple_participant_identification_methods, multiple_interaction_types, missing_biological_role, missing_cv, clustered_content,
missing_database, missing_database_accession, invalid_feature_range, feature_without_ranges, missing_publication, missing_interaction_detection_method,
interaction_without_any_participants, missing_interactor_type, missing_interaction_type, missing_alias_name, missing_annotation_topic
}
| Added rule missing_experimental_role | src/main/java/psidev/psi/mi/jami/datasource/FileParsingErrorType.java | Added rule missing_experimental_role | <ide><path>rc/main/java/psidev/psi/mi/jami/datasource/FileParsingErrorType.java
<ide> public enum FileParsingErrorType {
<ide>
<ide> invalid_syntax, multiple_experimental_roles, multiple_host_organisms, multiple_experiments, multiple_expressed_in,
<del> multiple_participant_identification_methods, multiple_interaction_types, missing_biological_role, missing_cv, clustered_content,
<add> multiple_participant_identification_methods, multiple_interaction_types, missing_biological_role, missing_experimental_role, missing_cv, clustered_content,
<ide> missing_database, missing_database_accession, invalid_feature_range, feature_without_ranges, missing_publication, missing_interaction_detection_method,
<del> interaction_without_any_participants, missing_interactor_type, missing_interaction_type, missing_alias_name, missing_annotation_topic
<add> interaction_without_any_participants, missing_interactor_type, missing_alias_name, missing_annotation_topic,
<add> missing_confidence_type, missing_confidence_value, interaction_evidence_without_experiment, missing_parameter_type, missing_parameter_factor,
<add> participant_without_interactor, missing_range_status, missing_range_position
<ide>
<ide> } |
|
Java | apache-2.0 | 6201b268290cc6609a8cd1655887ae741afd61fb | 0 | 10045125/ChatSecureAndroid,bonashen/ChatSecureAndroid,ChatSecure/ChatSecureAndroid,eighthave/ChatSecureAndroid,anvayarai/my-ChatSecure,n8fr8/AwesomeApp,guardianproject/ChatSecureAndroid,10045125/ChatSecureAndroid,bonashen/ChatSecureAndroid,anvayarai/my-ChatSecure,prive/prive-android,31H0B1eV/ChatSecureAndroid,prembasumatary/ChatSecureAndroid,joskarthic/chatsecure,ChatSecure/ChatSecureAndroid,n8fr8/AwesomeApp,guardianproject/ChatSecureAndroid,prive/prive-android,bonashen/ChatSecureAndroid,prembasumatary/ChatSecureAndroid,eighthave/ChatSecureAndroid,Heart2009/ChatSecureAndroid,joskarthic/chatsecure,anvayarai/my-ChatSecure,eighthave/ChatSecureAndroid,guardianproject/ChatSecureAndroid,n8fr8/ChatSecureAndroid,31H0B1eV/ChatSecureAndroid,h2ri/ChatSecureAndroid,prive/prive-android,h2ri/ChatSecureAndroid,n8fr8/ChatSecureAndroid,OnlyInAmerica/ChatSecureAndroid,kden/ChatSecureAndroid,OnlyInAmerica/ChatSecureAndroid,kden/ChatSecureAndroid,OnlyInAmerica/ChatSecureAndroid,n8fr8/AwesomeApp,ChatSecure/ChatSecureAndroid,maheshwarishivam/ChatSecureAndroid,31H0B1eV/ChatSecureAndroid,kden/ChatSecureAndroid,joskarthic/chatsecure,prive/prive-android,maheshwarishivam/ChatSecureAndroid,n8fr8/ChatSecureAndroid,OnlyInAmerica/ChatSecureAndroid,Heart2009/ChatSecureAndroid,h2ri/ChatSecureAndroid,Heart2009/ChatSecureAndroid,10045125/ChatSecureAndroid,ChatSecure/ChatSecureAndroid,prembasumatary/ChatSecureAndroid,maheshwarishivam/ChatSecureAndroid | package info.guardianproject.otr.app.im.app;
import info.guardianproject.otr.app.im.provider.Imps;
import info.guardianproject.otr.app.im.service.StatusBarNotifier;
import info.guardianproject.util.Debug;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.net.Uri.Builder;
import android.preference.PreferenceManager;
import android.util.Log;
/**
* Automatically initiate the service and connect when the network comes on,
* including on boot.
*/
public class BootCompletedListener extends BroadcastReceiver {
public final static String BOOTFLAG = "BOOTFLAG";
@Override
public synchronized void onReceive(Context context, Intent intent) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
boolean prefStartOnBoot = prefs.getBoolean("pref_start_on_boot", true);
if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED"))
{
Debug.onServiceStart();
if (prefStartOnBoot)
{
if (isUnencrypted(context))
{
Log.d(ImApp.LOG_TAG, "autostart");
new ImApp(context).startImServiceIfNeed(true);
Log.d(ImApp.LOG_TAG, "autostart done");
}
else
{
//show unlock notification
StatusBarNotifier sbn = new StatusBarNotifier(context);
sbn.notifyLocked();
}
}
}
}
private boolean isUnencrypted(Context context) {
try {
String pKey = "";
Cursor cursor = null;
Uri uri = Imps.Provider.CONTENT_URI_WITH_ACCOUNT;
Builder builder = uri.buildUpon();
builder.appendQueryParameter(ImApp.CACHEWORD_PASSWORD_KEY, pKey);
uri = builder.build();
cursor = context.getContentResolver().query(
uri, null, Imps.Provider.CATEGORY + "=?" /* selection */,
new String[] { ImApp.IMPS_CATEGORY } /* selection args */,
null);
if (cursor != null)
{
cursor.close();
return true;
}
else
{
return false;
}
} catch (Exception e) {
// Only complain if we thought this password should succeed
Log.e(ImApp.LOG_TAG, e.getMessage(), e);
// needs to be unlocked
return false;
}
}
}
| src/info/guardianproject/otr/app/im/app/BootCompletedListener.java | package info.guardianproject.otr.app.im.app;
import info.guardianproject.otr.app.im.provider.Imps;
import info.guardianproject.otr.app.im.service.StatusBarNotifier;
import info.guardianproject.util.Debug;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.net.Uri.Builder;
import android.preference.PreferenceManager;
import android.util.Log;
/**
* Automatically initiate the service and connect when the network comes on,
* including on boot.
*/
public class BootCompletedListener extends BroadcastReceiver {
public final static String BOOTFLAG = "BOOTFLAG";
@Override
public synchronized void onReceive(Context context, Intent intent) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
boolean prefStartOnBoot = prefs.getBoolean("pref_start_on_boot", true);
if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED"))
{
Debug.onServiceStart();
if (prefStartOnBoot)
{
if (isUnencrypted(context))
{
Log.d(ImApp.LOG_TAG, "autostart");
new ImApp(context).startImServiceIfNeed(true);
Log.d(ImApp.LOG_TAG, "autostart done");
}
else
{
//show unlock notification
StatusBarNotifier sbn = new StatusBarNotifier(context);
sbn.notifyLocked();
}
}
}
}
private boolean isUnencrypted(Context context) {
try {
boolean allowCreate = false;
String pKey = null;
Cursor cursor = null;
Uri uri = Imps.Provider.CONTENT_URI_WITH_ACCOUNT;
Builder builder = uri.buildUpon();
if (!allowCreate)
builder = builder.appendQueryParameter(ImApp.NO_CREATE_KEY, "1");
uri = builder.build();
cursor = context.getContentResolver().query(
uri, null, Imps.Provider.CATEGORY + "=?" /* selection */,
new String[] { ImApp.IMPS_CATEGORY } /* selection args */,
null);
if (cursor != null)
{
cursor.close();
return true;
}
else
{
return false;
}
} catch (Exception e) {
// Only complain if we thought this password should succeed
Log.e(ImApp.LOG_TAG, e.getMessage(), e);
// needs to be unlocked
return false;
}
}
}
| fix bootcomplete listener to work for unenc devices
| src/info/guardianproject/otr/app/im/app/BootCompletedListener.java | fix bootcomplete listener to work for unenc devices | <ide><path>rc/info/guardianproject/otr/app/im/app/BootCompletedListener.java
<ide>
<ide> private boolean isUnencrypted(Context context) {
<ide> try {
<del> boolean allowCreate = false;
<del> String pKey = null;
<add> String pKey = "";
<ide> Cursor cursor = null;
<ide>
<ide> Uri uri = Imps.Provider.CONTENT_URI_WITH_ACCOUNT;
<ide>
<ide> Builder builder = uri.buildUpon();
<del> if (!allowCreate)
<del> builder = builder.appendQueryParameter(ImApp.NO_CREATE_KEY, "1");
<add> builder.appendQueryParameter(ImApp.CACHEWORD_PASSWORD_KEY, pKey);
<add>
<ide> uri = builder.build();
<ide>
<ide> cursor = context.getContentResolver().query( |
|
Java | mit | 94ece98fe17fd312ada42a45b297640fb331ad1f | 0 | codeborne/selenide,simple-elf/selenide,codeborne/selenide,simple-elf/selenide,simple-elf/selenide,simple-elf/selenide,codeborne/selenide | package com.codeborne.selenide.impl;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nonnull;
import javax.annotation.ParametersAreNonnullByDefault;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
@ParametersAreNonnullByDefault
public final class FileHelper {
private static final Logger log = LoggerFactory.getLogger(FileHelper.class);
private FileHelper() {
}
public static void copyFile(File sourceFile, File targetFile) throws IOException {
try (FileInputStream in = new FileInputStream(sourceFile)) {
copyFile(in, targetFile);
}
}
public static void copyFile(InputStream in, File targetFile) throws IOException {
ensureParentFolderExists(targetFile);
try (FileOutputStream out = new FileOutputStream(targetFile)) {
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
}
}
public static void ensureParentFolderExists(File targetFile) {
ensureFolderExists(targetFile.getParentFile());
}
@Nonnull
public static File ensureFolderExists(File folder) {
if (!folder.exists()) {
log.info("Creating folder: {}", folder.getAbsolutePath());
if (!folder.mkdirs()) {
throw new IllegalArgumentException("Failed to create folder '" + folder.getAbsolutePath() + "'");
}
}
return folder;
}
public static void moveFile(File srcFile, File destFile) {
try {
FileUtils.moveFile(srcFile, destFile);
}
catch (IOException e) {
throw new IllegalStateException("Failed to move file " + srcFile.getAbsolutePath() +
" to " + destFile.getAbsolutePath(), e);
}
}
public static void deleteFolderIfEmpty(@Nonnull File folder) {
if (folder.isDirectory()) {
File[] files = folder.listFiles();
if (files == null || files.length == 0) {
if (folder.delete()) {
log.info("Deleted empty folder: {}", folder.getAbsolutePath());
} else {
log.error("Failed to delete empty folder: {}", folder.getAbsolutePath());
}
}
}
}
}
| src/main/java/com/codeborne/selenide/impl/FileHelper.java | package com.codeborne.selenide.impl;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nonnull;
import javax.annotation.ParametersAreNonnullByDefault;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
@ParametersAreNonnullByDefault
public final class FileHelper {
private static final Logger log = LoggerFactory.getLogger(FileHelper.class);
private FileHelper() {
}
public static void copyFile(File sourceFile, File targetFile) throws IOException {
try (FileInputStream in = new FileInputStream(sourceFile)) {
copyFile(in, targetFile);
}
}
public static void copyFile(InputStream in, File targetFile) throws IOException {
ensureParentFolderExists(targetFile);
try (FileOutputStream out = new FileOutputStream(targetFile)) {
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
}
}
public static void ensureParentFolderExists(File targetFile) {
ensureFolderExists(targetFile.getParentFile());
}
@Nonnull
public static File ensureFolderExists(File folder) {
if (!folder.exists()) {
log.info("Creating folder: {}", folder.getAbsolutePath());
if (!folder.mkdirs()) {
log.error("Failed to create folder: {}", folder.getAbsolutePath());
}
}
return folder;
}
public static void moveFile(File srcFile, File destFile) {
try {
FileUtils.moveFile(srcFile, destFile);
}
catch (IOException e) {
throw new IllegalStateException("Failed to move file " + srcFile.getAbsolutePath() +
" to " + destFile.getAbsolutePath(), e);
}
}
public static void deleteFolderIfEmpty(@Nonnull File folder) {
if (folder.isDirectory()) {
File[] files = folder.listFiles();
if (files == null || files.length == 0) {
if (folder.delete()) {
log.info("Deleted empty folder: {}", folder.getAbsolutePath());
} else {
log.error("Failed to delete empty folder: {}", folder.getAbsolutePath());
}
}
}
}
}
| #1265 report a clear error message if cannot create folder
browser doesn't work without this folder anyway, but reports a strange error like "timeout..."
| src/main/java/com/codeborne/selenide/impl/FileHelper.java | #1265 report a clear error message if cannot create folder | <ide><path>rc/main/java/com/codeborne/selenide/impl/FileHelper.java
<ide> if (!folder.exists()) {
<ide> log.info("Creating folder: {}", folder.getAbsolutePath());
<ide> if (!folder.mkdirs()) {
<del> log.error("Failed to create folder: {}", folder.getAbsolutePath());
<add> throw new IllegalArgumentException("Failed to create folder '" + folder.getAbsolutePath() + "'");
<ide> }
<ide> }
<ide> return folder; |
|
Java | apache-2.0 | f6c2b184b55b7d1641688f7c63c2b71cf8fc0132 | 0 | cherryhill/collectionspace-application | package org.collectionspace.chain.controller;
import static org.junit.Assert.*;
import org.collectionspace.chain.csp.persistence.TestBase;
import org.collectionspace.chain.util.json.JSONUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Test;
import org.mortbay.jetty.testing.HttpTester;
import org.mortbay.jetty.testing.ServletTester;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TestComposite extends TestBase {
private static final Logger log=LoggerFactory.getLogger(TestComposite.class);
private JSONObject createCompositePOSTPartJSON(String payload) throws JSONException {
JSONObject out=new JSONObject();
out.put("path","/cataloging/");
out.put("method","POST");
out.put("body",payload);
return out;
}
private JSONObject createCompositePUTPartJSON(String path,String payload) throws JSONException {
JSONObject out=new JSONObject();
out.put("path",path);
out.put("method","PUT");
out.put("body",payload);
return out;
}
private JSONObject createCompositeGETPartJSON(String path) throws JSONException {
JSONObject out=new JSONObject();
out.put("path",path);
out.put("method","GET");
return out;
}
private JSONObject createCompositeDELETEPartJSON(String path) throws JSONException {
JSONObject out=new JSONObject();
out.put("path",path);
out.put("method","DELETE");
return out;
}
@Test public void testConfigComposite() throws Exception {
ServletTester jetty=setupJetty();
JSONObject ppp=new JSONObject();
JSONObject recordlist=new JSONObject();
recordlist.put("path","/recordlist/uischema");
recordlist.put("method","GET");
ppp.put("recordlist", recordlist);
JSONObject recordtypes=new JSONObject();
recordtypes.put("path","/recordtypes/uischema");
recordtypes.put("method","GET");
recordtypes.put("dataType","json");
ppp.put("recordtypes", recordtypes);
JSONObject objectexit=new JSONObject();
objectexit.put("path","/objectexit/uischema");
objectexit.put("method","GET");
objectexit.put("dataType","json");
ppp.put("objectexit", objectexit);
JSONObject objectexitspec=new JSONObject();
objectexitspec.put("path","/objectexit/uispec");
objectexitspec.put("method","GET");
objectexitspec.put("dataType","json");
ppp.put("uispec", objectexitspec);
JSONObject record=new JSONObject();
record.put("path","/objectexit/5ad847df-904e-4eaf-a01e");
record.put("method","GET");
record.put("dataType","json");
ppp.put("record", record);
log.info(ppp.toString());
HttpTester out3 = GETData("/composite",ppp.toString(),jetty);
JSONObject jout3=new JSONObject(out3.getContent());
log.info(jout3.toString());
}
@Test public void testCompositeBasic() throws Exception {
ServletTester jetty=setupJetty();
// Three POSTs give us some data to play with
JSONObject p1=createCompositePOSTPartJSON(makeSimpleRequest(getResourceString("obj8.json")));
JSONObject p2=createCompositePOSTPartJSON(makeSimpleRequest(getResourceString("obj8.json")));
JSONObject p3=createCompositePOSTPartJSON(makeSimpleRequest(getResourceString("obj8.json")));
JSONObject p=new JSONObject();
p.put("p1",p1);
p.put("p2",p2);
p.put("p3",p3);
log.info("p="+p);
HttpTester out = POSTData("/composite",p.toString(),jetty);
JSONObject jout=new JSONObject(out.getContent());
log.info("POST="+jout);
JSONObject q1=jout.getJSONObject("p1");
JSONObject q2=jout.getJSONObject("p2");
JSONObject q3=jout.getJSONObject("p3");
assertEquals("201",q1.getString("status"));
assertEquals("201",q2.getString("status"));
assertEquals("201",q3.getString("status"));
assertTrue(q1.getString("redirect").startsWith("/cataloging/"));
assertTrue(q2.getString("redirect").startsWith("/cataloging/"));
assertTrue(q3.getString("redirect").startsWith("/cataloging/"));
String id1=q1.getString("redirect");
String id2=q2.getString("redirect");
String id3=q3.getString("redirect");
assertFalse(id1.equals(id2));
assertFalse(id1.equals(id3));
assertFalse(id2.equals(id3));
// Now try some PUTs to update the data
JSONObject p4=createCompositePUTPartJSON(id1,makeSimpleRequest(getResourceString("obj9.json")));
JSONObject p5=createCompositePUTPartJSON(id2,makeSimpleRequest(getResourceString("obj9.json")));
JSONObject pp=new JSONObject();
pp.put("p4",p4);
pp.put("p5",p5);
log.info("pp="+pp);
HttpTester out2 = PUTData("/composite",pp.toString(),jetty);
JSONObject jout2=new JSONObject(out2.getContent());
log.info("PUT="+jout2);
JSONObject q4=jout2.getJSONObject("p4");
JSONObject q5=jout2.getJSONObject("p5");
assertEquals("200",q4.getString("status"));
assertEquals("200",q5.getString("status"));
// Now some GETs
JSONObject ppp=new JSONObject();
ppp.put("p6",createCompositeGETPartJSON(id1));
ppp.put("p7",createCompositeGETPartJSON(id2));
ppp.put("p8",createCompositeGETPartJSON(id3));
log.info("+==============================");
log.info("ppp="+ppp);
HttpTester out3 = GETData("/composite",ppp.toString(),jetty);
JSONObject jout3=new JSONObject(out3.getContent());
JSONObject q6=jout3.getJSONObject("p6");
JSONObject q7=jout3.getJSONObject("p7");
JSONObject q8=jout3.getJSONObject("p8");
assertEquals("200",q6.getString("status"));
assertEquals("200",q7.getString("status"));
assertEquals("200",q8.getString("status"));
log.info("p6="+q6);
JSONObject b6=new JSONObject(q6.getString("body"));
JSONObject b7=new JSONObject(q7.getString("body"));
JSONObject b8=new JSONObject(q8.getString("body"));
assertEquals("4",b6.getJSONObject("fields").getString("objectNumber"));
assertEquals("4",b7.getJSONObject("fields").getString("objectNumber"));
assertEquals("3",b8.getJSONObject("fields").getString("objectNumber"));
// Now some DELETEs
JSONObject pppp=new JSONObject();
pppp.put("p9",createCompositeDELETEPartJSON(id2));
HttpTester out4 = POSTData("/composite",pppp.toString(),jetty);
JSONObject jout4=new JSONObject(out4.getContent());
JSONObject q9=jout4.getJSONObject("p9");
assertEquals("200",q9.getString("status"));
// Try some things that should fail, mixed with some things that should not
JSONObject ppppp=new JSONObject();
ppppp.put("p10",createCompositeGETPartJSON(id1));
ppppp.put("p11",createCompositeGETPartJSON(id2)); // this is failing
ppppp.put("p12",createCompositeGETPartJSON(id3));
log.info("ppppp="+ppppp);
HttpTester out5 = GETData("/composite",ppppp.toString(),jetty);
JSONObject jout5=new JSONObject(out5.getContent());
log.info("jout5="+jout5);
JSONObject q10=jout5.getJSONObject("p10");
JSONObject q11=jout5.getJSONObject("p11");
JSONObject q12=jout5.getJSONObject("p12");
assertEquals("200",q10.getString("status"));
assertEquals("200",q11.getString("status")); // XXX should be 404, but exception handling currently a bit broken
assertEquals("200",q12.getString("status"));
JSONObject b10=new JSONObject(q10.getString("body"));
JSONObject b11=new JSONObject(q11.getString("body"));
JSONObject b12=new JSONObject(q12.getString("body"));
assertEquals("4",b10.getJSONObject("fields").getString("objectNumber"));
assertEquals(true,b11.getBoolean("isError"));
assertEquals("3",b12.getJSONObject("fields").getString("objectNumber"));
}
}
| tomcat-main/src/test/java/org/collectionspace/chain/controller/TestComposite.java | package org.collectionspace.chain.controller;
import static org.junit.Assert.*;
import org.collectionspace.chain.csp.persistence.TestBase;
import org.collectionspace.chain.util.json.JSONUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Test;
import org.mortbay.jetty.testing.HttpTester;
import org.mortbay.jetty.testing.ServletTester;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TestComposite extends TestBase {
private static final Logger log=LoggerFactory.getLogger(TestComposite.class);
private JSONObject createCompositePOSTPartJSON(String payload) throws JSONException {
JSONObject out=new JSONObject();
out.put("path","/cataloging/");
out.put("method","POST");
out.put("body",payload);
return out;
}
private JSONObject createCompositePUTPartJSON(String path,String payload) throws JSONException {
JSONObject out=new JSONObject();
out.put("path",path);
out.put("method","PUT");
out.put("body",payload);
return out;
}
private JSONObject createCompositeGETPartJSON(String path) throws JSONException {
JSONObject out=new JSONObject();
out.put("path",path);
out.put("method","GET");
return out;
}
private JSONObject createCompositeDELETEPartJSON(String path) throws JSONException {
JSONObject out=new JSONObject();
out.put("path",path);
out.put("method","DELETE");
return out;
}
@Test public void testCompositeBasic() throws Exception {
ServletTester jetty=setupJetty();
// Three POSTs give us some data to play with
JSONObject p1=createCompositePOSTPartJSON(makeSimpleRequest(getResourceString("obj8.json")));
JSONObject p2=createCompositePOSTPartJSON(makeSimpleRequest(getResourceString("obj8.json")));
JSONObject p3=createCompositePOSTPartJSON(makeSimpleRequest(getResourceString("obj8.json")));
JSONObject p=new JSONObject();
p.put("p1",p1);
p.put("p2",p2);
p.put("p3",p3);
log.info("p="+p);
HttpTester out = POSTData("/composite",p.toString(),jetty);
JSONObject jout=new JSONObject(out.getContent());
JSONObject q1=jout.getJSONObject("p1");
JSONObject q2=jout.getJSONObject("p2");
JSONObject q3=jout.getJSONObject("p3");
assertEquals("201",q1.getString("status"));
assertEquals("201",q2.getString("status"));
assertEquals("201",q3.getString("status"));
assertTrue(q1.getString("redirect").startsWith("/cataloging/"));
assertTrue(q2.getString("redirect").startsWith("/cataloging/"));
assertTrue(q3.getString("redirect").startsWith("/cataloging/"));
String id1=q1.getString("redirect");
String id2=q2.getString("redirect");
String id3=q3.getString("redirect");
assertFalse(id1.equals(id2));
assertFalse(id1.equals(id3));
assertFalse(id2.equals(id3));
// Now try some PUTs to update the data
JSONObject p4=createCompositePUTPartJSON(id1,makeSimpleRequest(getResourceString("obj9.json")));
JSONObject p5=createCompositePUTPartJSON(id2,makeSimpleRequest(getResourceString("obj9.json")));
JSONObject pp=new JSONObject();
pp.put("p4",p4);
pp.put("p5",p5);
log.info("pp="+pp);
HttpTester out2 = PUTData("/composite",pp.toString(),jetty);
JSONObject jout2=new JSONObject(out2.getContent());
JSONObject q4=jout2.getJSONObject("p4");
JSONObject q5=jout2.getJSONObject("p5");
assertEquals("200",q4.getString("status"));
assertEquals("200",q5.getString("status"));
// Now some GETs
JSONObject ppp=new JSONObject();
ppp.put("p6",createCompositeGETPartJSON(id1));
ppp.put("p7",createCompositeGETPartJSON(id2));
ppp.put("p8",createCompositeGETPartJSON(id3));
log.info("ppp="+ppp);
HttpTester out3 = GETData("/composite",ppp.toString(),jetty);
JSONObject jout3=new JSONObject(out3.getContent());
JSONObject q6=jout3.getJSONObject("p6");
JSONObject q7=jout3.getJSONObject("p7");
JSONObject q8=jout3.getJSONObject("p8");
assertEquals("200",q6.getString("status"));
assertEquals("200",q7.getString("status"));
assertEquals("200",q8.getString("status"));
log.info("p6="+q6);
JSONObject b6=new JSONObject(q6.getString("body"));
JSONObject b7=new JSONObject(q7.getString("body"));
JSONObject b8=new JSONObject(q8.getString("body"));
assertEquals("4",b6.getJSONObject("fields").getString("objectNumber"));
assertEquals("4",b7.getJSONObject("fields").getString("objectNumber"));
assertEquals("3",b8.getJSONObject("fields").getString("objectNumber"));
// Now some DELETEs
JSONObject pppp=new JSONObject();
pppp.put("p9",createCompositeDELETEPartJSON(id2));
HttpTester out4 = POSTData("/composite",pppp.toString(),jetty);
JSONObject jout4=new JSONObject(out4.getContent());
JSONObject q9=jout4.getJSONObject("p9");
assertEquals("200",q9.getString("status"));
// Try some things that should fail, mixed with some things that should not
JSONObject ppppp=new JSONObject();
ppppp.put("p10",createCompositeGETPartJSON(id1));
ppppp.put("p11",createCompositeGETPartJSON(id2)); // this is failing
ppppp.put("p12",createCompositeGETPartJSON(id3));
log.info("ppppp="+ppppp);
HttpTester out5 = GETData("/composite",ppppp.toString(),jetty);
JSONObject jout5=new JSONObject(out5.getContent());
log.info("jout5="+jout5);
JSONObject q10=jout5.getJSONObject("p10");
JSONObject q11=jout5.getJSONObject("p11");
JSONObject q12=jout5.getJSONObject("p12");
assertEquals("200",q10.getString("status"));
assertEquals("200",q11.getString("status")); // XXX should be 404, but exception handling currently a bit broken
assertEquals("200",q12.getString("status"));
JSONObject b10=new JSONObject(q10.getString("body"));
JSONObject b11=new JSONObject(q11.getString("body"));
JSONObject b12=new JSONObject(q12.getString("body"));
assertEquals("4",b10.getJSONObject("fields").getString("objectNumber"));
assertEquals(true,b11.getBoolean("isError"));
assertEquals("3",b12.getJSONObject("fields").getString("objectNumber"));
}
}
| CSPACE-4073 = more testing
| tomcat-main/src/test/java/org/collectionspace/chain/controller/TestComposite.java | CSPACE-4073 = more testing | <ide><path>omcat-main/src/test/java/org/collectionspace/chain/controller/TestComposite.java
<ide> out.put("method","DELETE");
<ide> return out;
<ide> }
<del>
<add> @Test public void testConfigComposite() throws Exception {
<add> ServletTester jetty=setupJetty();
<add> JSONObject ppp=new JSONObject();
<add>
<add> JSONObject recordlist=new JSONObject();
<add> recordlist.put("path","/recordlist/uischema");
<add> recordlist.put("method","GET");
<add>
<add> ppp.put("recordlist", recordlist);
<add>
<add> JSONObject recordtypes=new JSONObject();
<add> recordtypes.put("path","/recordtypes/uischema");
<add> recordtypes.put("method","GET");
<add> recordtypes.put("dataType","json");
<add> ppp.put("recordtypes", recordtypes);
<add>
<add> JSONObject objectexit=new JSONObject();
<add> objectexit.put("path","/objectexit/uischema");
<add> objectexit.put("method","GET");
<add> objectexit.put("dataType","json");
<add> ppp.put("objectexit", objectexit);
<add>
<add> JSONObject objectexitspec=new JSONObject();
<add> objectexitspec.put("path","/objectexit/uispec");
<add> objectexitspec.put("method","GET");
<add> objectexitspec.put("dataType","json");
<add> ppp.put("uispec", objectexitspec);
<add>
<add> JSONObject record=new JSONObject();
<add> record.put("path","/objectexit/5ad847df-904e-4eaf-a01e");
<add> record.put("method","GET");
<add> record.put("dataType","json");
<add> ppp.put("record", record);
<add>
<add>
<add> log.info(ppp.toString());
<add> HttpTester out3 = GETData("/composite",ppp.toString(),jetty);
<add> JSONObject jout3=new JSONObject(out3.getContent());
<add> log.info(jout3.toString());
<add>
<add>
<add>
<add> }
<ide> @Test public void testCompositeBasic() throws Exception {
<ide> ServletTester jetty=setupJetty();
<ide> // Three POSTs give us some data to play with
<ide> log.info("p="+p);
<ide> HttpTester out = POSTData("/composite",p.toString(),jetty);
<ide> JSONObject jout=new JSONObject(out.getContent());
<add> log.info("POST="+jout);
<ide> JSONObject q1=jout.getJSONObject("p1");
<ide> JSONObject q2=jout.getJSONObject("p2");
<ide> JSONObject q3=jout.getJSONObject("p3");
<ide> log.info("pp="+pp);
<ide> HttpTester out2 = PUTData("/composite",pp.toString(),jetty);
<ide> JSONObject jout2=new JSONObject(out2.getContent());
<add> log.info("PUT="+jout2);
<ide> JSONObject q4=jout2.getJSONObject("p4");
<ide> JSONObject q5=jout2.getJSONObject("p5");
<ide> assertEquals("200",q4.getString("status"));
<ide> ppp.put("p6",createCompositeGETPartJSON(id1));
<ide> ppp.put("p7",createCompositeGETPartJSON(id2));
<ide> ppp.put("p8",createCompositeGETPartJSON(id3));
<add> log.info("+==============================");
<ide> log.info("ppp="+ppp);
<ide> HttpTester out3 = GETData("/composite",ppp.toString(),jetty);
<ide> JSONObject jout3=new JSONObject(out3.getContent()); |
|
Java | apache-2.0 | 7dbf994f8692ef7b966e3f4f2ebb81b7ff065c0d | 0 | SSEHUB/EASyProducer,SSEHUB/EASyProducer,SSEHUB/EASyProducer | package net.ssehub.easy.reasoning.sseReasoner;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import net.ssehub.easy.basics.logger.EASyLoggerFactory;
import net.ssehub.easy.basics.logger.EASyLoggerFactory.EASyLogger;
import net.ssehub.easy.basics.modelManagement.Utils;
import net.ssehub.easy.reasoning.core.reasoner.ReasonerConfiguration;
import net.ssehub.easy.reasoning.core.reasoner.ReasonerConfiguration.IAdditionalInformationLogger;
import net.ssehub.easy.reasoning.core.reasoner.ReasoningErrorCodes;
import net.ssehub.easy.reasoning.sseReasoner.functions.FailedElementDetails;
import net.ssehub.easy.reasoning.sseReasoner.functions.FailedElements;
import net.ssehub.easy.reasoning.sseReasoner.functions.ScopeAssignments;
import net.ssehub.easy.reasoning.sseReasoner.model.ContainerConstraintsFinder;
import net.ssehub.easy.reasoning.sseReasoner.model.SubstitutionVisitor;
import net.ssehub.easy.reasoning.sseReasoner.model.DefaultConstraint;
import net.ssehub.easy.reasoning.sseReasoner.model.VariablesInNotSimpleAssignmentConstraintsFinder;
import net.ssehub.easy.reasoning.sseReasoner.model.VariablesMap;
import net.ssehub.easy.varModel.confModel.AssignmentState;
import net.ssehub.easy.varModel.confModel.CompoundVariable;
import net.ssehub.easy.varModel.confModel.Configuration;
import net.ssehub.easy.varModel.confModel.IAssignmentState;
import net.ssehub.easy.varModel.confModel.IConfigurationElement;
import net.ssehub.easy.varModel.confModel.IDecisionVariable;
import net.ssehub.easy.varModel.cst.AttributeVariable;
import net.ssehub.easy.varModel.cst.CSTSemanticException;
import net.ssehub.easy.varModel.cst.CSTUtils;
import net.ssehub.easy.varModel.cst.CompoundAccess;
import net.ssehub.easy.varModel.cst.CompoundInitializer;
import net.ssehub.easy.varModel.cst.ConstantValue;
import net.ssehub.easy.varModel.cst.ConstraintSyntaxTree;
import net.ssehub.easy.varModel.cst.ContainerInitializer;
import net.ssehub.easy.varModel.cst.OCLFeatureCall;
import net.ssehub.easy.varModel.cst.Variable;
import net.ssehub.easy.varModel.cstEvaluation.EvaluationVisitor;
import net.ssehub.easy.varModel.cstEvaluation.EvaluationVisitor.Message;
import net.ssehub.easy.varModel.cstEvaluation.IResolutionListener;
import net.ssehub.easy.varModel.cstEvaluation.IValueChangeListener;
import net.ssehub.easy.varModel.model.AbstractVariable;
import net.ssehub.easy.varModel.model.Attribute;
import net.ssehub.easy.varModel.model.AttributeAssignment;
import net.ssehub.easy.varModel.model.AttributeAssignment.Assignment;
import net.ssehub.easy.varModel.model.Constraint;
import net.ssehub.easy.varModel.model.DecisionVariableDeclaration;
import net.ssehub.easy.varModel.model.IModelElement;
import net.ssehub.easy.varModel.model.ModelVisitorAdapter;
import net.ssehub.easy.varModel.model.OperationDefinition;
import net.ssehub.easy.varModel.model.PartialEvaluationBlock;
import net.ssehub.easy.varModel.model.Project;
import net.ssehub.easy.varModel.model.datatypes.Compound;
import net.ssehub.easy.varModel.model.datatypes.ConstraintType;
import net.ssehub.easy.varModel.model.datatypes.Container;
import net.ssehub.easy.varModel.model.datatypes.DerivedDatatype;
import net.ssehub.easy.varModel.model.datatypes.IDatatype;
import net.ssehub.easy.varModel.model.datatypes.MetaType;
import net.ssehub.easy.varModel.model.datatypes.OclKeyWords;
import net.ssehub.easy.varModel.model.datatypes.TypeQueries;
import net.ssehub.easy.varModel.model.filter.FilterType;
import net.ssehub.easy.varModel.model.filter.VariablesInConstraintFinder;
import net.ssehub.easy.varModel.model.values.ConstraintValue;
import net.ssehub.easy.varModel.model.values.ContainerValue;
import net.ssehub.easy.varModel.model.values.Value;
import net.ssehub.easy.varModel.model.values.ValueDoesNotMatchTypeException;
import net.ssehub.easy.varModel.model.values.ValueFactory;
import static net.ssehub.easy.reasoning.sseReasoner.ReasoningUtils.*;
/**
* Constraint identifier, resolver and executor. Assumption that constraints are not evaluated in parallel (see some
* comments). This resolver can be re-used. Therefore, call {@link #markForReuse()} before the first call to
* {@link #resolve()} and after reasoning completed, call {@link #clear()}. When performing a further reasoning on this
* instance, call {@link #reInit()}.
*
* @author Sizonenko
* @author El-Sharkawy
* @author Holger Eichelberger
*/
public class Resolver {
private static final EASyLogger LOGGER
= EASyLoggerFactory.INSTANCE.getLogger(Resolver.class, Descriptor.BUNDLE_NAME);
@SuppressWarnings("unused")
private IAdditionalInformationLogger infoLogger;
private ReasonerConfiguration reasonerConfig;
private Configuration config;
private boolean incremental = false;
private boolean considerFrozenConstraints = true;
private EvalVisitor evaluator = new EvalVisitor();
private FailedElements failedElements = new FailedElements();
private ScopeAssignments scopeAssignments = new ScopeAssignments();
private VariablesMap constraintMap = new VariablesMap();
private Map<Constraint, IDecisionVariable> constraintVariableMap = new HashMap<Constraint, IDecisionVariable>();
private Deque<Constraint> constraintBase = new LinkedList<Constraint>();
private Deque<Constraint> constraintBaseCopy = null;
private Set<Constraint> constraintBaseSet = new HashSet<Constraint>();
private List<Constraint> defaultConstraints = new LinkedList<Constraint>();
private List<Constraint> deferredDefaultConstraints = new LinkedList<Constraint>();
private List<Constraint> topLevelConstraints = new LinkedList<Constraint>();
private List<Constraint> otherConstraints = new LinkedList<Constraint>();
// Stats
private int constraintCounter = 0;
private int variablesInConstraintsCounter = 0;
private int reevaluationCounter = 0;
private int variablesCounter = 0;
private boolean hasTimeout = false;
private boolean isRunning = false;
private boolean wasStopped = false;
// global temporary variables avoiding parameter passing (performance)
private Project project;
private transient Set<IDecisionVariable> usedVariables = new HashSet<IDecisionVariable>(100);
private transient SubstitutionVisitor substVisitor = new SubstitutionVisitor();
private transient Map<AbstractVariable, CompoundAccess> varMap = new HashMap<AbstractVariable, CompoundAccess>(100);
private transient ContainerConstraintsFinder containerFinder = new ContainerConstraintsFinder();
private transient VariablesInNotSimpleAssignmentConstraintsFinder simpleAssignmentFinder
= new VariablesInNotSimpleAssignmentConstraintsFinder(constraintMap);
private transient ConstraintTranslationVisitor projectVisitor = new ConstraintTranslationVisitor();
private transient VariablesInConstraintFinder variablesFinder = new VariablesInConstraintFinder();
private transient long endTimestamp;
// >>> from here the names follows the reasoner.tex documentation
private IValueChangeListener listener = new IValueChangeListener() {
@Override
public void notifyUnresolved(IDecisionVariable variable) {
}
@Override
public void notifyChanged(IDecisionVariable variable, Value oldValue) {
if (!variable.isLocal()) {
if (Descriptor.LOGGING) {
LOGGER.debug("Value changed: " + variable.getDeclaration().getName() + " " + variable.getValue()
+ " Parent: " + (null == variable.getParent() ? null : variable.getParent()));
}
scopeAssignments.addAssignedVariable(variable);
// TODO if value type changes (currently not part of the notification), change also constraints
rescheduleConstraintsForChilds(variable);
// All constraints for the parent (as this was also changed)
rescheduleConstraintsForParent(variable);
}
}
/**
* Tries rescheduling the given constraints. Does not add a constraint to the constraint base if already
* scheduled.
*
* @param constraints the constraints to reschedule (may be <b>null</b>, ignored then)
*/
private void reschedule(Set<Constraint> constraints) {
if (null != constraints) {
for (Constraint varConstraint : constraints) {
if (!constraintBaseSet.contains(varConstraint)) {
addToConstraintBase(varConstraint);
}
}
}
}
/**
* Determines the constraints needed for the parents of <code>variable</code>.
*
* @param variable the variable to analyze
* @param constraintsToReevaluate the constraint set to be modified as a side effect
*/
private void rescheduleConstraintsForParent(IDecisionVariable variable) {
IConfigurationElement parent = variable.getParent();
if (parent instanceof IDecisionVariable) {
IDecisionVariable pVar = (IDecisionVariable) parent;
AbstractVariable declaration = pVar.getDeclaration();
reschedule(constraintMap.getRelevantConstraints(declaration));
rescheduleConstraintsForParent(pVar);
}
}
/**
* Determines the constraints needed for <code>variable</code> and its (transitive) child slots.
*
* @param variable the variable to analyze
* @param constraintsToReevaluate the constraint set to be modified as a side effect
*/
private void rescheduleConstraintsForChilds(IDecisionVariable variable) {
AbstractVariable declaration = variable.getDeclaration();
reschedule(constraintMap.getRelevantConstraints(declaration));
// All constraints for childs (as they may also changed)
for (int j = 0, nChilds = variable.getNestedElementsCount(); j < nChilds; j++) {
rescheduleConstraintsForChilds(variable.getNestedElement(j));
}
}
};
/**
* Listener for the {@link #evaluator} to record changed variables.
*/
private IResolutionListener resolutionListener = new IResolutionListener() {
@Override
public void notifyResolved(IDecisionVariable compound, String slotName, IDecisionVariable resolved) {
if (!(resolved.isLocal())) {
usedVariables.add(resolved);
}
}
@Override
public void notifyResolved(AbstractVariable declaration, IDecisionVariable resolved) {
if (!(resolved.isLocal())) {
usedVariables.add(resolved);
}
}
};
// <<< documented until here
/**
* Main constructor that activates Resolver constructor.
* @param project Project for evaluation.
* @param config Configuration to reason on.
* @param reasonerConfig the reasoner configuration to be used for reasoning (e.g. taken from the UI,
* may be <b>null</b>)
*/
public Resolver(Project project, Configuration config, ReasonerConfiguration reasonerConfig) {
this.reasonerConfig = reasonerConfig;
this.infoLogger = reasonerConfig.getLogger();
this.config = config;
}
/**
* Main constructor that activates Resolver constructor with clean {@link Configuration}.
* @param project Project for evaluation.
* @param reasonerConfig the reasoner configuration to be used for reasoning (e.g. taken from the UI,
* may be <b>null</b>)
*/
public Resolver(Project project, ReasonerConfiguration reasonerConfig) {
new Resolver(project, createCleanConfiguration(project), reasonerConfig);
}
/**
* Main constructor that activates Resolver constructor.
* @param config Configuration to reason on.
* @param reasonerConfig the reasoner configuration to be used for reasoning (e.g. taken from the UI,
* may be <b>null</b>)
*/
public Resolver(Configuration config, ReasonerConfiguration reasonerConfig) {
new Resolver(config.getProject(), config, reasonerConfig);
}
// >>> from here the names follow the reasoner.tex documentation
/**
* Resolves the (initial) values of the configuration.
*
* @see Utils#discoverImports(net.ssehub.easy.basics.modelManagement.IModel)
* @see #translateConstraints()
* @see #evaluateConstraints()
* @see Configuration#freeze(net.ssehub.easy.varModel.confModel.IFreezeSelector)
*/
public void resolve() {
isRunning = true;
// Stack of importedProject (start with inner most imported project)
evaluator.init(config, null, false, listener); // also for defaults as they may refer to each other
evaluator.setResolutionListener(resolutionListener);
evaluator.setScopeAssignments(scopeAssignments);
List<Project> projects = Utils.discoverImports(config.getProject());
endTimestamp = reasonerConfig.getTimeout() <= 0
? -1 : System.currentTimeMillis() + reasonerConfig.getTimeout();
for (int p = 0; !hasTimeout && !wasStopped && p < projects.size(); p++) {
project = projects.get(p);
if (Descriptor.LOGGING) {
LOGGER.debug("Project:" + project.getName());
}
translateConstraints();
evaluateConstraints();
// Freezes values after each scope
config.freezeValues(project, FilterType.NO_IMPORTS);
// TODO do incremental freezing in here -> required by interfaces with propagation constraints
if (Descriptor.LOGGING) {
printFailedElements(failedElements);
}
}
evaluator.clear();
isRunning = false;
}
/**
* Evaluates and reschedules failed constraints.
*
* @see #resolve()
*/
private void evaluateConstraints() {
if (Descriptor.LOGGING) {
printConstraints(constraintBase);
}
scopeAssignments.clearScopeAssignments();
evaluator.setDispatchScope(project);
while (!constraintBase.isEmpty() && !wasStopped) { // reasoner.tex -> hasTimeout see end of loop
usedVariables.clear();
Constraint constraint = constraintBase.pop();
constraintBaseSet.remove(constraint);
ConstraintSyntaxTree cst = constraint.getConsSyntax();
evaluator.setAssignmentState(constraint.isDefaultConstraint()
? AssignmentState.DEFAULT : AssignmentState.DERIVED);
reevaluationCounter++;
if (cst != null) {
if (Descriptor.LOGGING) {
LOGGER.debug("Resolving: " + reevaluationCounter + ": " + toIvmlString(cst)
+ " : " + constraint.getTopLevelParent());
}
evaluator.visit(cst);
analyzeEvaluationResult(constraint);
if (Descriptor.LOGGING) {
LOGGER.debug("Result: " + evaluator.getResult());
LOGGER.debug("------");
}
evaluator.clearIntermediary();
}
if (endTimestamp > 0 && System.currentTimeMillis() > endTimestamp) {
hasTimeout = true;
break;
}
}
}
/**
* Visits the contents of a project for translation. Do not store stateful information in this class.
*
* @author Holger Eichelberger
*/
private class ConstraintTranslationVisitor extends ModelVisitorAdapter {
// don't follow project imports here, just structural top-level traversal of the actual project!
private List<PartialEvaluationBlock> evals = null;
@Override // iterate over all elements declared in project, implicitly skipping not implemented elements
public void visitProject(Project project) {
for (int e = 0; e < project.getElementCount(); e++) {
project.getElement(e).accept(this);
}
if (null != evals) {
// prioritize top-level project contents over eval blocks
for (PartialEvaluationBlock block : evals) {
for (int i = 0; i < block.getNestedCount(); i++) {
block.getNested(i).accept(this);
}
for (int i = 0; i < block.getEvaluableCount(); i++) {
block.getEvaluable(i).accept(this);
}
}
}
}
@Override // translate all top-level/enum/attribute assignment declarations
public void visitDecisionVariableDeclaration(DecisionVariableDeclaration decl) {
translateDeclaration(decl, config.getDecision(decl), null);
}
@Override // collect all top-level/enum/attribute assignment constraints
public void visitConstraint(Constraint constraint) {
addConstraint(topLevelConstraints, constraint, true); // topLevelConstraints
}
@Override // iterate over nested blocks/contained constraints
public void visitPartialEvaluationBlock(PartialEvaluationBlock block) {
if (null == evals) {
evals = new LinkedList<PartialEvaluationBlock>();
}
evals.add(block);
}
@Override // iterate over nested blocks/contained, translate the individual blocks if not incremental
public void visitAttributeAssignment(AttributeAssignment assignment) {
for (int v = 0; v < assignment.getElementCount(); v++) {
assignment.getElement(v).accept(this);
}
for (int a = 0; a < assignment.getAssignmentCount(); a++) {
assignment.getAssignment(a).accept(this);
}
if (!incremental) {
translateAnnotationAssignments(assignment, null, null);
}
}
}
/**
* Extracts, translates and collects the internal constraints of <code>type</code> and stores them
* in {@link #derivedTypeConstraints}.
*
* @param decl VariableDeclaration of <code>DerivedDatatype</code>
* @param dType the type to translate
*/
private void translateDerivedDatatypeConstraints(AbstractVariable decl, DerivedDatatype dType) {
ConstraintSyntaxTree[] cst = createDerivedDatatypeExpressions(decl, dType);
if (null != cst) {
IModelElement topLevelParent = decl.getTopLevelParent();
for (int c = 0; c < cst.length; c++) {
// Should be in same project as the declaration belongs to
try { // derivedTypeConstraints
ConstraintSyntaxTree tmp = substituteVariables(cst[c], null, null, true);
addConstraint(topLevelConstraints, new Constraint(tmp, topLevelParent), true);
} catch (CSTSemanticException e) {
LOGGER.exception(e);
}
}
}
IDatatype basis = dType.getBasisType();
if (basis instanceof DerivedDatatype) {
translateDerivedDatatypeConstraints(decl, (DerivedDatatype) basis);
}
}
/**
* Translates constraint expressions specified for derived datatypes.
*
* @param declaration VariableDeclaration of <code>DerivedDatatype</code>
* @param dType type of <code>DerivedDatatype</code>
* @return the created constraints
*/
private ConstraintSyntaxTree[] createDerivedDatatypeExpressions(AbstractVariable declaration,
DerivedDatatype dType) {
ConstraintSyntaxTree[] csts = null;
int count = dType.getConstraintCount();
DecisionVariableDeclaration dVar = dType.getTypeDeclaration();
if (count > 0 && dVar != declaration) {
csts = new ConstraintSyntaxTree[count];
Variable replacement = new Variable(declaration);
//Copy and replace each instance of the internal declaration with the given instance
for (int i = 0; i < count; i++) {
substVisitor.addVariableMapping(dVar, replacement);
csts[i] = substVisitor.acceptAndClear(dType.getConstraint(i).getConsSyntax());
}
}
return csts;
}
/**
* Translates annotation default value expressions.
*
* @param decl {@link AbstractVariable} with annotations.
* @param variable {@link IDecisionVariable} with annotations.
* @param compound {@link CompoundAccess} null if variable is not nested.
*/
private void translateAnnotationDefaults(AbstractVariable decl, IDecisionVariable variable,
CompoundAccess compound) {
for (int i = 0; i < variable.getAttributesCount(); i++) {
Attribute attribute = (Attribute) variable.getAttribute(i).getDeclaration();
ConstraintSyntaxTree defaultValue = attribute.getDefaultValue();
if (null != defaultValue) {
try {
ConstraintSyntaxTree op;
if (compound == null) {
op = new AttributeVariable(new Variable(decl), attribute);
} else {
op = new AttributeVariable(compound, attribute);
}
defaultValue = new OCLFeatureCall(op, OclKeyWords.ASSIGNMENT, defaultValue);
defaultValue.inferDatatype(); // defaultAnnotationConstraints
addConstraint(otherConstraints, new DefaultConstraint(defaultValue, project), false);
} catch (CSTSemanticException e) {
e.printStackTrace();
}
}
}
}
/**
* Translates the (transitive) defaults and type constraints for a declaration.
*
* @param decl The {@link AbstractVariable} for which the default value should be resolved.
* @param var the instance of <tt>decl</tt>.
* @param cAcc if variable is a nested compound.
*/
protected void translateDeclaration(AbstractVariable decl, IDecisionVariable var, CompoundAccess cAcc) {
variablesCounter++;
IDatatype type = decl.getType();
ConstraintSyntaxTree defaultValue = decl.getDefaultValue();
AbstractVariable self = null;
ConstraintSyntaxTree selfEx = null;
if (type instanceof DerivedDatatype) {
translateDerivedDatatypeConstraints(decl, (DerivedDatatype) type);
}
if (!incremental) {
translateAnnotationDefaults(decl, var, cAcc);
}
if (null != defaultValue) { // considering the actual type rather than base, after derived (!)
type = inferTypeSafe(defaultValue, type);
}
if (TypeQueries.isCompound(type)) { // this is a compound value -> default constraints, do not defer
self = decl;
translateCompoundDeclaration(decl, var, cAcc, type);
} else if (TypeQueries.isContainer(type)) { // this is a container value -> default constraints, do not defer
translateContainerDeclaration(decl, var, type);
} else if (null != defaultValue && !incremental) {
if (null != cAcc) { // defer self/override init constraints to prevent accidental init override
selfEx = cAcc.getCompoundExpression();
}
} else if (incremental) { // remaining defaults
defaultValue = null;
}
if (null != defaultValue) {
try {
if (TypeQueries.isConstraint(decl.getType())) { // handle and register constraint variables
variablesCounter--;
// use closest parent instead of project -> runtime analysis
createConstraintVariableConstraint(defaultValue, selfEx, self, var.getDeclaration(), var);
} else { // Create default constraint
defaultValue = new OCLFeatureCall(null != selfEx ? cAcc : new Variable(decl),
OclKeyWords.ASSIGNMENT, defaultValue);
defaultValue = substituteVariables(defaultValue, selfEx, self, false);
List<Constraint> targetCons = defaultConstraints;
if (substVisitor.containsSelf() || isOverriddenSlot(decl)) {
targetCons = deferredDefaultConstraints;
}
addConstraint(targetCons, new DefaultConstraint(defaultValue, project), true);
}
substVisitor.clear(); // clear false above
} catch (CSTSemanticException e) {
LOGGER.exception(e); // should not occur, ok to log
}
}
}
/**
* Translates the (transitive) defaults and type constraints for a container declaration.
*
* @param decl The {@link AbstractVariable} for which the default value should be resolved.
* @param var the instance of <tt>decl</tt>.
* @param type the (specific) datatype ({@link Container})
*/
private void translateContainerDeclaration(AbstractVariable decl, IDecisionVariable var, IDatatype type) {
if (null != decl.getDefaultValue() && !incremental) {
Set<Compound> used = getUsedTypes(decl.getDefaultValue(), Compound.class);
if (null != used && !used.isEmpty()) {
Set<Compound> done = new HashSet<Compound>();
for (Compound uType : used) {
translateDefaultsCompoundContainer(decl, uType, done);
done.clear();
}
}
}
translateContainerCompoundConstraints(decl, var, null, otherConstraints);
IDatatype containedType = ((Container) type).getContainedType();
if (containedType instanceof DerivedDatatype) {
translateContainerDerivedDatatypeConstraints((DerivedDatatype) containedType, decl, null);
}
}
/**
* Translates constraints representing compound defaults in containers of compounds.
*
* @param decl the container variable
* @param cmpType the compound type used in the actual <code>decl</code> value to focus the constraints created
* @param done the already processed types (to be modified as a side effect)
*/
private void translateDefaultsCompoundContainer(AbstractVariable decl, Compound cmpType, Set<Compound> done) {
if (!done.contains(cmpType)) {
done.add(cmpType);
for (int d = 0; d < cmpType.getDeclarationCount(); d++) {
DecisionVariableDeclaration uDecl = cmpType.getDeclaration(d);
ConstraintSyntaxTree defaultValue = uDecl.getDefaultValue();
if (null != defaultValue) {
DecisionVariableDeclaration localDecl = new DecisionVariableDeclaration("cmp", cmpType, null);
try {
Variable localDeclVar = new Variable(localDecl);
defaultValue = substituteVariables(defaultValue, localDeclVar, null, true); // replace self
defaultValue = new OCLFeatureCall(new CompoundAccess(localDeclVar, uDecl.getName()),
OclKeyWords.ASSIGNMENT, defaultValue);
ConstraintSyntaxTree containerOp = new Variable(decl);
if (!TypeQueries.sameTypes(decl.getType(), cmpType)) {
containerOp = new OCLFeatureCall(containerOp, OclKeyWords.TYPE_SELECT,
new ConstantValue(ValueFactory.createValue(MetaType.TYPE, cmpType)));
}
if (isNestedContainer(decl.getType())) {
containerOp = new OCLFeatureCall(containerOp, OclKeyWords.FLATTEN);
}
defaultValue = createContainerCall(containerOp, Container.FORALL, defaultValue, localDecl);
defaultValue.inferDatatype();
addConstraint(deferredDefaultConstraints, new DefaultConstraint(defaultValue, project), true);
} catch (CSTSemanticException e) {
LOGGER.exception(e); // should not occur, ok to log
} catch (ValueDoesNotMatchTypeException e) {
LOGGER.exception(e); // should not occur, ok to log
}
}
}
// attributes??
for (int r = 0; r < cmpType.getRefinesCount(); r++) {
translateDefaultsCompoundContainer(decl, cmpType.getRefines(r), done);
}
}
}
/**
* Method for translating the internal constraint from containers with derived contained types.
*
* @param derivedType {@link DerivedDatatype} of the container.
* @param decl container variable.
* @param access {@link CompoundAccess}, might be <b>null</b>.
*/
private void translateContainerDerivedDatatypeConstraints(DerivedDatatype derivedType,
AbstractVariable decl, CompoundAccess access) {
// as long as evaluation is not parallelized, using the same localDecl shall not be a problem
DecisionVariableDeclaration localDecl = new DecisionVariableDeclaration("derivedType", derivedType, null);
ConstraintSyntaxTree[] cst = createDerivedDatatypeExpressions(localDecl, derivedType);
if (null != cst) {
for (int i = 0, n = cst.length; i < n; i++) {
ConstraintSyntaxTree itExpression = cst[i];
ConstraintSyntaxTree typeCst = null;
if (access == null) {
typeCst = createContainerCall(new Variable(decl), Container.FORALL, itExpression, localDecl);
} else {
typeCst = createContainerCall(access, Container.FORALL, itExpression, localDecl);
}
try {
typeCst.inferDatatype();
typeCst = substituteVariables(typeCst, null, null, true); // derivedTypeConstraints
addConstraint(topLevelConstraints, new Constraint(typeCst, project), true);
} catch (CSTSemanticException e) {
LOGGER.exception(e);
}
}
}
IDatatype basis = derivedType.getBasisType();
if (basis instanceof DerivedDatatype) {
translateContainerDerivedDatatypeConstraints((DerivedDatatype) basis, decl, access);
}
}
/**
* Method for retrieving constraints from compounds initialized in containers. <code>variable</code>
* must be a container and <code>decl</code> of type container.
*
* @param decl AbstractVariable.
* @param variable the instance of <tt>decl</tt>.
* @param topcmpAccess {@link CompoundAccess} if container is a nested element.
* @param results the resulting constraints
*/
private void translateContainerCompoundConstraints(AbstractVariable decl, IDecisionVariable variable,
CompoundAccess topcmpAccess, List<Constraint> results) {
IDatatype containedType = ((Container) decl.getType()).getContainedType();
for (IDatatype tmp : identifyContainedTypes(variable, containedType)) {
if (TypeQueries.isCompound(tmp)) {
translateContainerCompoundConstraints((Compound) tmp, containedType, decl, topcmpAccess, results);
}
}
}
/**
* Method for transforming a compound constraint into container forAll constraint.
* @param cmpType Specific compound type (with constraints).
* @param declaredContainedType the declared contained type of the container.
* @param decl {@link AbstractVariable}.
* @param topcmpAccess {@link CompoundAccess} if container is a nested element.
* @param result List of transformed constraints, to be modified as a side effect.
*/
private void translateContainerCompoundConstraints(Compound cmpType, IDatatype declaredContainedType,
AbstractVariable decl, CompoundAccess topcmpAccess, List<Constraint> result) {
DecisionVariableDeclaration localDecl = new DecisionVariableDeclaration("cmp", cmpType, null);
// fill varMap
for (int i = 0, n = cmpType.getInheritedElementCount(); i < n; i++) {
AbstractVariable nestedDecl = cmpType.getInheritedElement(i);
CompoundAccess cmpAccess = null;
cmpAccess = new CompoundAccess(new Variable(localDecl), nestedDecl.getName());
varMap.put(nestedDecl, cmpAccess);
}
List<Constraint> thisCompoundConstraints = new ArrayList<Constraint>();
allCompoundConstraints(cmpType, thisCompoundConstraints, true);
ConstraintSyntaxTree typeExpression = null;
if (!TypeQueries.sameTypes(cmpType, declaredContainedType)) {
typeExpression = createTypeValueConstantSafe(cmpType);
}
for (int i = 0; i < thisCompoundConstraints.size(); i++) {
ConstraintSyntaxTree itExpression = thisCompoundConstraints.get(i).getConsSyntax();
itExpression = substituteVariables(itExpression, null, localDecl, true);
if (Descriptor.LOGGING) {
LOGGER.debug("New loop constraint " + toIvmlString(itExpression));
}
try {
ConstraintSyntaxTree containerOp = topcmpAccess == null ? new Variable(decl) : topcmpAccess;
containerOp.inferDatatype();
if (null != typeExpression) {
containerOp = new OCLFeatureCall(containerOp, Container.SELECT_BY_KIND.getName(), typeExpression);
}
if (containerOp != null) {
containerOp.inferDatatype();
containerOp = createContainerCall(containerOp, Container.FORALL, itExpression, localDecl);
}
if (containerOp != null) {
containerOp.inferDatatype();
addConstraint(result, new Constraint(containerOp, project), true);
}
} catch (CSTSemanticException e) {
LOGGER.exception(e);
}
}
}
/**
* Method for translating compound default value declarations. Requires
* {@link #buildVariableMapping(AbstractVariable, IDecisionVariable, CompoundAccess, IDatatype)} before.
*
* @param decl The {@link AbstractVariable} for which the default value should be resolved.
* @param variable the instance of <tt>decl</tt>.
* @param compound if variable is a nested compound, the access expression to
* <code>decl</code>/<code>variable</code>
* @param type specific {@link Compound} type.
*/
private void translateCompoundDeclaration(AbstractVariable decl, IDecisionVariable variable,
CompoundAccess compound, IDatatype type) {
Compound cmpType = (Compound) type;
CompoundVariable cmpVar = (CompoundVariable) variable;
// resolve compound access first for all slots
for (int i = 0, n = cmpVar.getNestedElementsCount(); i < n; i++) {
IDecisionVariable nestedVar = cmpVar.getNestedElement(i);
AbstractVariable nestedDecl = nestedVar.getDeclaration();
CompoundAccess cmpAccess;
if (compound == null) {
cmpAccess = new CompoundAccess(new Variable(decl), nestedDecl.getName());
} else {
cmpAccess = new CompoundAccess(createAsTypeCast(compound, type, cmpVar.getValue().getType()),
nestedDecl.getName());
}
inferTypeSafe(cmpAccess, null);
// fill varMap
varMap.put(nestedDecl, cmpAccess);
}
for (int i = 0, n = cmpVar.getNestedElementsCount(); i < n; i++) {
IDecisionVariable nestedVar = cmpVar.getNestedElement(i);
AbstractVariable nestedDecl = nestedVar.getDeclaration();
translateDeclaration(nestedDecl, cmpVar.getNestedVariable(nestedDecl.getName()),
varMap.get(nestedDecl));
}
// create constraints on mutually interacting constraints now
for (int i = 0, n = cmpVar.getNestedElementsCount(); i < n; i++) {
IDecisionVariable nestedVar = cmpVar.getNestedElement(i);
AbstractVariable nestedDecl = nestedVar.getDeclaration();
IDatatype nestedType = nestedDecl.getType();
if (Container.isContainer(nestedType, ConstraintType.TYPE)
&& nestedVar.getValue() instanceof ContainerValue) {
createContainerConstraintValueConstraints((ContainerValue) nestedVar.getValue(), decl, nestedDecl,
nestedVar);
}
if (TypeQueries.isContainer(nestedType)) {
translateContainerCompoundConstraints(nestedDecl, variable, varMap.get(nestedDecl),
otherConstraints);
}
}
// Nested attribute assignments handling
if (!incremental) {
for (int a = 0; a < cmpType.getAssignmentCount(); a++) {
translateAnnotationAssignments(cmpType.getAssignment(a), null, compound);
}
}
List<Constraint> thisCompoundConstraints = new ArrayList<Constraint>();
allCompoundConstraints(cmpType, thisCompoundConstraints, false);
for (int i = 0; i < thisCompoundConstraints.size(); i++) {
ConstraintSyntaxTree oneConstraint = thisCompoundConstraints.get(i).getConsSyntax();
// changed null to decl
oneConstraint = substituteVariables(oneConstraint, null, decl, true);
try { // compoundConstraints
Constraint constraint = new Constraint(oneConstraint, decl);
addConstraint(otherConstraints, constraint, true);
} catch (CSTSemanticException e) {
LOGGER.exception(e);
}
}
processCompoundEvals(cmpType);
}
/**
* Method for extracting constraints from compounds eval blocks (also refined compounds).
* @param cmpType Compound to be analyzed
*/
private void processCompoundEvals(Compound cmpType) {
for (int r = 0; r < cmpType.getRefinesCount(); r++) {
processCompoundEvals(cmpType.getRefines(r));
}
for (int i = 0; i < cmpType.getModelElementCount(); i++) {
if (cmpType.getModelElement(i) instanceof PartialEvaluationBlock) {
PartialEvaluationBlock evalBlock = (PartialEvaluationBlock) cmpType.getModelElement(i);
processEvalConstraints(evalBlock);
}
}
}
/**
* Method for handling eval blocks - searching for nested eval blocks and extracting constraints.
* @param evalBlock Eval block to be processed.
*/
private void processEvalConstraints(PartialEvaluationBlock evalBlock) {
for (int i = 0; i < evalBlock.getNestedCount(); i++) {
processEvalConstraints(evalBlock.getNested(i));
}
for (int i = 0; i < evalBlock.getEvaluableCount(); i++) {
if (evalBlock.getEvaluable(i) instanceof Constraint) {
Constraint evalConstraint = (Constraint) evalBlock.getEvaluable(i);
ConstraintSyntaxTree evalCst = evalConstraint.getConsSyntax();
ConstraintSyntaxTree cst = substituteVariables(evalCst, null, null, true);
try {
addConstraint(otherConstraints, new Constraint(cst, project), true);
} catch (CSTSemanticException e) {
LOGGER.exception(e);
}
}
}
}
/**
* Creates a constraint from a (nested) constraint variable adding the result to
* {@link #constraintVariablesConstraints}.
*
* @param cst the constraint
* @param selfEx the expression representing <i>self</i> in <code>cst</code>, both, <code>self</code> and
* <code>selfEx</code> must not be different from <b>null</b> at the same time (may be <b>null</b> for none)
* @param self the declaration of the variable representing <i>self</i> in <code>cst</code> (may be <b>null</b>
* for none)
* @param parent the parent for new constraints
* @param variable the actually (nested) variable, used to fill {@link #constraintVariableMap}
* @return the created constraint
*/
private Constraint createConstraintVariableConstraint(ConstraintSyntaxTree cst, ConstraintSyntaxTree selfEx,
AbstractVariable self, IModelElement parent, IDecisionVariable variable) {
Constraint constraint = null;
if (cst != null) {
cst = substituteVariables(cst, selfEx, self, true);
try {
constraint = new Constraint(cst, parent);
addConstraint(otherConstraints, constraint, true); // constraintVariablesConstraints
// TODO reverse mapping for changing constraint types through value upon value change
constraintVariableMap.put(constraint, variable);
if (Descriptor.LOGGING) {
LOGGER.debug((null != self ? self.getName() + "." : "") + variable.getDeclaration().getName()
+ " compound constraint variable " + toIvmlString(cst));
}
} catch (CSTSemanticException e) {
LOGGER.exception(e);
}
}
return constraint;
}
/**
* Checks a container value for nested constraint values, i.e., values of nested constraint variables.
*
* @param val the container value
* @param decl the variable declaration representing <i>self</i> in the container/constraint value
* @param parent the parent for new constraints
* @param nestedVariable the variable holding the constraint value
*/
private void createContainerConstraintValueConstraints(ContainerValue val, AbstractVariable decl,
IModelElement parent, IDecisionVariable nestedVariable) {
for (int n = 0; n < val.getElementSize(); n++) {
Value cVal = val.getElement(n);
if (cVal instanceof ConstraintValue) {
ConstraintValue constraint = (ConstraintValue) cVal;
createConstraintVariableConstraint(constraint.getValue(), null, decl, parent, nestedVariable);
}
}
}
/**
* Translates attribute assignments. It is important to recall that in case of nested (orthogonal) attribute
* assignments, the outer one(s) must also be applied to the inner ones.
*
* @param assignment Attribute assignments on top-level.
* @param effectiveAssignments the list of effective current assignments, use <b>null</b> if not recursive.
* @param compound Parent {@link CompoundAccess}.
*/
private void translateAnnotationAssignments(AttributeAssignment assignment, List<Assignment> effectiveAssignments,
CompoundAccess compound) {
List<Assignment> assng = null == effectiveAssignments ? new ArrayList<Assignment>() : effectiveAssignments;
for (int d = 0; d < assignment.getAssignmentDataCount(); d++) {
assng.add(assignment.getAssignmentData(d));
}
for (int d = 0; d < assng.size(); d++) {
Assignment effectiveAssignment = assng.get(d);
for (int e = 0; e < assignment.getElementCount(); e++) {
DecisionVariableDeclaration aElt = assignment.getElement(e);
IDatatype aEltType = aElt.getType();
translateAnnotationAssignment(effectiveAssignment, aElt, compound);
if (TypeQueries.isCompound(aEltType)) {
Compound cmp = (Compound) aEltType;
for (int s = 0; s < cmp.getDeclarationCount(); s++) {
DecisionVariableDeclaration slot = cmp.getDeclaration(s);
CompoundAccess cmpAccess;
if (compound == null) {
cmpAccess = new CompoundAccess(new Variable(aElt), slot.getName());
} else {
cmpAccess = new CompoundAccess(compound, slot.getName());
}
varMap.put(slot, cmpAccess);
inferTypeSafe(cmpAccess, null);
}
for (int s = 0; s < cmp.getDeclarationCount(); s++) {
DecisionVariableDeclaration slot = cmp.getDeclaration(s);
translateAnnotationAssignment(effectiveAssignment, slot, varMap.get(slot));
}
}
}
}
for (int a = 0; a < assignment.getAssignmentCount(); a++) {
translateAnnotationAssignments(assignment.getAssignment(a), assng, compound);
}
}
/**
* Method for creating attribute constraint for a specific element.
* @param assignment Attribute assignment constraint.
* @param element Elements to which the attribute is assigned.
* @param compound Nesting compound if there is one, may be <b>null</b> for none.
*/
private void translateAnnotationAssignment(Assignment assignment, DecisionVariableDeclaration element,
CompoundAccess compound) {
String attributeName = assignment.getName();
Attribute attrib = (Attribute) element.getAttribute(attributeName);
if (null != attrib) {
ConstraintSyntaxTree cst;
//handle annotations in compounds
if (null == compound) {
compound = varMap.get(element);
}
if (compound == null) {
cst = new AttributeVariable(new Variable(element), attrib);
} else {
cst = new AttributeVariable(compound, attrib);
}
cst = new OCLFeatureCall(cst, OclKeyWords.ASSIGNMENT,
substituteVariables(assignment.getExpression(), null, null, true));
inferTypeSafe(cst, null);
try { // assignedAttributeConstraints
addConstraint(otherConstraints, new Constraint(cst, project), false);
} catch (CSTSemanticException e) {
LOGGER.exception(e);
}
}
}
/**
* Translates and collects all constraints in {@link #project} by adding the collected constraints to the
* {@link #constraintBase}.
*
* @see #resolve()
*/
private void translateConstraints() {
// translate only if not marked for reuse and copy of constraint base is already available
if (null == constraintBaseCopy || constraintBaseCopy.isEmpty()) {
varMap.clear();
project.accept(projectVisitor);
addAllToConstraintBase(defaultConstraints);
addAllToConstraintBase(deferredDefaultConstraints);
addAllToConstraintBase(topLevelConstraints);
addAllToConstraintBase(otherConstraints);
constraintCounter = constraintBase.size();
variablesInConstraintsCounter = constraintMap.getDeclarationSize();
clearConstraintLists();
// if marked for re-use, copy constraint base
if (null != constraintBaseCopy) {
constraintBaseCopy.addAll(constraintBase);
}
}
}
/**
* Adding a constraint to a constraint set, checking for contained container/compound initializers if
* requested.
*
* @param target the target container to add the constraint to
* @param constraint the constraint
* @param checkForInitializers check also for initializers if (<code>true</code>), add only if (<code>false</code>)
*/
private void addConstraint(Collection<Constraint> target, Constraint constraint, boolean checkForInitializers) {
ConstraintSyntaxTree cst = constraint.getConsSyntax();
boolean add = true;
if (incremental) {
add = !CSTUtils.isAssignment(cst);
}
if (add && !considerFrozenConstraints) {
variablesFinder.setConfiguration(config);
cst.accept(variablesFinder);
Set<IAssignmentState> states = variablesFinder.getStates();
add = (!(1 == states.size() && states.contains(AssignmentState.FROZEN)));
variablesFinder.clear();
}
if (add) {
if (checkForInitializers) {
containerFinder.accept(cst);
if (containerFinder.isConstraintContainer()) {
checkContainerInitializer(containerFinder.getExpression(), false, constraint.getParent());
}
if (containerFinder.isCompoundInitializer()) {
checkCompoundInitializer(containerFinder.getExpression(), true, constraint.getParent());
}
containerFinder.clear();
}
target.add(constraint);
simpleAssignmentFinder.acceptAndClear(constraint);
}
}
/**
* Method for checking if {@link CompoundInitializer} holds
* a {@link de.uni_hildesheim.sse.ivml.CollectionInitializer} with {@link Constraint}s.
* @param exp expression to check.
* @param substituteVars <code>true</code> if {@link #varMap} shall be applied to substitute variables in
* <code>exp</code> (if variable is nested), <code>false</code> if <code>exp</code> shall be taken over as it is.
* @param parent parent for temporary constraints
*/
private void checkCompoundInitializer(ConstraintSyntaxTree exp, boolean substituteVars, IModelElement parent) {
CompoundInitializer compoundInit = (CompoundInitializer) exp;
for (int i = 0; i < compoundInit.getExpressionCount(); i++) {
if (compoundInit.getExpression(i) instanceof ContainerInitializer) {
checkContainerInitializer(compoundInit.getExpression(i), substituteVars, parent);
}
if (compoundInit.getExpression(i) instanceof CompoundInitializer) {
checkCompoundInitializer(compoundInit.getExpression(i), substituteVars, parent);
}
}
}
/**
* Method for checking if an expression is a {@link ContainerInitializer}.
* @param exp expression to be checked.
* @param substituteVars <code>true</code> if {@link #varMap} shall be applied to substitute variables in
* <code>exp</code> (if variable is nested), <code>false</code> if <code>exp</code> shall be taken over as it is.
* @param parent parent for temporary constraints
*/
private void checkContainerInitializer(ConstraintSyntaxTree exp, boolean substituteVars, IModelElement parent) {
ContainerInitializer containerInit = (ContainerInitializer) exp;
if (ConstraintType.TYPE.isAssignableFrom(containerInit.getType().getContainedType())) {
for (int i = 0; i < containerInit.getExpressionCount(); i++) {
Constraint constraint = new Constraint(parent);
ConstraintSyntaxTree cst = containerInit.getExpression(i);
if (substituteVars) {
cst = substituteVariables(cst, null, null, true);
}
try {
constraint.setConsSyntax(cst);
addConstraint(otherConstraints, constraint, false); // collectionConstraints
} catch (CSTSemanticException e) {
LOGGER.exception(e);
}
}
}
}
/**
* Method for getting all constraints relevant to a {@link Compound}.
* @param cmpType Compound to be analyzed.
* @param thisCompoundConstraints The list to add the compound {@link Constraint}s to.
* @param host True if this is a host compound.
*/
private void allCompoundConstraints(Compound cmpType,
List<Constraint> thisCompoundConstraints, boolean host) {
for (int i = 0; i < cmpType.getConstraintsCount(); i++) {
thisCompoundConstraints.add(cmpType.getConstraint(i));
}
if (host) { // TODO why not constraint expr via refines?
for (int i = 0; i < cmpType.getInheritedElementCount(); i++) {
DecisionVariableDeclaration decl = cmpType.getInheritedElement(i);
ConstraintSyntaxTree defaultValue = decl.getDefaultValue();
if (null != defaultValue) {
if (ConstraintType.TYPE.isAssignableFrom(decl.getType())) {
Constraint constraint = new Constraint(project);
try {
constraint.setConsSyntax(defaultValue);
thisCompoundConstraints.add(constraint);
} catch (CSTSemanticException e) {
LOGGER.exception(e);
}
}
}
}
}
for (int r = 0; r < cmpType.getRefinesCount(); r++) {
allCompoundConstraints(cmpType.getRefines(r), thisCompoundConstraints, false);
}
for (int a = 0; a < cmpType.getAssignmentCount(); a++) {
allAssignmentConstraints(cmpType.getAssignment(a), thisCompoundConstraints);
}
}
/**
* Collects all assignment constraints and adds them to <code>result</code>.
*
* @param assng the assignment constraint
* @param result the list of constraints to be modified as a side effect
*/
private void allAssignmentConstraints(AttributeAssignment assng, List<Constraint> result) {
for (int c = 0; c < assng.getConstraintsCount(); c++) {
result.add(assng.getConstraint(c));
}
for (int a = 0; a < assng.getAssignmentCount(); a++) {
allAssignmentConstraints(assng.getAssignment(a), result);
}
}
// <<< documented until here
// messages
/**
* Records information about the evaluation result, failed evaluation messages.
*
* @param constraint the constraint to record the actual messages for
*/
private void analyzeEvaluationResult(Constraint constraint) {
if (evaluator.constraintFailed()) {
FailedElementDetails failedElementDetails = new FailedElementDetails();
failedElementDetails.setProblemPoints(new HashSet<IDecisionVariable>(usedVariables));
failedElementDetails.setProblemConstraintPart(getFailedConstraintPart());
failedElementDetails.setProblemConstraint(constraint);
failedElementDetails.setErrorClassifier(ReasoningErrorCodes.FAILED_CONSTRAINT);
failedElements.addProblemConstraint(constraint, failedElementDetails);
if (Descriptor.LOGGING) {
LOGGER.debug("Failed constraint: " + toIvmlString(constraint));
printModelElements(config, "constraint resolved");
printProblemPoints(usedVariables);
}
} else if (evaluator.constraintFulfilled()) {
failedElements.removeProblemConstraint(constraint);
if (Descriptor.LOGGING) {
LOGGER.debug("Constraint fulfilled: " + toIvmlString(constraint));
}
}
// must be done always, constraints -> undefined may cause illegal variable assignments as side effect
for (int j = 0; j < evaluator.getMessageCount(); j++) {
Message msg = evaluator.getMessage(j);
AbstractVariable var = msg.getVariable();
if (var != null) {
// no local variable, i.e., defined for/within user-defined operation or within constraint
if (!(var.getParent() instanceof OperationDefinition) && !(var.getParent() instanceof Constraint)) {
usedVariables.clear();
usedVariables.add(msg.getDecision());
FailedElementDetails failedelementDetails = new FailedElementDetails();
failedelementDetails.setProblemPoints(new HashSet<IDecisionVariable>(usedVariables));
// due to NULL result if failed assignment
failedelementDetails.setProblemConstraintPart(constraint.getConsSyntax());
failedelementDetails.setProblemConstraint(constraint);
failedelementDetails.setErrorClassifier(ReasoningErrorCodes.FAILED_REASSIGNMENT);
failedElements.addProblemVariable(var, failedelementDetails);
if (Descriptor.LOGGING) {
LOGGER.debug("Assigment error: " + evaluator.getMessage(j).getVariable());
printProblemPoints(usedVariables);
}
}
}
}
}
// helpers, accessors
/**
* Adds <code>constraint</code> to the constraint base.
*
* @param constraint the constraint
*/
private void addToConstraintBase(Constraint constraint) {
constraintBase.addLast(constraint);
constraintBaseSet.add(constraint);
}
/**
* Method for using {@link SubstitutionVisitor} for constraint transformation. Uses the actual
* variable mapping in {@link #varMap} and may consider a mapping for <code>self</code>.
*
* @param cst Constraint to be transformed.
* @param selfEx an expression representing <i>self</i> (ignored if <b>null</b>, <code>self</code> and
* <code>selfEx</code> shall never both be specified/not <b>null</b>).
* @param self an variable declaration representing <i>self</i> (ignored if <b>null</b>).
* @param clear clear {@link #substVisitor} if <code>true</code> or leave its state for further queries requring
* the caller to explicitly clear the copy visitor after usage
* @return Transformed constraint.
*/
private ConstraintSyntaxTree substituteVariables(ConstraintSyntaxTree cst, ConstraintSyntaxTree selfEx,
AbstractVariable self, boolean clear) {
substVisitor.setMappings(varMap);
if (selfEx != null) {
substVisitor.setSelf(selfEx);
}
if (self != null) {
substVisitor.setSelf(self);
}
cst = substVisitor.acceptAndClear(cst);
inferTypeSafe(cst, null);
return cst;
}
/**
* Adds all <code>constraints</code> to the constraint base.
*
* @param constraints the constraints
*/
private void addAllToConstraintBase(Collection<Constraint> constraints) {
constraintBase.addAll(constraints);
constraintBaseSet.addAll(constraints);
}
/**
* Method for clearing all constraint lists.
*/
private void clearConstraintLists() {
defaultConstraints.clear();
deferredDefaultConstraints.clear();
topLevelConstraints.clear();
otherConstraints.clear();
}
/**
* Will be called after a failure was detected in a default constraint of an {@link AbstractVariable}.
* @param decl The conflicting declaration of an {@link AbstractVariable}.
* Call {@link AbstractVariable#getDefaultValue()} to retrieve the conflicting constraint.
*/
@SuppressWarnings("unused")
private void conflictingDefault(AbstractVariable decl) {
// currently unused
}
/**
* Method for creating a clean {@link Configuration}.
* @param project Project for {@link Configuration}
* @return Created {@link Configuration}
*/
private Configuration createCleanConfiguration(Project project) {
return new Configuration(project, false);
}
/**
* Method for checking part of a failed constraints against null.
* @return null or part of a failed constraint.
*/
private ConstraintSyntaxTree getFailedConstraintPart() {
ConstraintSyntaxTree cstPart = null;
if (evaluator.getFailedExpression() != null) {
cstPart = evaluator.getFailedExpression()[0];
}
return cstPart;
}
/**
* Getter for the map of all ConstraintVariables.
* and their {@link Constraint}s.
* @return Map of constraint variables and their constraints.
*/
Map<Constraint, IDecisionVariable> getConstraintVariableMap() {
return constraintVariableMap;
}
/**
* Method for returning the overall count of evaluated constraints in the model.
* @return number of evaluated constraints.
*/
int constraintCount() {
return constraintCounter;
}
/**
* Method for returning the overall number of variables in the model.
* @return number of variables.
*/
int variableCount() {
return variablesCounter;
}
/**
* Method for returning the number of variables involved in constraints.
* @return number of variables.
*/
int variableInConstraintCount() {
return variablesInConstraintsCounter;
}
/**
* Method for returning the overall number of reevaluations in the model.
* @return number of reevaluations.
*/
int reevaluationCount() {
return reevaluationCounter;
}
/**
* Method for retrieving {@link FailedElements} with failed {@link Constraint}s and {@link IDecisionVariable}s.
* @return {@link FailedElements}
*/
FailedElements getFailedElements() {
return failedElements;
}
/**
* Sets whether reasoning shall happen incrementally.
*
* @param incremental if reasoning shall happen incrementally
* @see #setConsiderFrozenConstraints(boolean)
*/
void setIncremental(boolean incremental) {
this.incremental = incremental;
}
/**
* Defines whether frozen constraints shall be considered. Can speed up incremental reasoning.
*
* @param considerFrozenConstraints whether frozen constraint shall be considered (default <code>true</code>)
* @see #setIncremental(boolean)
*/
void setConsiderFrozenConstraints(boolean considerFrozenConstraints) {
this.considerFrozenConstraints = considerFrozenConstraints;
}
/**
* Factory method for creating the evaluation visitor.
*
* @return the evaluation visitor
*/
protected EvaluationVisitor createEvaluationVisitor() {
return new EvalVisitor();
}
/**
* Returns whether reasoning stopped due to a timeout.
*
* @return <code>true</code> for timeout, <code>false</code> else
*/
boolean hasTimeout() {
return hasTimeout;
}
/**
* Returns whether reasoning was stopped due to a user-request.
*
* @return <code>true</code> for stopped, <code>false</code> else
*/
boolean wasStopped() {
return wasStopped;
}
/**
* Returns whether the reasoner is (still) operating.
*
* @return <code>true</code> for operating, <code>false</code> else
*/
boolean isRunning() {
return isRunning;
}
/**
* Stops/terminates reasoning. If possible, a reasoner shall stop the reasoning
* operations as quick as possible. A reasoner must not implement this operation.
*
* @return <code>true</code> if the reasoner tries to stop, <code>false</code> else
* (operation not implemented)
*/
boolean stop() {
wasStopped = true;
return true;
}
/**
* Marks this instance for re-use. Must be called before the first call to {@link #resolve()}.
*/
void markForReuse() {
constraintBaseCopy = new LinkedList<Constraint>();
}
/**
* Clears this instance for reuse to free most of the resources.
*
* @see #markForReuse()
* @see #reInit()
*/
void clear() {
clearConstraintLists();
failedElements.clear();
scopeAssignments.clearScopeAssignments();
// keep the constraintMap
// keep the constraintVariableMap
constraintBase.clear();
constraintBaseSet.clear();
// keep constraintCounter - is set during translation
// keep variablesInConstraintsCounter - is set during translation
reevaluationCounter = 0;
// keep variablesCounter - is set during translation
hasTimeout = false;
isRunning = false;
wasStopped = false;
usedVariables.clear();
substVisitor.clear();
varMap.clear();
containerFinder.clear();
simpleAssignmentFinder.clear();
}
/**
* Re-initializes this resolver instance to allocated resources only if really needed.
*
* @see #markForReuse()
* @see #reInit()
*/
void reInit() {
if (null != constraintBaseCopy) {
constraintBase.addAll(constraintBaseCopy);
constraintBaseSet.addAll(constraintBaseCopy);
}
}
}
| Plugins/Reasoner/EASy-Original-Reasoner/de.uni_hildesheim.sse.reasoning.reasoner/src/net/ssehub/easy/reasoning/sseReasoner/Resolver.java | package net.ssehub.easy.reasoning.sseReasoner;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import net.ssehub.easy.basics.logger.EASyLoggerFactory;
import net.ssehub.easy.basics.logger.EASyLoggerFactory.EASyLogger;
import net.ssehub.easy.basics.modelManagement.Utils;
import net.ssehub.easy.reasoning.core.reasoner.ReasonerConfiguration;
import net.ssehub.easy.reasoning.core.reasoner.ReasonerConfiguration.IAdditionalInformationLogger;
import net.ssehub.easy.reasoning.core.reasoner.ReasoningErrorCodes;
import net.ssehub.easy.reasoning.sseReasoner.functions.FailedElementDetails;
import net.ssehub.easy.reasoning.sseReasoner.functions.FailedElements;
import net.ssehub.easy.reasoning.sseReasoner.functions.ScopeAssignments;
import net.ssehub.easy.reasoning.sseReasoner.model.ContainerConstraintsFinder;
import net.ssehub.easy.reasoning.sseReasoner.model.SubstitutionVisitor;
import net.ssehub.easy.reasoning.sseReasoner.model.DefaultConstraint;
import net.ssehub.easy.reasoning.sseReasoner.model.VariablesInNotSimpleAssignmentConstraintsFinder;
import net.ssehub.easy.reasoning.sseReasoner.model.VariablesMap;
import net.ssehub.easy.varModel.confModel.AssignmentState;
import net.ssehub.easy.varModel.confModel.CompoundVariable;
import net.ssehub.easy.varModel.confModel.Configuration;
import net.ssehub.easy.varModel.confModel.IAssignmentState;
import net.ssehub.easy.varModel.confModel.IConfigurationElement;
import net.ssehub.easy.varModel.confModel.IDecisionVariable;
import net.ssehub.easy.varModel.cst.AttributeVariable;
import net.ssehub.easy.varModel.cst.CSTSemanticException;
import net.ssehub.easy.varModel.cst.CSTUtils;
import net.ssehub.easy.varModel.cst.CompoundAccess;
import net.ssehub.easy.varModel.cst.CompoundInitializer;
import net.ssehub.easy.varModel.cst.ConstantValue;
import net.ssehub.easy.varModel.cst.ConstraintSyntaxTree;
import net.ssehub.easy.varModel.cst.ContainerInitializer;
import net.ssehub.easy.varModel.cst.OCLFeatureCall;
import net.ssehub.easy.varModel.cst.Variable;
import net.ssehub.easy.varModel.cstEvaluation.EvaluationVisitor;
import net.ssehub.easy.varModel.cstEvaluation.EvaluationVisitor.Message;
import net.ssehub.easy.varModel.cstEvaluation.IResolutionListener;
import net.ssehub.easy.varModel.cstEvaluation.IValueChangeListener;
import net.ssehub.easy.varModel.model.AbstractVariable;
import net.ssehub.easy.varModel.model.Attribute;
import net.ssehub.easy.varModel.model.AttributeAssignment;
import net.ssehub.easy.varModel.model.AttributeAssignment.Assignment;
import net.ssehub.easy.varModel.model.Constraint;
import net.ssehub.easy.varModel.model.DecisionVariableDeclaration;
import net.ssehub.easy.varModel.model.IModelElement;
import net.ssehub.easy.varModel.model.ModelVisitorAdapter;
import net.ssehub.easy.varModel.model.OperationDefinition;
import net.ssehub.easy.varModel.model.PartialEvaluationBlock;
import net.ssehub.easy.varModel.model.Project;
import net.ssehub.easy.varModel.model.datatypes.Compound;
import net.ssehub.easy.varModel.model.datatypes.ConstraintType;
import net.ssehub.easy.varModel.model.datatypes.Container;
import net.ssehub.easy.varModel.model.datatypes.DerivedDatatype;
import net.ssehub.easy.varModel.model.datatypes.IDatatype;
import net.ssehub.easy.varModel.model.datatypes.MetaType;
import net.ssehub.easy.varModel.model.datatypes.OclKeyWords;
import net.ssehub.easy.varModel.model.datatypes.TypeQueries;
import net.ssehub.easy.varModel.model.filter.FilterType;
import net.ssehub.easy.varModel.model.filter.VariablesInConstraintFinder;
import net.ssehub.easy.varModel.model.values.ConstraintValue;
import net.ssehub.easy.varModel.model.values.ContainerValue;
import net.ssehub.easy.varModel.model.values.Value;
import net.ssehub.easy.varModel.model.values.ValueDoesNotMatchTypeException;
import net.ssehub.easy.varModel.model.values.ValueFactory;
import static net.ssehub.easy.reasoning.sseReasoner.ReasoningUtils.*;
/**
* Constraint identifier, resolver and executor. Assumption that constraints are not evaluated in parallel (see some
* comments). This resolver can be re-used. Therefore, call {@link #markForReuse()} before the first call to
* {@link #resolve()} and after reasoning completed, call {@link #clear()}. When performing a further reasoning on this
* instance, call {@link #reInit()}.
*
* @author Sizonenko
* @author El-Sharkawy
* @author Holger Eichelberger
*/
public class Resolver {
private static final EASyLogger LOGGER
= EASyLoggerFactory.INSTANCE.getLogger(Resolver.class, Descriptor.BUNDLE_NAME);
@SuppressWarnings("unused")
private IAdditionalInformationLogger infoLogger;
private ReasonerConfiguration reasonerConfig;
private Configuration config;
private boolean incremental = false;
private boolean considerFrozenConstraints = true;
private EvalVisitor evaluator = new EvalVisitor();
private FailedElements failedElements = new FailedElements();
private ScopeAssignments scopeAssignments = new ScopeAssignments();
private VariablesMap constraintMap = new VariablesMap();
private Map<Constraint, IDecisionVariable> constraintVariableMap = new HashMap<Constraint, IDecisionVariable>();
private Deque<Constraint> constraintBase = new LinkedList<Constraint>();
private Deque<Constraint> constraintBaseCopy = null;
private Set<Constraint> constraintBaseSet = new HashSet<Constraint>();
private List<Constraint> defaultConstraints = new LinkedList<Constraint>();
private List<Constraint> deferredDefaultConstraints = new LinkedList<Constraint>();
private List<Constraint> topLevelConstraints = new LinkedList<Constraint>();
private List<Constraint> otherConstraints = new LinkedList<Constraint>();
// Stats
private int constraintCounter = 0;
private int variablesInConstraintsCounter = 0;
private int reevaluationCounter = 0;
private int variablesCounter = 0;
private boolean hasTimeout = false;
private boolean isRunning = false;
private boolean wasStopped = false;
// global temporary variables avoiding parameter passing (performance)
private Project project;
private transient Set<IDecisionVariable> usedVariables = new HashSet<IDecisionVariable>(100);
private transient SubstitutionVisitor copyVisitor = new SubstitutionVisitor();
private transient Map<AbstractVariable, CompoundAccess> varMap = new HashMap<AbstractVariable, CompoundAccess>(100);
private transient ContainerConstraintsFinder containerFinder = new ContainerConstraintsFinder();
private transient VariablesInNotSimpleAssignmentConstraintsFinder simpleAssignmentFinder
= new VariablesInNotSimpleAssignmentConstraintsFinder(constraintMap);
private transient ConstraintTranslationVisitor projectVisitor = new ConstraintTranslationVisitor();
private transient VariablesInConstraintFinder variablesFinder = new VariablesInConstraintFinder();
private transient long endTimestamp;
// >>> from here the names follows the reasoner.tex documentation
private IValueChangeListener listener = new IValueChangeListener() {
@Override
public void notifyUnresolved(IDecisionVariable variable) {
}
@Override
public void notifyChanged(IDecisionVariable variable, Value oldValue) {
if (!variable.isLocal()) {
if (Descriptor.LOGGING) {
LOGGER.debug("Value changed: " + variable.getDeclaration().getName() + " " + variable.getValue()
+ " Parent: " + (null == variable.getParent() ? null : variable.getParent()));
}
scopeAssignments.addAssignedVariable(variable);
// TODO if value type changes (currently not part of the notification), change also constraints
rescheduleConstraintsForChilds(variable);
// All constraints for the parent (as this was also changed)
rescheduleConstraintsForParent(variable);
}
}
/**
* Tries rescheduling the given constraints. Does not add a constraint to the constraint base if already
* scheduled.
*
* @param constraints the constraints to reschedule (may be <b>null</b>, ignored then)
*/
private void reschedule(Set<Constraint> constraints) {
if (null != constraints) {
for (Constraint varConstraint : constraints) {
if (!constraintBaseSet.contains(varConstraint)) {
addToConstraintBase(varConstraint);
}
}
}
}
/**
* Determines the constraints needed for the parents of <code>variable</code>.
*
* @param variable the variable to analyze
* @param constraintsToReevaluate the constraint set to be modified as a side effect
*/
private void rescheduleConstraintsForParent(IDecisionVariable variable) {
IConfigurationElement parent = variable.getParent();
if (parent instanceof IDecisionVariable) {
IDecisionVariable pVar = (IDecisionVariable) parent;
AbstractVariable declaration = pVar.getDeclaration();
reschedule(constraintMap.getRelevantConstraints(declaration));
rescheduleConstraintsForParent(pVar);
}
}
/**
* Determines the constraints needed for <code>variable</code> and its (transitive) child slots.
*
* @param variable the variable to analyze
* @param constraintsToReevaluate the constraint set to be modified as a side effect
*/
private void rescheduleConstraintsForChilds(IDecisionVariable variable) {
AbstractVariable declaration = variable.getDeclaration();
reschedule(constraintMap.getRelevantConstraints(declaration));
// All constraints for childs (as they may also changed)
for (int j = 0, nChilds = variable.getNestedElementsCount(); j < nChilds; j++) {
rescheduleConstraintsForChilds(variable.getNestedElement(j));
}
}
};
/**
* Listener for the {@link #evaluator} to record changed variables.
*/
private IResolutionListener resolutionListener = new IResolutionListener() {
@Override
public void notifyResolved(IDecisionVariable compound, String slotName, IDecisionVariable resolved) {
if (!(resolved.isLocal())) {
usedVariables.add(resolved);
}
}
@Override
public void notifyResolved(AbstractVariable declaration, IDecisionVariable resolved) {
if (!(resolved.isLocal())) {
usedVariables.add(resolved);
}
}
};
// <<< documented until here
/**
* Main constructor that activates Resolver constructor.
* @param project Project for evaluation.
* @param config Configuration to reason on.
* @param reasonerConfig the reasoner configuration to be used for reasoning (e.g. taken from the UI,
* may be <b>null</b>)
*/
public Resolver(Project project, Configuration config, ReasonerConfiguration reasonerConfig) {
this.reasonerConfig = reasonerConfig;
this.infoLogger = reasonerConfig.getLogger();
this.config = config;
}
/**
* Main constructor that activates Resolver constructor with clean {@link Configuration}.
* @param project Project for evaluation.
* @param reasonerConfig the reasoner configuration to be used for reasoning (e.g. taken from the UI,
* may be <b>null</b>)
*/
public Resolver(Project project, ReasonerConfiguration reasonerConfig) {
new Resolver(project, createCleanConfiguration(project), reasonerConfig);
}
/**
* Main constructor that activates Resolver constructor.
* @param config Configuration to reason on.
* @param reasonerConfig the reasoner configuration to be used for reasoning (e.g. taken from the UI,
* may be <b>null</b>)
*/
public Resolver(Configuration config, ReasonerConfiguration reasonerConfig) {
new Resolver(config.getProject(), config, reasonerConfig);
}
// >>> from here the names follow the reasoner.tex documentation
/**
* Resolves the (initial) values of the configuration.
*
* @see Utils#discoverImports(net.ssehub.easy.basics.modelManagement.IModel)
* @see #translateConstraints()
* @see #evaluateConstraints()
* @see Configuration#freeze(net.ssehub.easy.varModel.confModel.IFreezeSelector)
*/
public void resolve() {
isRunning = true;
// Stack of importedProject (start with inner most imported project)
evaluator.init(config, null, false, listener); // also for defaults as they may refer to each other
evaluator.setResolutionListener(resolutionListener);
evaluator.setScopeAssignments(scopeAssignments);
List<Project> projects = Utils.discoverImports(config.getProject());
endTimestamp = reasonerConfig.getTimeout() <= 0
? -1 : System.currentTimeMillis() + reasonerConfig.getTimeout();
for (int p = 0; !hasTimeout && !wasStopped && p < projects.size(); p++) {
project = projects.get(p);
if (Descriptor.LOGGING) {
LOGGER.debug("Project:" + project.getName());
}
translateConstraints();
evaluateConstraints();
// Freezes values after each scope
config.freezeValues(project, FilterType.NO_IMPORTS);
// TODO do incremental freezing in here -> required by interfaces with propagation constraints
if (Descriptor.LOGGING) {
printFailedElements(failedElements);
}
}
evaluator.clear();
isRunning = false;
}
/**
* Evaluates and reschedules failed constraints.
*
* @see #resolve()
*/
private void evaluateConstraints() {
if (Descriptor.LOGGING) {
printConstraints(constraintBase);
}
scopeAssignments.clearScopeAssignments();
evaluator.setDispatchScope(project);
while (!constraintBase.isEmpty() && !wasStopped) { // reasoner.tex -> hasTimeout see end of loop
usedVariables.clear();
Constraint constraint = constraintBase.pop();
constraintBaseSet.remove(constraint);
ConstraintSyntaxTree cst = constraint.getConsSyntax();
evaluator.setAssignmentState(constraint.isDefaultConstraint()
? AssignmentState.DEFAULT : AssignmentState.DERIVED);
reevaluationCounter++;
if (cst != null) {
if (Descriptor.LOGGING) {
LOGGER.debug("Resolving: " + reevaluationCounter + ": " + toIvmlString(cst)
+ " : " + constraint.getTopLevelParent());
}
evaluator.visit(cst);
analyzeEvaluationResult(constraint);
if (Descriptor.LOGGING) {
LOGGER.debug("Result: " + evaluator.getResult());
LOGGER.debug("------");
}
evaluator.clearIntermediary();
}
if (endTimestamp > 0 && System.currentTimeMillis() > endTimestamp) {
hasTimeout = true;
break;
}
}
}
/**
* Visits the contents of a project for translation. Do not store stateful information in this class.
*
* @author Holger Eichelberger
*/
private class ConstraintTranslationVisitor extends ModelVisitorAdapter {
// don't follow project imports here, just structural top-level traversal of the actual project!
private List<PartialEvaluationBlock> evals = null;
@Override // iterate over all elements declared in project, implicitly skipping not implemented elements
public void visitProject(Project project) {
for (int e = 0; e < project.getElementCount(); e++) {
project.getElement(e).accept(this);
}
if (null != evals) {
// prioritize top-level project contents over eval blocks
for (PartialEvaluationBlock block : evals) {
for (int i = 0; i < block.getNestedCount(); i++) {
block.getNested(i).accept(this);
}
for (int i = 0; i < block.getEvaluableCount(); i++) {
block.getEvaluable(i).accept(this);
}
}
}
}
@Override // translate all top-level/enum/attribute assignment declarations
public void visitDecisionVariableDeclaration(DecisionVariableDeclaration decl) {
translateDeclaration(decl, config.getDecision(decl), null);
}
@Override // collect all top-level/enum/attribute assignment constraints
public void visitConstraint(Constraint constraint) {
addConstraint(topLevelConstraints, constraint, true); // topLevelConstraints
}
@Override // iterate over nested blocks/contained constraints
public void visitPartialEvaluationBlock(PartialEvaluationBlock block) {
if (null == evals) {
evals = new LinkedList<PartialEvaluationBlock>();
}
evals.add(block);
}
@Override // iterate over nested blocks/contained, translate the individual blocks if not incremental
public void visitAttributeAssignment(AttributeAssignment assignment) {
for (int v = 0; v < assignment.getElementCount(); v++) {
assignment.getElement(v).accept(this);
}
for (int a = 0; a < assignment.getAssignmentCount(); a++) {
assignment.getAssignment(a).accept(this);
}
if (!incremental) {
translateAnnotationAssignments(assignment, null, null);
}
}
}
/**
* Extracts, translates and collects the internal constraints of <code>type</code> and stores them
* in {@link #derivedTypeConstraints}.
*
* @param decl VariableDeclaration of <code>DerivedDatatype</code>
* @param dType the type to translate
*/
private void translateDerivedDatatypeConstraints(AbstractVariable decl, DerivedDatatype dType) {
ConstraintSyntaxTree[] cst = createDerivedDatatypeExpressions(decl, dType);
if (null != cst) {
IModelElement topLevelParent = decl.getTopLevelParent();
for (int c = 0; c < cst.length; c++) {
// Should be in same project as the declaration belongs to
try { // derivedTypeConstraints
ConstraintSyntaxTree tmp = substituteVariables(cst[c], null, null, true);
addConstraint(topLevelConstraints, new Constraint(tmp, topLevelParent), true);
} catch (CSTSemanticException e) {
LOGGER.exception(e);
}
}
}
IDatatype basis = dType.getBasisType();
if (basis instanceof DerivedDatatype) {
translateDerivedDatatypeConstraints(decl, (DerivedDatatype) basis);
}
}
/**
* Translates constraint expressions specified for derived datatypes.
*
* @param declaration VariableDeclaration of <code>DerivedDatatype</code>
* @param dType type of <code>DerivedDatatype</code>
* @return the created constraints
*/
private ConstraintSyntaxTree[] createDerivedDatatypeExpressions(AbstractVariable declaration,
DerivedDatatype dType) {
ConstraintSyntaxTree[] csts = null;
int count = dType.getConstraintCount();
DecisionVariableDeclaration dVar = dType.getTypeDeclaration();
if (count > 0 && dVar != declaration) {
csts = new ConstraintSyntaxTree[count];
Variable replacement = new Variable(declaration);
//Copy and replace each instance of the internal declaration with the given instance
for (int i = 0; i < count; i++) {
copyVisitor.addVariableMapping(dVar, replacement);
csts[i] = copyVisitor.acceptAndClear(dType.getConstraint(i).getConsSyntax());
}
}
return csts;
}
/**
* Translates annotation default value expressions.
*
* @param decl {@link AbstractVariable} with annotations.
* @param variable {@link IDecisionVariable} with annotations.
* @param compound {@link CompoundAccess} null if variable is not nested.
*/
private void translateAnnotationDefaults(AbstractVariable decl, IDecisionVariable variable,
CompoundAccess compound) {
for (int i = 0; i < variable.getAttributesCount(); i++) {
Attribute attribute = (Attribute) variable.getAttribute(i).getDeclaration();
ConstraintSyntaxTree defaultValue = attribute.getDefaultValue();
if (null != defaultValue) {
try {
ConstraintSyntaxTree op;
if (compound == null) {
op = new AttributeVariable(new Variable(decl), attribute);
} else {
op = new AttributeVariable(compound, attribute);
}
defaultValue = new OCLFeatureCall(op, OclKeyWords.ASSIGNMENT, defaultValue);
defaultValue.inferDatatype(); // defaultAnnotationConstraints
addConstraint(otherConstraints, new DefaultConstraint(defaultValue, project), false);
} catch (CSTSemanticException e) {
e.printStackTrace();
}
}
}
}
/**
* Translates the (transitive) defaults and type constraints for a declaration.
*
* @param decl The {@link AbstractVariable} for which the default value should be resolved.
* @param var the instance of <tt>decl</tt>.
* @param cAcc if variable is a nested compound.
*/
protected void translateDeclaration(AbstractVariable decl, IDecisionVariable var, CompoundAccess cAcc) {
variablesCounter++;
IDatatype type = decl.getType();
ConstraintSyntaxTree defaultValue = decl.getDefaultValue();
AbstractVariable self = null;
ConstraintSyntaxTree selfEx = null;
if (type instanceof DerivedDatatype) {
translateDerivedDatatypeConstraints(decl, (DerivedDatatype) type);
}
if (!incremental) {
translateAnnotationDefaults(decl, var, cAcc);
}
if (null != defaultValue) { // considering the actual type rather than base, after derived (!)
type = inferTypeSafe(defaultValue, type);
}
if (TypeQueries.isCompound(type)) { // this is a compound value -> default constraints, do not defer
self = decl;
translateCompoundDeclaration(decl, var, cAcc, type);
} else if (TypeQueries.isContainer(type)) { // this is a container value -> default constraints, do not defer
translateContainerDeclaration(decl, var, type);
} else if (null != defaultValue && !incremental) {
if (null != cAcc) { // defer self/override init constraints to prevent accidental init override
selfEx = cAcc.getCompoundExpression();
}
} else if (incremental) { // remaining defaults
defaultValue = null;
}
if (null != defaultValue) {
try {
if (TypeQueries.isConstraint(decl.getType())) { // handle and register constraint variables
variablesCounter--;
// use closest parent instead of project -> runtime analysis
createConstraintVariableConstraint(defaultValue, selfEx, self, var.getDeclaration(), var);
} else { // Create default constraint
defaultValue = new OCLFeatureCall(null != selfEx ? cAcc : new Variable(decl),
OclKeyWords.ASSIGNMENT, defaultValue);
defaultValue = substituteVariables(defaultValue, selfEx, self, false);
List<Constraint> targetCons = defaultConstraints;
if (copyVisitor.containsSelf() || isOverriddenSlot(decl)) {
targetCons = deferredDefaultConstraints;
}
addConstraint(targetCons, new DefaultConstraint(defaultValue, project), true);
}
copyVisitor.clear(); // clear false above
} catch (CSTSemanticException e) {
LOGGER.exception(e); // should not occur, ok to log
}
}
}
/**
* Translates the (transitive) defaults and type constraints for a container declaration.
*
* @param decl The {@link AbstractVariable} for which the default value should be resolved.
* @param var the instance of <tt>decl</tt>.
* @param type the (specific) datatype ({@link Container})
*/
private void translateContainerDeclaration(AbstractVariable decl, IDecisionVariable var, IDatatype type) {
if (null != decl.getDefaultValue() && !incremental) {
Set<Compound> used = getUsedTypes(decl.getDefaultValue(), Compound.class);
if (null != used && !used.isEmpty()) {
Set<Compound> done = new HashSet<Compound>();
for (Compound uType : used) {
translateDefaultsCompoundContainer(decl, uType, done);
done.clear();
}
}
}
translateContainerCompoundConstraints(decl, var, null, otherConstraints);
IDatatype containedType = ((Container) type).getContainedType();
if (containedType instanceof DerivedDatatype) {
translateContainerDerivedDatatypeConstraints((DerivedDatatype) containedType, decl, null);
}
}
/**
* Translates constraints representing compound defaults in containers of compounds.
*
* @param decl the container variable
* @param cmpType the compound type used in the actual <code>decl</code> value to focus the constraints created
* @param done the already processed types (to be modified as a side effect)
*/
private void translateDefaultsCompoundContainer(AbstractVariable decl, Compound cmpType, Set<Compound> done) {
if (!done.contains(cmpType)) {
done.add(cmpType);
for (int d = 0; d < cmpType.getDeclarationCount(); d++) {
DecisionVariableDeclaration uDecl = cmpType.getDeclaration(d);
ConstraintSyntaxTree defaultValue = uDecl.getDefaultValue();
if (null != defaultValue) {
DecisionVariableDeclaration localDecl = new DecisionVariableDeclaration("cmp", cmpType, null);
try {
Variable localDeclVar = new Variable(localDecl);
defaultValue = substituteVariables(defaultValue, localDeclVar, null, true); // replace self
defaultValue = new OCLFeatureCall(new CompoundAccess(localDeclVar, uDecl.getName()),
OclKeyWords.ASSIGNMENT, defaultValue);
ConstraintSyntaxTree containerOp = new Variable(decl);
if (!TypeQueries.sameTypes(decl.getType(), cmpType)) {
containerOp = new OCLFeatureCall(containerOp, OclKeyWords.TYPE_SELECT,
new ConstantValue(ValueFactory.createValue(MetaType.TYPE, cmpType)));
}
if (isNestedContainer(decl.getType())) {
containerOp = new OCLFeatureCall(containerOp, OclKeyWords.FLATTEN);
}
defaultValue = createContainerCall(containerOp, Container.FORALL, defaultValue, localDecl);
defaultValue.inferDatatype();
addConstraint(deferredDefaultConstraints, new DefaultConstraint(defaultValue, project), true);
} catch (CSTSemanticException e) {
LOGGER.exception(e); // should not occur, ok to log
} catch (ValueDoesNotMatchTypeException e) {
LOGGER.exception(e); // should not occur, ok to log
}
}
}
// attributes??
for (int r = 0; r < cmpType.getRefinesCount(); r++) {
translateDefaultsCompoundContainer(decl, cmpType.getRefines(r), done);
}
}
}
/**
* Method for translating the internal constraint from containers with derived contained types.
*
* @param derivedType {@link DerivedDatatype} of the container.
* @param decl container variable.
* @param access {@link CompoundAccess}, might be <b>null</b>.
*/
private void translateContainerDerivedDatatypeConstraints(DerivedDatatype derivedType,
AbstractVariable decl, CompoundAccess access) {
// as long as evaluation is not parallelized, using the same localDecl shall not be a problem
DecisionVariableDeclaration localDecl = new DecisionVariableDeclaration("derivedType", derivedType, null);
ConstraintSyntaxTree[] cst = createDerivedDatatypeExpressions(localDecl, derivedType);
if (null != cst) {
for (int i = 0, n = cst.length; i < n; i++) {
ConstraintSyntaxTree itExpression = cst[i];
ConstraintSyntaxTree typeCst = null;
if (access == null) {
typeCst = createContainerCall(new Variable(decl), Container.FORALL, itExpression, localDecl);
} else {
typeCst = createContainerCall(access, Container.FORALL, itExpression, localDecl);
}
try {
typeCst.inferDatatype();
typeCst = substituteVariables(typeCst, null, null, true); // derivedTypeConstraints
addConstraint(topLevelConstraints, new Constraint(typeCst, project), true);
} catch (CSTSemanticException e) {
LOGGER.exception(e);
}
}
}
IDatatype basis = derivedType.getBasisType();
if (basis instanceof DerivedDatatype) {
translateContainerDerivedDatatypeConstraints((DerivedDatatype) basis, decl, access);
}
}
/**
* Method for retrieving constraints from compounds initialized in containers. <code>variable</code>
* must be a container and <code>decl</code> of type container.
*
* @param decl AbstractVariable.
* @param variable the instance of <tt>decl</tt>.
* @param topcmpAccess {@link CompoundAccess} if container is a nested element.
* @param results the resulting constraints
*/
private void translateContainerCompoundConstraints(AbstractVariable decl, IDecisionVariable variable,
CompoundAccess topcmpAccess, List<Constraint> results) {
IDatatype containedType = ((Container) decl.getType()).getContainedType();
for (IDatatype tmp : identifyContainedTypes(variable, containedType)) {
if (TypeQueries.isCompound(tmp)) {
translateContainerCompoundConstraints((Compound) tmp, containedType, decl, topcmpAccess, results);
}
}
}
/**
* Method for transforming a compound constraint into container forAll constraint.
* @param cmpType Specific compound type (with constraints).
* @param declaredContainedType the declared contained type of the container.
* @param decl {@link AbstractVariable}.
* @param topcmpAccess {@link CompoundAccess} if container is a nested element.
* @param result List of transformed constraints, to be modified as a side effect.
*/
private void translateContainerCompoundConstraints(Compound cmpType, IDatatype declaredContainedType,
AbstractVariable decl, CompoundAccess topcmpAccess, List<Constraint> result) {
DecisionVariableDeclaration localDecl = new DecisionVariableDeclaration("cmp", cmpType, null);
// fill varMap
for (int i = 0, n = cmpType.getInheritedElementCount(); i < n; i++) {
AbstractVariable nestedDecl = cmpType.getInheritedElement(i);
CompoundAccess cmpAccess = null;
cmpAccess = new CompoundAccess(new Variable(localDecl), nestedDecl.getName());
varMap.put(nestedDecl, cmpAccess);
}
List<Constraint> thisCompoundConstraints = new ArrayList<Constraint>();
allCompoundConstraints(cmpType, thisCompoundConstraints, true);
ConstraintSyntaxTree typeExpression = null;
if (!TypeQueries.sameTypes(cmpType, declaredContainedType)) {
typeExpression = createTypeValueConstantSafe(cmpType);
}
for (int i = 0; i < thisCompoundConstraints.size(); i++) {
ConstraintSyntaxTree itExpression = thisCompoundConstraints.get(i).getConsSyntax();
itExpression = substituteVariables(itExpression, null, localDecl, true);
if (Descriptor.LOGGING) {
LOGGER.debug("New loop constraint " + toIvmlString(itExpression));
}
try {
ConstraintSyntaxTree containerOp = topcmpAccess == null ? new Variable(decl) : topcmpAccess;
containerOp.inferDatatype();
if (null != typeExpression) {
containerOp = new OCLFeatureCall(containerOp, Container.SELECT_BY_KIND.getName(), typeExpression);
}
if (containerOp != null) {
containerOp.inferDatatype();
containerOp = createContainerCall(containerOp, Container.FORALL, itExpression, localDecl);
}
if (containerOp != null) {
containerOp.inferDatatype();
addConstraint(result, new Constraint(containerOp, project), true);
}
} catch (CSTSemanticException e) {
LOGGER.exception(e);
}
}
}
/**
* Method for translating compound default value declarations. Requires
* {@link #buildVariableMapping(AbstractVariable, IDecisionVariable, CompoundAccess, IDatatype)} before.
*
* @param decl The {@link AbstractVariable} for which the default value should be resolved.
* @param variable the instance of <tt>decl</tt>.
* @param compound if variable is a nested compound, the access expression to
* <code>decl</code>/<code>variable</code>
* @param type specific {@link Compound} type.
*/
private void translateCompoundDeclaration(AbstractVariable decl, IDecisionVariable variable,
CompoundAccess compound, IDatatype type) {
Compound cmpType = (Compound) type;
CompoundVariable cmpVar = (CompoundVariable) variable;
// resolve compound access first for all slots
for (int i = 0, n = cmpVar.getNestedElementsCount(); i < n; i++) {
IDecisionVariable nestedVar = cmpVar.getNestedElement(i);
AbstractVariable nestedDecl = nestedVar.getDeclaration();
CompoundAccess cmpAccess;
if (compound == null) {
cmpAccess = new CompoundAccess(new Variable(decl), nestedDecl.getName());
} else {
cmpAccess = new CompoundAccess(createAsTypeCast(compound, type, cmpVar.getValue().getType()),
nestedDecl.getName());
}
inferTypeSafe(cmpAccess, null);
// fill varMap
varMap.put(nestedDecl, cmpAccess);
}
for (int i = 0, n = cmpVar.getNestedElementsCount(); i < n; i++) {
IDecisionVariable nestedVar = cmpVar.getNestedElement(i);
AbstractVariable nestedDecl = nestedVar.getDeclaration();
translateDeclaration(nestedDecl, cmpVar.getNestedVariable(nestedDecl.getName()),
varMap.get(nestedDecl));
}
// create constraints on mutually interacting constraints now
for (int i = 0, n = cmpVar.getNestedElementsCount(); i < n; i++) {
IDecisionVariable nestedVar = cmpVar.getNestedElement(i);
AbstractVariable nestedDecl = nestedVar.getDeclaration();
IDatatype nestedType = nestedDecl.getType();
if (Container.isContainer(nestedType, ConstraintType.TYPE)
&& nestedVar.getValue() instanceof ContainerValue) {
createContainerConstraintValueConstraints((ContainerValue) nestedVar.getValue(), decl, nestedDecl,
nestedVar);
}
if (TypeQueries.isContainer(nestedType)) {
translateContainerCompoundConstraints(nestedDecl, variable, varMap.get(nestedDecl),
otherConstraints);
}
}
// Nested attribute assignments handling
if (!incremental) {
for (int a = 0; a < cmpType.getAssignmentCount(); a++) {
translateAnnotationAssignments(cmpType.getAssignment(a), null, compound);
}
}
List<Constraint> thisCompoundConstraints = new ArrayList<Constraint>();
allCompoundConstraints(cmpType, thisCompoundConstraints, false);
for (int i = 0; i < thisCompoundConstraints.size(); i++) {
ConstraintSyntaxTree oneConstraint = thisCompoundConstraints.get(i).getConsSyntax();
// changed null to decl
oneConstraint = substituteVariables(oneConstraint, null, decl, true);
try { // compoundConstraints
Constraint constraint = new Constraint(oneConstraint, decl);
addConstraint(otherConstraints, constraint, true);
} catch (CSTSemanticException e) {
LOGGER.exception(e);
}
}
processCompoundEvals(cmpType);
}
/**
* Method for extracting constraints from compounds eval blocks (also refined compounds).
* @param cmpType Compound to be analyzed
*/
private void processCompoundEvals(Compound cmpType) {
for (int r = 0; r < cmpType.getRefinesCount(); r++) {
processCompoundEvals(cmpType.getRefines(r));
}
for (int i = 0; i < cmpType.getModelElementCount(); i++) {
if (cmpType.getModelElement(i) instanceof PartialEvaluationBlock) {
PartialEvaluationBlock evalBlock = (PartialEvaluationBlock) cmpType.getModelElement(i);
processEvalConstraints(evalBlock);
}
}
}
/**
* Method for handling eval blocks - searching for nested eval blocks and extracting constraints.
* @param evalBlock Eval block to be processed.
*/
private void processEvalConstraints(PartialEvaluationBlock evalBlock) {
for (int i = 0; i < evalBlock.getNestedCount(); i++) {
processEvalConstraints(evalBlock.getNested(i));
}
for (int i = 0; i < evalBlock.getEvaluableCount(); i++) {
if (evalBlock.getEvaluable(i) instanceof Constraint) {
Constraint evalConstraint = (Constraint) evalBlock.getEvaluable(i);
ConstraintSyntaxTree evalCst = evalConstraint.getConsSyntax();
ConstraintSyntaxTree cst = substituteVariables(evalCst, null, null, true);
try {
addConstraint(otherConstraints, new Constraint(cst, project), true);
} catch (CSTSemanticException e) {
LOGGER.exception(e);
}
}
}
}
/**
* Creates a constraint from a (nested) constraint variable adding the result to
* {@link #constraintVariablesConstraints}.
*
* @param cst the constraint
* @param selfEx the expression representing <i>self</i> in <code>cst</code>, both, <code>self</code> and
* <code>selfEx</code> must not be different from <b>null</b> at the same time (may be <b>null</b> for none)
* @param self the declaration of the variable representing <i>self</i> in <code>cst</code> (may be <b>null</b>
* for none)
* @param parent the parent for new constraints
* @param variable the actually (nested) variable, used to fill {@link #constraintVariableMap}
* @return the created constraint
*/
private Constraint createConstraintVariableConstraint(ConstraintSyntaxTree cst, ConstraintSyntaxTree selfEx,
AbstractVariable self, IModelElement parent, IDecisionVariable variable) {
Constraint constraint = null;
if (cst != null) {
cst = substituteVariables(cst, selfEx, self, true);
try {
constraint = new Constraint(cst, parent);
addConstraint(otherConstraints, constraint, true); // constraintVariablesConstraints
// TODO reverse mapping for changing constraint types through value upon value change
constraintVariableMap.put(constraint, variable);
if (Descriptor.LOGGING) {
LOGGER.debug((null != self ? self.getName() + "." : "") + variable.getDeclaration().getName()
+ " compound constraint variable " + toIvmlString(cst));
}
} catch (CSTSemanticException e) {
LOGGER.exception(e);
}
}
return constraint;
}
/**
* Checks a container value for nested constraint values, i.e., values of nested constraint variables.
*
* @param val the container value
* @param decl the variable declaration representing <i>self</i> in the container/constraint value
* @param parent the parent for new constraints
* @param nestedVariable the variable holding the constraint value
*/
private void createContainerConstraintValueConstraints(ContainerValue val, AbstractVariable decl,
IModelElement parent, IDecisionVariable nestedVariable) {
for (int n = 0; n < val.getElementSize(); n++) {
Value cVal = val.getElement(n);
if (cVal instanceof ConstraintValue) {
ConstraintValue constraint = (ConstraintValue) cVal;
createConstraintVariableConstraint(constraint.getValue(), null, decl, parent, nestedVariable);
}
}
}
/**
* Translates attribute assignments. It is important to recall that in case of nested (orthogonal) attribute
* assignments, the outer one(s) must also be applied to the inner ones.
*
* @param assignment Attribute assignments on top-level.
* @param effectiveAssignments the list of effective current assignments, use <b>null</b> if not recursive.
* @param compound Parent {@link CompoundAccess}.
*/
private void translateAnnotationAssignments(AttributeAssignment assignment, List<Assignment> effectiveAssignments,
CompoundAccess compound) {
List<Assignment> assng = null == effectiveAssignments ? new ArrayList<Assignment>() : effectiveAssignments;
for (int d = 0; d < assignment.getAssignmentDataCount(); d++) {
assng.add(assignment.getAssignmentData(d));
}
for (int d = 0; d < assng.size(); d++) {
Assignment effectiveAssignment = assng.get(d);
for (int e = 0; e < assignment.getElementCount(); e++) {
DecisionVariableDeclaration aElt = assignment.getElement(e);
IDatatype aEltType = aElt.getType();
translateAnnotationAssignment(effectiveAssignment, aElt, compound);
if (TypeQueries.isCompound(aEltType)) {
Compound cmp = (Compound) aEltType;
for (int s = 0; s < cmp.getDeclarationCount(); s++) {
DecisionVariableDeclaration slot = cmp.getDeclaration(s);
CompoundAccess cmpAccess;
if (compound == null) {
cmpAccess = new CompoundAccess(new Variable(aElt), slot.getName());
} else {
cmpAccess = new CompoundAccess(compound, slot.getName());
}
varMap.put(slot, cmpAccess);
inferTypeSafe(cmpAccess, null);
}
for (int s = 0; s < cmp.getDeclarationCount(); s++) {
DecisionVariableDeclaration slot = cmp.getDeclaration(s);
translateAnnotationAssignment(effectiveAssignment, slot, varMap.get(slot));
}
}
}
}
for (int a = 0; a < assignment.getAssignmentCount(); a++) {
translateAnnotationAssignments(assignment.getAssignment(a), assng, compound);
}
}
/**
* Method for creating attribute constraint for a specific element.
* @param assignment Attribute assignment constraint.
* @param element Elements to which the attribute is assigned.
* @param compound Nesting compound if there is one, may be <b>null</b> for none.
*/
private void translateAnnotationAssignment(Assignment assignment, DecisionVariableDeclaration element,
CompoundAccess compound) {
String attributeName = assignment.getName();
Attribute attrib = (Attribute) element.getAttribute(attributeName);
if (null != attrib) {
ConstraintSyntaxTree cst;
//handle annotations in compounds
if (null == compound) {
compound = varMap.get(element);
}
if (compound == null) {
cst = new AttributeVariable(new Variable(element), attrib);
} else {
cst = new AttributeVariable(compound, attrib);
}
cst = new OCLFeatureCall(cst, OclKeyWords.ASSIGNMENT,
substituteVariables(assignment.getExpression(), null, null, true));
inferTypeSafe(cst, null);
try { // assignedAttributeConstraints
addConstraint(otherConstraints, new Constraint(cst, project), false);
} catch (CSTSemanticException e) {
LOGGER.exception(e);
}
}
}
/**
* Translates and collects all constraints in {@link #project} by adding the collected constraints to the
* {@link #constraintBase}.
*
* @see #resolve()
*/
private void translateConstraints() {
// translate only if not marked for reuse and copy of constraint base is already available
if (null == constraintBaseCopy || constraintBaseCopy.isEmpty()) {
varMap.clear();
project.accept(projectVisitor);
addAllToConstraintBase(defaultConstraints);
addAllToConstraintBase(deferredDefaultConstraints);
addAllToConstraintBase(topLevelConstraints);
addAllToConstraintBase(otherConstraints);
constraintCounter = constraintBase.size();
variablesInConstraintsCounter = constraintMap.getDeclarationSize();
clearConstraintLists();
// if marked for re-use, copy constraint base
if (null != constraintBaseCopy) {
constraintBaseCopy.addAll(constraintBase);
}
}
}
/**
* Adding a constraint to a constraint set, checking for contained container/compound initializers if
* requested.
*
* @param target the target container to add the constraint to
* @param constraint the constraint
* @param checkForInitializers check also for initializers if (<code>true</code>), add only if (<code>false</code>)
*/
private void addConstraint(Collection<Constraint> target, Constraint constraint, boolean checkForInitializers) {
ConstraintSyntaxTree cst = constraint.getConsSyntax();
boolean add = true;
if (incremental) {
add = !CSTUtils.isAssignment(cst);
}
if (add && !considerFrozenConstraints) {
variablesFinder.setConfiguration(config);
cst.accept(variablesFinder);
Set<IAssignmentState> states = variablesFinder.getStates();
add = (!(1 == states.size() && states.contains(AssignmentState.FROZEN)));
variablesFinder.clear();
}
if (add) {
if (checkForInitializers) {
containerFinder.accept(cst);
if (containerFinder.isConstraintContainer()) {
checkContainerInitializer(containerFinder.getExpression(), false, constraint.getParent());
}
if (containerFinder.isCompoundInitializer()) {
checkCompoundInitializer(containerFinder.getExpression(), true, constraint.getParent());
}
containerFinder.clear();
}
target.add(constraint);
simpleAssignmentFinder.acceptAndClear(constraint);
}
}
/**
* Method for checking if {@link CompoundInitializer} holds
* a {@link de.uni_hildesheim.sse.ivml.CollectionInitializer} with {@link Constraint}s.
* @param exp expression to check.
* @param substituteVars <code>true</code> if {@link #varMap} shall be applied to substitute variables in
* <code>exp</code> (if variable is nested), <code>false</code> if <code>exp</code> shall be taken over as it is.
* @param parent parent for temporary constraints
*/
private void checkCompoundInitializer(ConstraintSyntaxTree exp, boolean substituteVars, IModelElement parent) {
CompoundInitializer compoundInit = (CompoundInitializer) exp;
for (int i = 0; i < compoundInit.getExpressionCount(); i++) {
if (compoundInit.getExpression(i) instanceof ContainerInitializer) {
checkContainerInitializer(compoundInit.getExpression(i), substituteVars, parent);
}
if (compoundInit.getExpression(i) instanceof CompoundInitializer) {
checkCompoundInitializer(compoundInit.getExpression(i), substituteVars, parent);
}
}
}
/**
* Method for checking if an expression is a {@link ContainerInitializer}.
* @param exp expression to be checked.
* @param substituteVars <code>true</code> if {@link #varMap} shall be applied to substitute variables in
* <code>exp</code> (if variable is nested), <code>false</code> if <code>exp</code> shall be taken over as it is.
* @param parent parent for temporary constraints
*/
private void checkContainerInitializer(ConstraintSyntaxTree exp, boolean substituteVars, IModelElement parent) {
ContainerInitializer containerInit = (ContainerInitializer) exp;
if (ConstraintType.TYPE.isAssignableFrom(containerInit.getType().getContainedType())) {
for (int i = 0; i < containerInit.getExpressionCount(); i++) {
Constraint constraint = new Constraint(parent);
ConstraintSyntaxTree cst = containerInit.getExpression(i);
if (substituteVars) {
cst = substituteVariables(cst, null, null, true);
}
try {
constraint.setConsSyntax(cst);
addConstraint(otherConstraints, constraint, false); // collectionConstraints
} catch (CSTSemanticException e) {
LOGGER.exception(e);
}
}
}
}
/**
* Method for getting all constraints relevant to a {@link Compound}.
* @param cmpType Compound to be analyzed.
* @param thisCompoundConstraints The list to add the compound {@link Constraint}s to.
* @param host True if this is a host compound.
*/
private void allCompoundConstraints(Compound cmpType,
List<Constraint> thisCompoundConstraints, boolean host) {
for (int i = 0; i < cmpType.getConstraintsCount(); i++) {
thisCompoundConstraints.add(cmpType.getConstraint(i));
}
if (host) { // TODO why not constraint expr via refines?
for (int i = 0; i < cmpType.getInheritedElementCount(); i++) {
DecisionVariableDeclaration decl = cmpType.getInheritedElement(i);
ConstraintSyntaxTree defaultValue = decl.getDefaultValue();
if (null != defaultValue) {
if (ConstraintType.TYPE.isAssignableFrom(decl.getType())) {
Constraint constraint = new Constraint(project);
try {
constraint.setConsSyntax(defaultValue);
thisCompoundConstraints.add(constraint);
} catch (CSTSemanticException e) {
LOGGER.exception(e);
}
}
}
}
}
for (int r = 0; r < cmpType.getRefinesCount(); r++) {
allCompoundConstraints(cmpType.getRefines(r), thisCompoundConstraints, false);
}
for (int a = 0; a < cmpType.getAssignmentCount(); a++) {
allAssignmentConstraints(cmpType.getAssignment(a), thisCompoundConstraints);
}
}
/**
* Collects all assignment constraints and adds them to <code>result</code>.
*
* @param assng the assignment constraint
* @param result the list of constraints to be modified as a side effect
*/
private void allAssignmentConstraints(AttributeAssignment assng, List<Constraint> result) {
for (int c = 0; c < assng.getConstraintsCount(); c++) {
result.add(assng.getConstraint(c));
}
for (int a = 0; a < assng.getAssignmentCount(); a++) {
allAssignmentConstraints(assng.getAssignment(a), result);
}
}
// <<< documented until here
// messages
/**
* Records information about the evaluation result, failed evaluation messages.
*
* @param constraint the constraint to record the actual messages for
*/
private void analyzeEvaluationResult(Constraint constraint) {
if (evaluator.constraintFailed()) {
FailedElementDetails failedElementDetails = new FailedElementDetails();
failedElementDetails.setProblemPoints(new HashSet<IDecisionVariable>(usedVariables));
failedElementDetails.setProblemConstraintPart(getFailedConstraintPart());
failedElementDetails.setProblemConstraint(constraint);
failedElementDetails.setErrorClassifier(ReasoningErrorCodes.FAILED_CONSTRAINT);
failedElements.addProblemConstraint(constraint, failedElementDetails);
if (Descriptor.LOGGING) {
LOGGER.debug("Failed constraint: " + toIvmlString(constraint));
printModelElements(config, "constraint resolved");
printProblemPoints(usedVariables);
}
} else if (evaluator.constraintFulfilled()) {
failedElements.removeProblemConstraint(constraint);
if (Descriptor.LOGGING) {
LOGGER.debug("Constraint fulfilled: " + toIvmlString(constraint));
}
}
// must be done always, constraints -> undefined may cause illegal variable assignments as side effect
for (int j = 0; j < evaluator.getMessageCount(); j++) {
Message msg = evaluator.getMessage(j);
AbstractVariable var = msg.getVariable();
if (var != null) {
// no local variable, i.e., defined for/within user-defined operation or within constraint
if (!(var.getParent() instanceof OperationDefinition) && !(var.getParent() instanceof Constraint)) {
usedVariables.clear();
usedVariables.add(msg.getDecision());
FailedElementDetails failedelementDetails = new FailedElementDetails();
failedelementDetails.setProblemPoints(new HashSet<IDecisionVariable>(usedVariables));
// due to NULL result if failed assignment
failedelementDetails.setProblemConstraintPart(constraint.getConsSyntax());
failedelementDetails.setProblemConstraint(constraint);
failedelementDetails.setErrorClassifier(ReasoningErrorCodes.FAILED_REASSIGNMENT);
failedElements.addProblemVariable(var, failedelementDetails);
if (Descriptor.LOGGING) {
LOGGER.debug("Assigment error: " + evaluator.getMessage(j).getVariable());
printProblemPoints(usedVariables);
}
}
}
}
}
// helpers, accessors
/**
* Adds <code>constraint</code> to the constraint base.
*
* @param constraint the constraint
*/
private void addToConstraintBase(Constraint constraint) {
constraintBase.addLast(constraint);
constraintBaseSet.add(constraint);
}
/**
* Method for using {@link SubstitutionVisitor} for constraint transformation. Uses the actual
* variable mapping in {@link #varMap} and may consider a mapping for <code>self</code>.
*
* @param cst Constraint to be transformed.
* @param selfEx an expression representing <i>self</i> (ignored if <b>null</b>, <code>self</code> and
* <code>selfEx</code> shall never both be specified/not <b>null</b>).
* @param self an variable declaration representing <i>self</i> (ignored if <b>null</b>).
* @param clear clear {@link #copyVisitor} if <code>true</code> or leave its state for further queries requring
* the caller to explicitly clear the copy visitor after usage
* @return Transformed constraint.
*/
private ConstraintSyntaxTree substituteVariables(ConstraintSyntaxTree cst, ConstraintSyntaxTree selfEx,
AbstractVariable self, boolean clear) {
copyVisitor.setMappings(varMap);
if (selfEx != null) {
copyVisitor.setSelf(selfEx);
}
if (self != null) {
copyVisitor.setSelf(self);
}
cst = copyVisitor.acceptAndClear(cst);
inferTypeSafe(cst, null);
return cst;
}
/**
* Adds all <code>constraints</code> to the constraint base.
*
* @param constraints the constraints
*/
private void addAllToConstraintBase(Collection<Constraint> constraints) {
constraintBase.addAll(constraints);
constraintBaseSet.addAll(constraints);
}
/**
* Method for clearing all constraint lists.
*/
private void clearConstraintLists() {
defaultConstraints.clear();
deferredDefaultConstraints.clear();
topLevelConstraints.clear();
otherConstraints.clear();
}
/**
* Will be called after a failure was detected in a default constraint of an {@link AbstractVariable}.
* @param decl The conflicting declaration of an {@link AbstractVariable}.
* Call {@link AbstractVariable#getDefaultValue()} to retrieve the conflicting constraint.
*/
@SuppressWarnings("unused")
private void conflictingDefault(AbstractVariable decl) {
// currently unused
}
/**
* Method for creating a clean {@link Configuration}.
* @param project Project for {@link Configuration}
* @return Created {@link Configuration}
*/
private Configuration createCleanConfiguration(Project project) {
return new Configuration(project, false);
}
/**
* Method for checking part of a failed constraints against null.
* @return null or part of a failed constraint.
*/
private ConstraintSyntaxTree getFailedConstraintPart() {
ConstraintSyntaxTree cstPart = null;
if (evaluator.getFailedExpression() != null) {
cstPart = evaluator.getFailedExpression()[0];
}
return cstPart;
}
/**
* Getter for the map of all ConstraintVariables.
* and their {@link Constraint}s.
* @return Map of constraint variables and their constraints.
*/
Map<Constraint, IDecisionVariable> getConstraintVariableMap() {
return constraintVariableMap;
}
/**
* Method for returning the overall count of evaluated constraints in the model.
* @return number of evaluated constraints.
*/
int constraintCount() {
return constraintCounter;
}
/**
* Method for returning the overall number of variables in the model.
* @return number of variables.
*/
int variableCount() {
return variablesCounter;
}
/**
* Method for returning the number of variables involved in constraints.
* @return number of variables.
*/
int variableInConstraintCount() {
return variablesInConstraintsCounter;
}
/**
* Method for returning the overall number of reevaluations in the model.
* @return number of reevaluations.
*/
int reevaluationCount() {
return reevaluationCounter;
}
/**
* Method for retrieving {@link FailedElements} with failed {@link Constraint}s and {@link IDecisionVariable}s.
* @return {@link FailedElements}
*/
FailedElements getFailedElements() {
return failedElements;
}
/**
* Sets whether reasoning shall happen incrementally.
*
* @param incremental if reasoning shall happen incrementally
* @see #setConsiderFrozenConstraints(boolean)
*/
void setIncremental(boolean incremental) {
this.incremental = incremental;
}
/**
* Defines whether frozen constraints shall be considered. Can speed up incremental reasoning.
*
* @param considerFrozenConstraints whether frozen constraint shall be considered (default <code>true</code>)
* @see #setIncremental(boolean)
*/
void setConsiderFrozenConstraints(boolean considerFrozenConstraints) {
this.considerFrozenConstraints = considerFrozenConstraints;
}
/**
* Factory method for creating the evaluation visitor.
*
* @return the evaluation visitor
*/
protected EvaluationVisitor createEvaluationVisitor() {
return new EvalVisitor();
}
/**
* Returns whether reasoning stopped due to a timeout.
*
* @return <code>true</code> for timeout, <code>false</code> else
*/
boolean hasTimeout() {
return hasTimeout;
}
/**
* Returns whether reasoning was stopped due to a user-request.
*
* @return <code>true</code> for stopped, <code>false</code> else
*/
boolean wasStopped() {
return wasStopped;
}
/**
* Returns whether the reasoner is (still) operating.
*
* @return <code>true</code> for operating, <code>false</code> else
*/
boolean isRunning() {
return isRunning;
}
/**
* Stops/terminates reasoning. If possible, a reasoner shall stop the reasoning
* operations as quick as possible. A reasoner must not implement this operation.
*
* @return <code>true</code> if the reasoner tries to stop, <code>false</code> else
* (operation not implemented)
*/
boolean stop() {
wasStopped = true;
return true;
}
/**
* Marks this instance for re-use. Must be called before the first call to {@link #resolve()}.
*/
void markForReuse() {
constraintBaseCopy = new LinkedList<Constraint>();
}
/**
* Clears this instance for reuse to free most of the resources.
*
* @see #markForReuse()
* @see #reInit()
*/
void clear() {
clearConstraintLists();
failedElements.clear();
scopeAssignments.clearScopeAssignments();
// keep the constraintMap
// keep the constraintVariableMap
constraintBase.clear();
constraintBaseSet.clear();
// keep constraintCounter - is set during translation
// keep variablesInConstraintsCounter - is set during translation
reevaluationCounter = 0;
// keep variablesCounter - is set during translation
hasTimeout = false;
isRunning = false;
wasStopped = false;
usedVariables.clear();
copyVisitor.clear();
varMap.clear();
containerFinder.clear();
simpleAssignmentFinder.clear();
}
/**
* Re-initializes this resolver instance to allocated resources only if really needed.
*
* @see #markForReuse()
* @see #reInit()
*/
void reInit() {
if (null != constraintBaseCopy) {
constraintBase.addAll(constraintBaseCopy);
constraintBaseSet.addAll(constraintBaseCopy);
}
}
}
| copyVisitor->substVisitor | Plugins/Reasoner/EASy-Original-Reasoner/de.uni_hildesheim.sse.reasoning.reasoner/src/net/ssehub/easy/reasoning/sseReasoner/Resolver.java | copyVisitor->substVisitor | <ide><path>lugins/Reasoner/EASy-Original-Reasoner/de.uni_hildesheim.sse.reasoning.reasoner/src/net/ssehub/easy/reasoning/sseReasoner/Resolver.java
<ide>
<ide> private Project project;
<ide> private transient Set<IDecisionVariable> usedVariables = new HashSet<IDecisionVariable>(100);
<del> private transient SubstitutionVisitor copyVisitor = new SubstitutionVisitor();
<add> private transient SubstitutionVisitor substVisitor = new SubstitutionVisitor();
<ide> private transient Map<AbstractVariable, CompoundAccess> varMap = new HashMap<AbstractVariable, CompoundAccess>(100);
<ide> private transient ContainerConstraintsFinder containerFinder = new ContainerConstraintsFinder();
<ide> private transient VariablesInNotSimpleAssignmentConstraintsFinder simpleAssignmentFinder
<ide> Variable replacement = new Variable(declaration);
<ide> //Copy and replace each instance of the internal declaration with the given instance
<ide> for (int i = 0; i < count; i++) {
<del> copyVisitor.addVariableMapping(dVar, replacement);
<del> csts[i] = copyVisitor.acceptAndClear(dType.getConstraint(i).getConsSyntax());
<add> substVisitor.addVariableMapping(dVar, replacement);
<add> csts[i] = substVisitor.acceptAndClear(dType.getConstraint(i).getConsSyntax());
<ide> }
<ide> }
<ide> return csts;
<ide> OclKeyWords.ASSIGNMENT, defaultValue);
<ide> defaultValue = substituteVariables(defaultValue, selfEx, self, false);
<ide> List<Constraint> targetCons = defaultConstraints;
<del> if (copyVisitor.containsSelf() || isOverriddenSlot(decl)) {
<add> if (substVisitor.containsSelf() || isOverriddenSlot(decl)) {
<ide> targetCons = deferredDefaultConstraints;
<ide> }
<ide> addConstraint(targetCons, new DefaultConstraint(defaultValue, project), true);
<ide> }
<del> copyVisitor.clear(); // clear false above
<add> substVisitor.clear(); // clear false above
<ide> } catch (CSTSemanticException e) {
<ide> LOGGER.exception(e); // should not occur, ok to log
<ide> }
<ide> * @param selfEx an expression representing <i>self</i> (ignored if <b>null</b>, <code>self</code> and
<ide> * <code>selfEx</code> shall never both be specified/not <b>null</b>).
<ide> * @param self an variable declaration representing <i>self</i> (ignored if <b>null</b>).
<del> * @param clear clear {@link #copyVisitor} if <code>true</code> or leave its state for further queries requring
<add> * @param clear clear {@link #substVisitor} if <code>true</code> or leave its state for further queries requring
<ide> * the caller to explicitly clear the copy visitor after usage
<ide> * @return Transformed constraint.
<ide> */
<ide> private ConstraintSyntaxTree substituteVariables(ConstraintSyntaxTree cst, ConstraintSyntaxTree selfEx,
<ide> AbstractVariable self, boolean clear) {
<del> copyVisitor.setMappings(varMap);
<add> substVisitor.setMappings(varMap);
<ide> if (selfEx != null) {
<del> copyVisitor.setSelf(selfEx);
<add> substVisitor.setSelf(selfEx);
<ide> }
<ide> if (self != null) {
<del> copyVisitor.setSelf(self);
<del> }
<del> cst = copyVisitor.acceptAndClear(cst);
<add> substVisitor.setSelf(self);
<add> }
<add> cst = substVisitor.acceptAndClear(cst);
<ide> inferTypeSafe(cst, null);
<ide> return cst;
<ide> }
<ide> isRunning = false;
<ide> wasStopped = false;
<ide> usedVariables.clear();
<del> copyVisitor.clear();
<add> substVisitor.clear();
<ide> varMap.clear();
<ide> containerFinder.clear();
<ide> simpleAssignmentFinder.clear(); |
|
Java | apache-2.0 | 3f8ab38fd3f34a013ea99eb49632b5ad397edfbf | 0 | photo/mobile-android,photo/mobile-android | package com.trovebox.android.app.util;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import android.app.Activity;
import android.text.TextUtils;
import com.google.analytics.tracking.android.EasyTracker;
import com.google.analytics.tracking.android.ExceptionParser;
import com.google.analytics.tracking.android.ExceptionReporter;
import com.google.analytics.tracking.android.GAServiceManager;
import com.trovebox.android.app.Preferences;
import com.trovebox.android.app.TroveboxApplication;
/**
* A wrapper class around GoogleAnalytics SDK
*
* @author Eugene Popovich
*/
public class TrackerUtils {
static final String TAG = TrackerUtils.class.getSimpleName();
/**
* Used for tests
*/
public static boolean SKIP_UNCAUGHT_SETUP = false;
/**
* The exception parser used to track exceptions
*/
static ExceptionParser parser = new ExceptionParser() {
@Override
public String getDescription(String threadName, Throwable t) {
return getStackTrace(t) + getTrackingSuffix(true);
}
};
private static String getStackTrace(Throwable throwable) {
final Writer result = new StringWriter();
final PrintWriter printWriter = new PrintWriter(result);
throwable.printStackTrace(printWriter);
return result.toString();
}
/**
* Setup uncaug exception handler
*/
public static void setupTrackerUncaughtExceptionHandler() {
if (SKIP_UNCAUGHT_SETUP)
{
return;
}
EasyTracker.getInstance().setContext(TroveboxApplication.getContext());
ExceptionReporter myHandler = new ExceptionReporter(
EasyTracker.getTracker(), // Currently used Tracker.
GAServiceManager.getInstance(), // GoogleAnalytics
Thread.getDefaultUncaughtExceptionHandler()); // Current default
// uncaught
// exception
// handler.
myHandler.setExceptionParser(parser);
Thread.setDefaultUncaughtExceptionHandler(myHandler);
}
/**
* Track social event
*
* @param network
* @param action
* @param target
*/
public static void trackSocial(String network, String action,
String target)
{
EasyTracker.getTracker().sendSocial(network, action,
target);
trackEvent("social", "action", network);
}
/**
* Track preference change event
*
* @param preferenceName
* @param preferenceHolder
*/
public static void trackPreferenceChangeEvent(String preferenceName, Object preferenceHolder)
{
trackPreferenceChangeEvent(preferenceName, null, preferenceHolder);
}
/**
* Track preference change event
*
* @param preferenceName
* @param preferenceValue
* @param preferenceHolder
*/
public static void trackPreferenceChangeEvent(String preferenceName, Object preferenceValue,
Object preferenceHolder)
{
String preferenceValueString = preferenceValue == null ? null : preferenceValue.toString();
trackUiEvent(preferenceHolder.getClass().getSimpleName() + ".PreferenceChange",
preferenceName
+ (TextUtils.isEmpty(preferenceValueString) ? "" : "."
+ preferenceValueString));
}
/**
* Track tab selected event
*
* @param tabName
* @param tabHolder
*/
public static void trackTabSelectedEvent(String tabName, Object tabHolder)
{
trackUiEvent(tabHolder.getClass().getSimpleName() + ".TabSelected", tabName);
}
/**
* Track tab reselected event
*
* @param tabName
* @param tabHolder
*/
public static void trackTabReselectedEvent(String tabName, Object tabHolder)
{
trackUiEvent(tabHolder.getClass().getSimpleName() + ".TabReselected", tabName);
}
/**
* Track navigation item selected event
*
* @param navigationItemName
* @param navigationItemHolder
*/
public static void trackNavigationItemSelectedEvent(String navigationItemName,
Object navigationItemHolder)
{
trackUiEvent(navigationItemHolder.getClass().getSimpleName() + ".NavigationItemSelected",
navigationItemName);
}
/**
* Track navigation item reselected event
*
* @param navigationItemName
* @param navigationItemHolder
*/
public static void trackNavigationItemReselectedEvent(String navigationItemName,
Object navigationItemHolder)
{
trackUiEvent(navigationItemHolder.getClass().getSimpleName() + ".NavigationItemReselected",
navigationItemName);
}
/**
* Track button click event
*
* @param buttonName
* @param buttonHolder
*/
public static void trackButtonClickEvent(String buttonName, Object buttonHolder)
{
trackUiEvent(buttonHolder.getClass().getSimpleName() + ".ButtonClick", buttonName);
}
/**
* Track options menu clicked event
*
* @param menuName
* @param menuHolder
*/
public static void trackOptionsMenuClickEvent(String menuName, Object menuHolder)
{
trackUiEvent(menuHolder.getClass().getSimpleName() + ".OptionsMenuClick", menuName);
}
/**
* Track context menu click event
*
* @param menuName
* @param menuHolder
*/
public static void trackContextMenuClickEvent(String menuName, Object menuHolder)
{
trackUiEvent(menuHolder.getClass().getSimpleName() + ".ContextMenuClick", menuName);
}
/**
* Track ui event
*
* @param action
* @param label
*/
public static void trackUiEvent(String action,
String label)
{
trackEvent("ui_event", action, label);
}
/**
* Track service event
*
* @param action
* @param label
*/
public static void trackServiceEvent(String action,
String label)
{
trackEvent("service_event", action, label);
}
/**
* Track error event
*
* @param action
* @param label
*/
public static void trackErrorEvent(String action,
String label)
{
trackEvent("error_event", action, label);
}
/**
* Track limit event
*
* @param action
* @param label
*/
public static void trackLimitEvent(String action,
String label)
{
trackEvent("limit_event", action, label);
}
/**
* Track background event
*
* @param action
* @param label
*/
public static void trackBackgroundEvent(String action,
String label)
{
trackEvent("background_event", action, label);
}
/**
* Track In-app billing event
*
* @param action
* @param label
*/
public static void trackInAppBillingEvent(String action,
String label)
{
trackEvent("in_app_billing_event", action, label);
}
/**
* Track background event
*
* @param action
* @param eventHolder
*/
public static void trackBackgroundEvent(String action,
Object eventHolder)
{
trackEvent("background_event", action, eventHolder.getClass().getSimpleName());
}
/**
* Track an event
*
* @param category
* @param action
* @param label
*/
public static void trackEvent(String category,
String action,
String label)
{
EasyTracker.getTracker().sendEvent(category + getTrackingSuffix(), action, label, null);
}
/**
* @param inteval
* @param action
* @param holder
*/
public static void trackDataLoadTiming(long inteval, String action, String holder)
{
trackTiming("data_load", inteval, action, holder);
}
/**
* @param inteval
* @param action
* @param holder
*/
public static void trackDataProcessingTiming(long inteval, String action, String holder)
{
trackTiming("data_processing", inteval, action, holder);
}
/**
* Track timing
*
* @param category
* @param inteval
* @param name
* @param label
*/
public static void trackTiming(String category, long inteval, String name, String label)
{
EasyTracker.getTracker().sendTiming(category + getTrackingSuffix(), inteval, name, label);
}
/**
* Track view
*
* @param view
*/
public static void trackView(Object view)
{
EasyTracker.getTracker().sendView(view.getClass().getSimpleName() + getTrackingSuffix());
}
/**
* Track throwable
*
* @param t
*/
public static void trackThrowable(Throwable t)
{
EasyTracker.getInstance().setContext(TroveboxApplication.getContext());
EasyTracker.getTracker().setExceptionParser(parser);
EasyTracker.getTracker().sendException(Thread.currentThread().getName(), t, false);
}
/**
* Track message as exception
* @param message
*/
public static void trackException(String message)
{
EasyTracker.getTracker().sendException(message, false);
}
/**
* Called when activity is started
*
* @param activity
*/
public static void activityStart(Activity activity)
{
EasyTracker.getInstance().activityStart(activity);
}
/**
* Called when activity is stopped
*
* @param activity
*/
public static void activityStop(Activity activity)
{
EasyTracker.getInstance().activityStop(activity);
}
static String getTrackingSuffix()
{
return getTrackingSuffix(false);
}
/**
* Get the tracking suffix to separate self_hosted usage from the hosted
*
* @param trackRetrievalError
* @return
*/
static String getTrackingSuffix(boolean trackRetrievalError)
{
try
{
return Preferences.isLoggedIn() && Preferences.isSelfHosted() ? " (self_hosted)" : "";
} catch (Throwable t)
{
CommonUtils.error(TAG, null, t);
return trackRetrievalError ?
CommonUtils.format(" (suffix_retrieval_error: %1$s)", getStackTrace(t))
: " (suffix_retrieval_error)";
}
}
}
| app/src/com/trovebox/android/app/util/TrackerUtils.java | package com.trovebox.android.app.util;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import android.app.Activity;
import android.text.TextUtils;
import com.google.analytics.tracking.android.EasyTracker;
import com.google.analytics.tracking.android.ExceptionParser;
import com.google.analytics.tracking.android.ExceptionReporter;
import com.google.analytics.tracking.android.GAServiceManager;
import com.trovebox.android.app.TroveboxApplication;
/**
* A wrapper class around GoogleAnalytics SDK
*
* @author Eugene Popovich
*/
public class TrackerUtils {
/**
* Used for tests
*/
public static boolean SKIP_UNCAUGHT_SETUP = false;
/**
* The exception parser used to track exceptions
*/
static ExceptionParser parser = new ExceptionParser() {
@Override
public String getDescription(String threadName, Throwable t) {
return getStackTrace(t);
}
private String getStackTrace(Throwable throwable) {
final Writer result = new StringWriter();
final PrintWriter printWriter = new PrintWriter(result);
throwable.printStackTrace(printWriter);
return result.toString();
}
};
/**
* Setup uncaug exception handler
*/
public static void setupTrackerUncaughtExceptionHandler() {
if (SKIP_UNCAUGHT_SETUP)
{
return;
}
EasyTracker.getInstance().setContext(TroveboxApplication.getContext());
ExceptionReporter myHandler = new ExceptionReporter(
EasyTracker.getTracker(), // Currently used Tracker.
GAServiceManager.getInstance(), // GoogleAnalytics
Thread.getDefaultUncaughtExceptionHandler()); // Current default
// uncaught
// exception
// handler.
myHandler.setExceptionParser(parser);
Thread.setDefaultUncaughtExceptionHandler(myHandler);
}
/**
* Track social event
*
* @param network
* @param action
* @param target
*/
public static void trackSocial(String network, String action,
String target)
{
EasyTracker.getTracker().sendSocial(network, action,
target);
trackEvent("social", "action", network);
}
/**
* Track preference change event
*
* @param preferenceName
* @param preferenceHolder
*/
public static void trackPreferenceChangeEvent(String preferenceName, Object preferenceHolder)
{
trackPreferenceChangeEvent(preferenceName, null, preferenceHolder);
}
/**
* Track preference change event
*
* @param preferenceName
* @param preferenceValue
* @param preferenceHolder
*/
public static void trackPreferenceChangeEvent(String preferenceName, Object preferenceValue,
Object preferenceHolder)
{
String preferenceValueString = preferenceValue == null ? null : preferenceValue.toString();
trackUiEvent(preferenceHolder.getClass().getSimpleName() + ".PreferenceChange",
preferenceName
+ (TextUtils.isEmpty(preferenceValueString) ? "" : "."
+ preferenceValueString));
}
/**
* Track tab selected event
*
* @param tabName
* @param tabHolder
*/
public static void trackTabSelectedEvent(String tabName, Object tabHolder)
{
trackUiEvent(tabHolder.getClass().getSimpleName() + ".TabSelected", tabName);
}
/**
* Track tab reselected event
*
* @param tabName
* @param tabHolder
*/
public static void trackTabReselectedEvent(String tabName, Object tabHolder)
{
trackUiEvent(tabHolder.getClass().getSimpleName() + ".TabReselected", tabName);
}
/**
* Track navigation item selected event
*
* @param navigationItemName
* @param navigationItemHolder
*/
public static void trackNavigationItemSelectedEvent(String navigationItemName,
Object navigationItemHolder)
{
trackUiEvent(navigationItemHolder.getClass().getSimpleName() + ".NavigationItemSelected",
navigationItemName);
}
/**
* Track navigation item reselected event
*
* @param navigationItemName
* @param navigationItemHolder
*/
public static void trackNavigationItemReselectedEvent(String navigationItemName,
Object navigationItemHolder)
{
trackUiEvent(navigationItemHolder.getClass().getSimpleName() + ".NavigationItemReselected",
navigationItemName);
}
/**
* Track button click event
*
* @param buttonName
* @param buttonHolder
*/
public static void trackButtonClickEvent(String buttonName, Object buttonHolder)
{
trackUiEvent(buttonHolder.getClass().getSimpleName() + ".ButtonClick", buttonName);
}
/**
* Track options menu clicked event
*
* @param menuName
* @param menuHolder
*/
public static void trackOptionsMenuClickEvent(String menuName, Object menuHolder)
{
trackUiEvent(menuHolder.getClass().getSimpleName() + ".OptionsMenuClick", menuName);
}
/**
* Track context menu click event
*
* @param menuName
* @param menuHolder
*/
public static void trackContextMenuClickEvent(String menuName, Object menuHolder)
{
trackUiEvent(menuHolder.getClass().getSimpleName() + ".ContextMenuClick", menuName);
}
/**
* Track ui event
*
* @param action
* @param label
*/
public static void trackUiEvent(String action,
String label)
{
trackEvent("ui_event", action, label);
}
/**
* Track service event
*
* @param action
* @param label
*/
public static void trackServiceEvent(String action,
String label)
{
trackEvent("service_event", action, label);
}
/**
* Track error event
*
* @param action
* @param label
*/
public static void trackErrorEvent(String action,
String label)
{
trackEvent("error_event", action, label);
}
/**
* Track limit event
*
* @param action
* @param label
*/
public static void trackLimitEvent(String action,
String label)
{
trackEvent("limit_event", action, label);
}
/**
* Track background event
*
* @param action
* @param label
*/
public static void trackBackgroundEvent(String action,
String label)
{
trackEvent("background_event", action, label);
}
/**
* Track In-app billing event
*
* @param action
* @param label
*/
public static void trackInAppBillingEvent(String action,
String label)
{
trackEvent("in_app_billing_event", action, label);
}
/**
* Track background event
*
* @param action
* @param eventHolder
*/
public static void trackBackgroundEvent(String action,
Object eventHolder)
{
trackEvent("background_event", action, eventHolder.getClass().getSimpleName());
}
/**
* Track an event
*
* @param category
* @param action
* @param label
*/
public static void trackEvent(String category,
String action,
String label)
{
EasyTracker.getTracker().sendEvent(category, action, label, null);
}
/**
* @param inteval
* @param action
* @param holder
*/
public static void trackDataLoadTiming(long inteval, String action, String holder)
{
trackTiming("data_load", inteval, action, holder);
}
/**
* @param inteval
* @param action
* @param holder
*/
public static void trackDataProcessingTiming(long inteval, String action, String holder)
{
trackTiming("data_processing", inteval, action, holder);
}
/**
* Track timing
*
* @param category
* @param inteval
* @param name
* @param label
*/
public static void trackTiming(String category, long inteval, String name, String label)
{
EasyTracker.getTracker().sendTiming(category, inteval, name, label);
}
/**
* Track view
*
* @param view
*/
public static void trackView(Object view)
{
EasyTracker.getTracker().sendView(view.getClass().getSimpleName());
}
/**
* Track throwable
*
* @param t
*/
public static void trackThrowable(Throwable t)
{
EasyTracker.getInstance().setContext(TroveboxApplication.getContext());
EasyTracker.getTracker().setExceptionParser(parser);
EasyTracker.getTracker().sendException(Thread.currentThread().getName(), t, false);
}
/**
* Track message as exception
* @param message
*/
public static void trackException(String message)
{
EasyTracker.getTracker().sendException(message, false);
}
/**
* Called when activity is started
*
* @param activity
*/
public static void activityStart(Activity activity)
{
EasyTracker.getInstance().activityStart(activity);
}
/**
* Called when activity is stopped
*
* @param activity
*/
public static void activityStop(Activity activity)
{
EasyTracker.getInstance().activityStop(activity);
}
}
| #374
- TrackerUtils: added additional suffix to the self-hosted event
categories and exceptions
- TrackerUtils: added new methods getTrackingSuffix | app/src/com/trovebox/android/app/util/TrackerUtils.java | #374 - TrackerUtils: added additional suffix to the self-hosted event categories and exceptions - TrackerUtils: added new methods getTrackingSuffix | <ide><path>pp/src/com/trovebox/android/app/util/TrackerUtils.java
<ide> import com.google.analytics.tracking.android.ExceptionParser;
<ide> import com.google.analytics.tracking.android.ExceptionReporter;
<ide> import com.google.analytics.tracking.android.GAServiceManager;
<add>import com.trovebox.android.app.Preferences;
<ide> import com.trovebox.android.app.TroveboxApplication;
<ide>
<ide> /**
<ide> * @author Eugene Popovich
<ide> */
<ide> public class TrackerUtils {
<add> static final String TAG = TrackerUtils.class.getSimpleName();
<ide> /**
<ide> * Used for tests
<ide> */
<ide> static ExceptionParser parser = new ExceptionParser() {
<ide> @Override
<ide> public String getDescription(String threadName, Throwable t) {
<del> return getStackTrace(t);
<add> return getStackTrace(t) + getTrackingSuffix(true);
<ide> }
<ide>
<del> private String getStackTrace(Throwable throwable) {
<del> final Writer result = new StringWriter();
<del> final PrintWriter printWriter = new PrintWriter(result);
<del> throwable.printStackTrace(printWriter);
<del>
<del> return result.toString();
<del> }
<ide> };
<add>
<add> private static String getStackTrace(Throwable throwable) {
<add> final Writer result = new StringWriter();
<add> final PrintWriter printWriter = new PrintWriter(result);
<add> throwable.printStackTrace(printWriter);
<add>
<add> return result.toString();
<add> }
<ide>
<ide> /**
<ide> * Setup uncaug exception handler
<ide> String action,
<ide> String label)
<ide> {
<del> EasyTracker.getTracker().sendEvent(category, action, label, null);
<add> EasyTracker.getTracker().sendEvent(category + getTrackingSuffix(), action, label, null);
<ide> }
<ide>
<ide> /**
<ide> */
<ide> public static void trackTiming(String category, long inteval, String name, String label)
<ide> {
<del> EasyTracker.getTracker().sendTiming(category, inteval, name, label);
<add> EasyTracker.getTracker().sendTiming(category + getTrackingSuffix(), inteval, name, label);
<ide> }
<ide>
<ide> /**
<ide> */
<ide> public static void trackView(Object view)
<ide> {
<del> EasyTracker.getTracker().sendView(view.getClass().getSimpleName());
<add> EasyTracker.getTracker().sendView(view.getClass().getSimpleName() + getTrackingSuffix());
<ide> }
<ide>
<ide> /**
<ide> {
<ide> EasyTracker.getInstance().activityStop(activity);
<ide> }
<add>
<add> static String getTrackingSuffix()
<add> {
<add> return getTrackingSuffix(false);
<add> }
<add>
<add> /**
<add> * Get the tracking suffix to separate self_hosted usage from the hosted
<add> *
<add> * @param trackRetrievalError
<add> * @return
<add> */
<add> static String getTrackingSuffix(boolean trackRetrievalError)
<add> {
<add> try
<add> {
<add> return Preferences.isLoggedIn() && Preferences.isSelfHosted() ? " (self_hosted)" : "";
<add> } catch (Throwable t)
<add> {
<add> CommonUtils.error(TAG, null, t);
<add> return trackRetrievalError ?
<add> CommonUtils.format(" (suffix_retrieval_error: %1$s)", getStackTrace(t))
<add> : " (suffix_retrieval_error)";
<add> }
<add> }
<ide> } |
|
Java | apache-2.0 | 650360a9c07faa2f5daf1b07d4aee7bb36e240a4 | 0 | Schinzel/basic-utils | package io.schinzel.basicutils;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import static org.exparity.hamcrest.date.LocalDateTimeMatchers.within;
import static org.junit.Assert.*;
import org.junit.Test;
/**
*
* @author schinzel
*/
public class MiscUtilTest extends MiscUtil {
@Test
public void testSnooze() {
int snoozeTimeInMillis = 100;
//Test the snooze 10 times
for (int i = 0; i < 10; i++) {
LocalDateTime start = LocalDateTime.now();
MiscUtil.snooze(snoozeTimeInMillis);
//Check that the snooze does not differ more than 20 ms of the requested snooze time.
assertThat(LocalDateTime.now(),
within(20, ChronoUnit.MILLIS, start.plus(snoozeTimeInMillis, ChronoUnit.MILLIS)));
}
}
@Test
public void testSnoozeSeconds() {
int snoozeTimeInSeconds = 1;
LocalDateTime start = LocalDateTime.now();
MiscUtil.snoozeSeconds(snoozeTimeInSeconds);
//Check that the snooze does not differ more than 20 ms of the requested snooze time.
assertThat(LocalDateTime.now(),
within(20, ChronoUnit.MILLIS, start.plus(snoozeTimeInSeconds, ChronoUnit.SECONDS)));
}
}
| src/test/java/io/schinzel/basicutils/MiscUtilTest.java | package io.schinzel.basicutils;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import static org.exparity.hamcrest.date.LocalDateTimeMatchers.within;
import static org.junit.Assert.*;
import org.junit.Test;
/**
*
* @author schinzel
*/
public class MiscUtilTest extends MiscUtil {
@Test
public void testSnooze() {
int snoozeTime = 100;
//Test the snooze 10 times
for (int i = 0; i < 10; i++) {
LocalDateTime start = LocalDateTime.now();
MiscUtil.snooze(snoozeTime);
//Check that the snooze does not differ more than 20% of the request snooze time.
assertThat(LocalDateTime.now(),
within(20, ChronoUnit.MILLIS, start.plus(snoozeTime, ChronoUnit.MILLIS)));
}
}
}
| Test added
| src/test/java/io/schinzel/basicutils/MiscUtilTest.java | Test added | <ide><path>rc/test/java/io/schinzel/basicutils/MiscUtilTest.java
<ide>
<ide> @Test
<ide> public void testSnooze() {
<del> int snoozeTime = 100;
<add> int snoozeTimeInMillis = 100;
<ide> //Test the snooze 10 times
<ide> for (int i = 0; i < 10; i++) {
<ide> LocalDateTime start = LocalDateTime.now();
<del> MiscUtil.snooze(snoozeTime);
<del> //Check that the snooze does not differ more than 20% of the request snooze time.
<add> MiscUtil.snooze(snoozeTimeInMillis);
<add> //Check that the snooze does not differ more than 20 ms of the requested snooze time.
<ide> assertThat(LocalDateTime.now(),
<del> within(20, ChronoUnit.MILLIS, start.plus(snoozeTime, ChronoUnit.MILLIS)));
<add> within(20, ChronoUnit.MILLIS, start.plus(snoozeTimeInMillis, ChronoUnit.MILLIS)));
<ide> }
<ide> }
<ide>
<add>
<add> @Test
<add> public void testSnoozeSeconds() {
<add> int snoozeTimeInSeconds = 1;
<add> LocalDateTime start = LocalDateTime.now();
<add> MiscUtil.snoozeSeconds(snoozeTimeInSeconds);
<add> //Check that the snooze does not differ more than 20 ms of the requested snooze time.
<add> assertThat(LocalDateTime.now(),
<add> within(20, ChronoUnit.MILLIS, start.plus(snoozeTimeInSeconds, ChronoUnit.SECONDS)));
<add> }
<add>
<ide> } |
|
Java | apache-2.0 | c34c3a1b5364566d4c83d1ceaa73406c1b04d040 | 0 | kmi/iserve,kmi/iserve,kmi/iserve,kmi/iserve | /*
* Copyright (c) 2013. Knowledge Media Institute - The Open University
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.ac.open.kmi.iserve.discovery.disco.impl;
import com.google.common.base.Stopwatch;
import com.google.common.collect.Table;
import es.usc.citius.composit.importer.wsc.wscxml.WSCImporter;
import junit.extensions.TestSetup;
import junit.framework.Assert;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.apache.log4j.BasicConfigurator;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import uk.ac.open.kmi.iserve.commons.io.MediaType;
import uk.ac.open.kmi.iserve.commons.io.Syntax;
import uk.ac.open.kmi.iserve.commons.io.Transformer;
import uk.ac.open.kmi.iserve.commons.io.util.FilenameFilterBySyntax;
import uk.ac.open.kmi.iserve.commons.model.Service;
import uk.ac.open.kmi.iserve.discovery.api.MatchResult;
import uk.ac.open.kmi.iserve.discovery.disco.DiscoMatchType;
import uk.ac.open.kmi.iserve.sal.manager.impl.ManagerSingleton;
import java.io.File;
import java.io.FileInputStream;
import java.io.FilenameFilter;
import java.net.URI;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* DiscoMatcherTest
*
* @author <a href="mailto:[email protected]">Carlos Pedrinaci</a> (KMi - The Open University)
* @since 01/08/2013
*/
public class LogicConceptMatcherWSC08Test extends TestCase {
private static final Logger log = LoggerFactory.getLogger(LogicConceptMatcherWSC08Test.class);
private static final String WSC08_01_SERVICES = "/wsc08-dataset01/services/services.xml";
private static final String MEDIATYPE = "text/xml";
private LogicConceptMatcher matcher = new LogicConceptMatcher();
public static TestSetup suite() {
TestSetup setup = new TestSetup(new TestSuite(LogicConceptMatcherWSC08Test.class)) {
protected void setUp() throws Exception {
BasicConfigurator.configure();
// do your one-time setup here
// Clean the whole thing before testing
ManagerSingleton.getInstance().clearRegistry();
log.info("Importing WSC 2008 services");
String file = LogicConceptMatcherWSC08Test.class.getResource(WSC08_01_SERVICES).getFile();
log.debug("Using " + file);
File services = new File(file);
//List<Service> result = new WSCImporter().transform(new FileInputStream(services), null);
// Automatic plugin discovery
List<Service> result = Transformer.getInstance().transform(services, null, MEDIATYPE);
// Import all services
for(Service s : result){
URI uri = ManagerSingleton.getInstance().importService(s);
Assert.assertNotNull(uri);
log.info("Service added: " + uri.toASCIIString());
}
/*
URI testFolder = LogicConceptMatcherWSC08Test.class.getResource(WSC08_01_SERVICES).toURI();
log.debug("Test folder {}", testFolder);
FilenameFilter ttlFilter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return (name.endsWith(".owl") || name.endsWith(".owls"));
}
};
File dir = new File(testFolder);
File[] msmTtlTcFiles = dir.listFiles(ttlFilter);
log.debug("Valid services detected: {}", msmTtlTcFiles);
FileInputStream in;
// Upload every document and obtain their URLs
for (File ttlFile : msmTtlTcFiles) {
log.debug("Importing {}", ttlFile.getAbsolutePath());
in = new FileInputStream(ttlFile);
ManagerSingleton.getInstance().importService(in, OWLS_MEDIATYPE);
} */
}
protected void tearDown() throws Exception {
// do your one-time tear down here!
}
};
return setup;
}
public void testDirectPluginMatch() throws Exception {
URI origin = URI.create("http://127.0.0.1/ontology/taxonomy.owl#con1655991159");
URI destination = URI.create("http://127.0.0.1/ontology/taxonomy.owl#con409488015");
// Obtain matches
Stopwatch stopwatch = new Stopwatch().start();
MatchResult match = matcher.match(origin, destination);
stopwatch.stop();
log.info("Obtained match in {} \n {}", stopwatch, match);
Assert.assertEquals(DiscoMatchType.Plugin, match.getMatchType());
}
public void testDirectSubsumeMatch() throws Exception {
URI origin = URI.create("http://127.0.0.1/ontology/taxonomy.owl#con1655991159");
URI destination = URI.create("http://127.0.0.1/ontology/taxonomy.owl#con409488015");
// Obtain matches
Stopwatch stopwatch = new Stopwatch().start();
MatchResult match = matcher.match(destination, origin);
stopwatch.stop();
log.info("Obtained match in {} \n {}", stopwatch, match);
Assert.assertEquals(DiscoMatchType.Subsume, match.getMatchType());
}
public void testIndirectPluginMatch() throws Exception {
URI origin = URI.create("http://127.0.0.1/ontology/taxonomy.owl#con1901563774");
URI destination = URI.create("http://127.0.0.1/ontology/taxonomy.owl#con241744282");
// Obtain matches
Stopwatch stopwatch = new Stopwatch().start();
MatchResult match = matcher.match(origin, destination);
stopwatch.stop();
log.info("Obtained match in {} \n {}", stopwatch, match);
Assert.assertEquals(DiscoMatchType.Plugin, match.getMatchType());
}
/*
@Test
public void testMatchBySets() throws Exception {
Set<URI> origins = new HashSet<URI>();
origins.add(URI.create("http://127.0.0.1/ontology/SUMO.owl#EuroDollar"));
origins.add(URI.create("http://127.0.0.1/ontology/SUMO.owl#Abstract"));
origins.add(URI.create("http://127.0.0.1/ontology/SUMO.owl#TherapeuticProcess"));
Set<URI> destinations = new HashSet<URI>();
destinations.add(URI.create("http://127.0.0.1/ontology/SUMO.owl#Quantity"));
destinations.add(URI.create("http://127.0.0.1/ontology/SUMO.owl#IntentionalProcess"));
destinations.add(URI.create("http://127.0.0.1/ontology/SUMO.owl#Entity"));
// Obtain cross-matches
Stopwatch stopwatch = new Stopwatch().start();
Table<URI, URI, MatchResult> matches =
matcher.match(origins, destinations);
stopwatch.stop();
log.info("Obtained all cross matches ({}) in {} \n {}", matches.size(), stopwatch, matches);
Assert.assertEquals(matches.size(), 4);
stopwatch.reset();
}
@Test
public void testListMatchesOfType() throws Exception {
// Obtain only exact
Stopwatch stopwatch = new Stopwatch().start();
Map<URI, MatchResult> matches =
matcher.listMatchesOfType(URI.create("http://127.0.0.1/ontology/SUMO.owl#EuroDollar"), DiscoMatchType.Exact);
stopwatch.stop();
log.info("Obtained all exact matches ({}) in {} \n", matches.size(), stopwatch, matches);
Assert.assertEquals(matches.size(), 1);
stopwatch.reset();
// Obtain only plugin
stopwatch.start();
matches = matcher.listMatchesOfType(URI.create("http://127.0.0.1/ontology/SUMO.owl#EuroDollar"), DiscoMatchType.Plugin);
stopwatch.stop();
log.info("Obtained all plugin matches ({}) in {} \n", matches.size(), stopwatch, matches);
Assert.assertEquals(matches.size(), 5);
stopwatch.reset();
// Obtain only plugin
stopwatch.start();
matches = matcher.listMatchesOfType(URI.create("http://127.0.0.1/ontology/SUMO.owl#EuroDollar"), DiscoMatchType.Subsume);
stopwatch.stop();
log.info("Obtained all plugin matches ({}) in {} \n", matches.size(), stopwatch, matches);
Assert.assertEquals(matches.size(), 0);
stopwatch.reset();
}
@Test
public void testListMatchesAtLeastOfType() throws Exception {
// Obtain at least exact
Stopwatch stopwatch = new Stopwatch().start();
Map<URI, MatchResult> matches =
matcher.listMatchesAtLeastOfType(URI.create("http://127.0.0.1/ontology/SUMO.owl#EuroDollar"), DiscoMatchType.Exact);
stopwatch.stop();
log.info("Obtained at least Exact matches ({}) in {} \n", matches.size(), stopwatch, matches);
Assert.assertEquals(matches.size(), 1);
stopwatch.reset();
// Obtain at least plugin
stopwatch.start();
matches = matcher.listMatchesAtLeastOfType(URI.create("http://127.0.0.1/ontology/SUMO.owl#EuroDollar"), DiscoMatchType.Plugin);
stopwatch.stop();
log.info("Obtained at least Plugin matches ({}) in {} \n", matches.size(), stopwatch, matches);
Assert.assertEquals(matches.size(), 6);
stopwatch.reset();
// Obtain at least subsumes
stopwatch.start();
matches = matcher.listMatchesAtLeastOfType(URI.create("http://127.0.0.1/ontology/SUMO.owl#EuroDollar"), DiscoMatchType.Subsume);
stopwatch.stop();
log.info("Obtained at least Subsumes matches ({}) in {} \n", matches.size(), stopwatch, matches);
Assert.assertEquals(matches.size(), 6);
stopwatch.reset();
// Obtain at least fail
stopwatch.start();
matches = matcher.listMatchesAtLeastOfType(URI.create("http://127.0.0.1/ontology/SUMO.owl#EuroDollar"), DiscoMatchType.Fail);
stopwatch.stop();
log.info("Obtained at least Fail matches ({}) in {} \n", matches.size(), stopwatch, matches);
Assert.assertEquals(matches.size(), 6);
stopwatch.reset();
}
@Test
public void testListMatchesAtMostOfType() throws Exception {
// Obtain at least exact
Stopwatch stopwatch = new Stopwatch().start();
Map<URI, MatchResult> matches =
matcher.listMatchesAtMostOfType(URI.create("http://127.0.0.1/ontology/SUMO.owl#EuroDollar"), DiscoMatchType.Exact);
stopwatch.stop();
log.info("Obtained at most Exact matches ({}) in {} \n", matches.size(), stopwatch, matches);
Assert.assertEquals(matches.size(), 6);
stopwatch.reset();
// Obtain at least plugin
stopwatch.start();
matches = matcher.listMatchesAtMostOfType(URI.create("http://127.0.0.1/ontology/SUMO.owl#EuroDollar"), DiscoMatchType.Plugin);
stopwatch.stop();
log.info("Obtained at most Plugin matches ({}) in {} \n", matches.size(), stopwatch, matches);
Assert.assertEquals(matches.size(), 5);
stopwatch.reset();
// Obtain at least subsumes
stopwatch.start();
matches = matcher.listMatchesAtMostOfType(URI.create("http://127.0.0.1/ontology/SUMO.owl#EuroDollar"), DiscoMatchType.Subsume);
stopwatch.stop();
log.info("Obtained at most Subsumes matches ({}) in {} \n", matches.size(), stopwatch, matches);
Assert.assertEquals(matches.size(), 0);
stopwatch.reset();
// Obtain at least fail
stopwatch.start();
matches = matcher.listMatchesAtMostOfType(URI.create("http://127.0.0.1/ontology/SUMO.owl#EuroDollar"), DiscoMatchType.Fail);
stopwatch.stop();
log.info("Obtained at most Fail matches ({}) in {} \n", matches.size(), stopwatch, matches);
Assert.assertEquals(matches.size(), 0);
stopwatch.reset();
}
@Test
public void testListMatchesWithinRange() throws Exception {
// Obtain all matches
Stopwatch stopwatch = new Stopwatch().start();
Map<URI, MatchResult> matches =
matcher.listMatchesWithinRange(URI.create("http://127.0.0.1/ontology/SUMO.owl#EuroDollar"), DiscoMatchType.Fail, DiscoMatchType.Exact);
stopwatch.stop();
log.info("Obtained all matches ({}) in {} \n", matches.size(), stopwatch, matches);
Assert.assertEquals(matches.size(), 6);
stopwatch.reset();
// Obtain only exact
stopwatch.start();
matches = matcher.listMatchesWithinRange(URI.create("http://127.0.0.1/ontology/SUMO.owl#EuroDollar"), DiscoMatchType.Exact, DiscoMatchType.Exact);
stopwatch.stop();
log.info("Obtained exact matches ({}) in {} \n", matches.size(), stopwatch, matches);
Assert.assertEquals(matches.size(), 1);
stopwatch.reset();
// Obtain from Plugin up
stopwatch.start();
matches = matcher.listMatchesWithinRange(URI.create("http://127.0.0.1/ontology/SUMO.owl#EuroDollar"), DiscoMatchType.Plugin, DiscoMatchType.Exact);
stopwatch.stop();
log.info("Obtained matches >= Plugin ({}) in {} \n", matches.size(), stopwatch, matches);
Assert.assertEquals(matches.size(), 6);
stopwatch.reset();
// Obtain Plugin and subsumes
stopwatch.start();
matches = matcher.listMatchesWithinRange(URI.create("http://127.0.0.1/ontology/SUMO.owl#EuroDollar"), DiscoMatchType.Subsume, DiscoMatchType.Plugin);
stopwatch.stop();
log.info("Obtained Subsumes >= matches >= Plugin ({}) in {} \n", matches.size(), stopwatch, matches);
Assert.assertEquals(matches.size(), 5);
stopwatch.reset();
// Invert limits
stopwatch.start();
matches = matcher.listMatchesWithinRange(URI.create("http://127.0.0.1/ontology/SUMO.owl#EuroDollar"), DiscoMatchType.Exact, DiscoMatchType.Plugin);
stopwatch.stop();
log.info("Obtained Exact >= matches >= Plugin ({}) in {} \n", matches.size(), stopwatch, matches);
Assert.assertEquals(matches.size(), 0);
stopwatch.reset();
}*/
}
| iserve-discovery-disco/src/test/java/uk/ac/open/kmi/iserve/discovery/disco/impl/LogicConceptMatcherWSC08Test.java | /*
* Copyright (c) 2013. Knowledge Media Institute - The Open University
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.ac.open.kmi.iserve.discovery.disco.impl;
import com.google.common.base.Stopwatch;
import com.google.common.collect.Table;
import es.usc.citius.composit.importer.wsc.wscxml.WSCImporter;
import junit.extensions.TestSetup;
import junit.framework.Assert;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.apache.log4j.BasicConfigurator;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import uk.ac.open.kmi.iserve.commons.io.MediaType;
import uk.ac.open.kmi.iserve.commons.io.Syntax;
import uk.ac.open.kmi.iserve.commons.io.Transformer;
import uk.ac.open.kmi.iserve.commons.io.util.FilenameFilterBySyntax;
import uk.ac.open.kmi.iserve.commons.model.Service;
import uk.ac.open.kmi.iserve.discovery.api.MatchResult;
import uk.ac.open.kmi.iserve.discovery.disco.DiscoMatchType;
import uk.ac.open.kmi.iserve.sal.manager.impl.ManagerSingleton;
import java.io.File;
import java.io.FileInputStream;
import java.io.FilenameFilter;
import java.net.URI;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* DiscoMatcherTest
*
* @author <a href="mailto:[email protected]">Carlos Pedrinaci</a> (KMi - The Open University)
* @since 01/08/2013
*/
public class LogicConceptMatcherWSC08Test extends TestCase {
private static final Logger log = LoggerFactory.getLogger(LogicConceptMatcherWSC08Test.class);
private static final String WSC08_01_SERVICES = "/wsc08-dataset01/services/services.xml";
private static final String MEDIATYPE = "text/xml";
private LogicConceptMatcher matcher = new LogicConceptMatcher();
public static TestSetup suite() {
TestSetup setup = new TestSetup(new TestSuite(LogicConceptMatcherWSC08Test.class)) {
protected void setUp() throws Exception {
BasicConfigurator.configure();
// do your one-time setup here
// Clean the whole thing before testing
ManagerSingleton.getInstance().clearRegistry();
log.info("Importing WSC 2008 services");
String file = LogicConceptMatcherWSC08Test.class.getResource(WSC08_01_SERVICES).getFile();
log.debug("Using " + file);
File services = new File(file);
//List<Service> result = new WSCImporter().transform(new FileInputStream(services), null);
// Automatic plugin discovery
List<Service> result = Transformer.getInstance().transform(services, null, MEDIATYPE);
// Import all services
for(Service s : result){
URI uri = ManagerSingleton.getInstance().importService(s);
Assert.assertNotNull(uri);
log.info("Service added: " + uri.toASCIIString());
}
/*
URI testFolder = LogicConceptMatcherWSC08Test.class.getResource(WSC08_01_SERVICES).toURI();
log.debug("Test folder {}", testFolder);
FilenameFilter ttlFilter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return (name.endsWith(".owl") || name.endsWith(".owls"));
}
};
File dir = new File(testFolder);
File[] msmTtlTcFiles = dir.listFiles(ttlFilter);
log.debug("Valid services detected: {}", msmTtlTcFiles);
FileInputStream in;
// Upload every document and obtain their URLs
for (File ttlFile : msmTtlTcFiles) {
log.debug("Importing {}", ttlFile.getAbsolutePath());
in = new FileInputStream(ttlFile);
ManagerSingleton.getInstance().importService(in, OWLS_MEDIATYPE);
} */
}
protected void tearDown() throws Exception {
// do your one-time tear down here!
}
};
return setup;
}
public void testMatch() throws Exception {
URI origin = URI.create("http://127.0.0.1/ontology/taxonomy.owl#con1981452129");
URI destination = URI.create("http://127.0.0.1/ontology/taxonomy.owl#con596084519");
// Obtain matches
Stopwatch stopwatch = new Stopwatch().start();
MatchResult match = matcher.match(origin, destination);
stopwatch.stop();
log.info("Obtained match in {} \n {}", stopwatch, match);
Assert.assertEquals(DiscoMatchType.Plugin, match.getMatchType());
}
/*
@Test
public void testMatchBySets() throws Exception {
Set<URI> origins = new HashSet<URI>();
origins.add(URI.create("http://127.0.0.1/ontology/SUMO.owl#EuroDollar"));
origins.add(URI.create("http://127.0.0.1/ontology/SUMO.owl#Abstract"));
origins.add(URI.create("http://127.0.0.1/ontology/SUMO.owl#TherapeuticProcess"));
Set<URI> destinations = new HashSet<URI>();
destinations.add(URI.create("http://127.0.0.1/ontology/SUMO.owl#Quantity"));
destinations.add(URI.create("http://127.0.0.1/ontology/SUMO.owl#IntentionalProcess"));
destinations.add(URI.create("http://127.0.0.1/ontology/SUMO.owl#Entity"));
// Obtain cross-matches
Stopwatch stopwatch = new Stopwatch().start();
Table<URI, URI, MatchResult> matches =
matcher.match(origins, destinations);
stopwatch.stop();
log.info("Obtained all cross matches ({}) in {} \n {}", matches.size(), stopwatch, matches);
Assert.assertEquals(matches.size(), 4);
stopwatch.reset();
}
@Test
public void testListMatchesOfType() throws Exception {
// Obtain only exact
Stopwatch stopwatch = new Stopwatch().start();
Map<URI, MatchResult> matches =
matcher.listMatchesOfType(URI.create("http://127.0.0.1/ontology/SUMO.owl#EuroDollar"), DiscoMatchType.Exact);
stopwatch.stop();
log.info("Obtained all exact matches ({}) in {} \n", matches.size(), stopwatch, matches);
Assert.assertEquals(matches.size(), 1);
stopwatch.reset();
// Obtain only plugin
stopwatch.start();
matches = matcher.listMatchesOfType(URI.create("http://127.0.0.1/ontology/SUMO.owl#EuroDollar"), DiscoMatchType.Plugin);
stopwatch.stop();
log.info("Obtained all plugin matches ({}) in {} \n", matches.size(), stopwatch, matches);
Assert.assertEquals(matches.size(), 5);
stopwatch.reset();
// Obtain only plugin
stopwatch.start();
matches = matcher.listMatchesOfType(URI.create("http://127.0.0.1/ontology/SUMO.owl#EuroDollar"), DiscoMatchType.Subsume);
stopwatch.stop();
log.info("Obtained all plugin matches ({}) in {} \n", matches.size(), stopwatch, matches);
Assert.assertEquals(matches.size(), 0);
stopwatch.reset();
}
@Test
public void testListMatchesAtLeastOfType() throws Exception {
// Obtain at least exact
Stopwatch stopwatch = new Stopwatch().start();
Map<URI, MatchResult> matches =
matcher.listMatchesAtLeastOfType(URI.create("http://127.0.0.1/ontology/SUMO.owl#EuroDollar"), DiscoMatchType.Exact);
stopwatch.stop();
log.info("Obtained at least Exact matches ({}) in {} \n", matches.size(), stopwatch, matches);
Assert.assertEquals(matches.size(), 1);
stopwatch.reset();
// Obtain at least plugin
stopwatch.start();
matches = matcher.listMatchesAtLeastOfType(URI.create("http://127.0.0.1/ontology/SUMO.owl#EuroDollar"), DiscoMatchType.Plugin);
stopwatch.stop();
log.info("Obtained at least Plugin matches ({}) in {} \n", matches.size(), stopwatch, matches);
Assert.assertEquals(matches.size(), 6);
stopwatch.reset();
// Obtain at least subsumes
stopwatch.start();
matches = matcher.listMatchesAtLeastOfType(URI.create("http://127.0.0.1/ontology/SUMO.owl#EuroDollar"), DiscoMatchType.Subsume);
stopwatch.stop();
log.info("Obtained at least Subsumes matches ({}) in {} \n", matches.size(), stopwatch, matches);
Assert.assertEquals(matches.size(), 6);
stopwatch.reset();
// Obtain at least fail
stopwatch.start();
matches = matcher.listMatchesAtLeastOfType(URI.create("http://127.0.0.1/ontology/SUMO.owl#EuroDollar"), DiscoMatchType.Fail);
stopwatch.stop();
log.info("Obtained at least Fail matches ({}) in {} \n", matches.size(), stopwatch, matches);
Assert.assertEquals(matches.size(), 6);
stopwatch.reset();
}
@Test
public void testListMatchesAtMostOfType() throws Exception {
// Obtain at least exact
Stopwatch stopwatch = new Stopwatch().start();
Map<URI, MatchResult> matches =
matcher.listMatchesAtMostOfType(URI.create("http://127.0.0.1/ontology/SUMO.owl#EuroDollar"), DiscoMatchType.Exact);
stopwatch.stop();
log.info("Obtained at most Exact matches ({}) in {} \n", matches.size(), stopwatch, matches);
Assert.assertEquals(matches.size(), 6);
stopwatch.reset();
// Obtain at least plugin
stopwatch.start();
matches = matcher.listMatchesAtMostOfType(URI.create("http://127.0.0.1/ontology/SUMO.owl#EuroDollar"), DiscoMatchType.Plugin);
stopwatch.stop();
log.info("Obtained at most Plugin matches ({}) in {} \n", matches.size(), stopwatch, matches);
Assert.assertEquals(matches.size(), 5);
stopwatch.reset();
// Obtain at least subsumes
stopwatch.start();
matches = matcher.listMatchesAtMostOfType(URI.create("http://127.0.0.1/ontology/SUMO.owl#EuroDollar"), DiscoMatchType.Subsume);
stopwatch.stop();
log.info("Obtained at most Subsumes matches ({}) in {} \n", matches.size(), stopwatch, matches);
Assert.assertEquals(matches.size(), 0);
stopwatch.reset();
// Obtain at least fail
stopwatch.start();
matches = matcher.listMatchesAtMostOfType(URI.create("http://127.0.0.1/ontology/SUMO.owl#EuroDollar"), DiscoMatchType.Fail);
stopwatch.stop();
log.info("Obtained at most Fail matches ({}) in {} \n", matches.size(), stopwatch, matches);
Assert.assertEquals(matches.size(), 0);
stopwatch.reset();
}
@Test
public void testListMatchesWithinRange() throws Exception {
// Obtain all matches
Stopwatch stopwatch = new Stopwatch().start();
Map<URI, MatchResult> matches =
matcher.listMatchesWithinRange(URI.create("http://127.0.0.1/ontology/SUMO.owl#EuroDollar"), DiscoMatchType.Fail, DiscoMatchType.Exact);
stopwatch.stop();
log.info("Obtained all matches ({}) in {} \n", matches.size(), stopwatch, matches);
Assert.assertEquals(matches.size(), 6);
stopwatch.reset();
// Obtain only exact
stopwatch.start();
matches = matcher.listMatchesWithinRange(URI.create("http://127.0.0.1/ontology/SUMO.owl#EuroDollar"), DiscoMatchType.Exact, DiscoMatchType.Exact);
stopwatch.stop();
log.info("Obtained exact matches ({}) in {} \n", matches.size(), stopwatch, matches);
Assert.assertEquals(matches.size(), 1);
stopwatch.reset();
// Obtain from Plugin up
stopwatch.start();
matches = matcher.listMatchesWithinRange(URI.create("http://127.0.0.1/ontology/SUMO.owl#EuroDollar"), DiscoMatchType.Plugin, DiscoMatchType.Exact);
stopwatch.stop();
log.info("Obtained matches >= Plugin ({}) in {} \n", matches.size(), stopwatch, matches);
Assert.assertEquals(matches.size(), 6);
stopwatch.reset();
// Obtain Plugin and subsumes
stopwatch.start();
matches = matcher.listMatchesWithinRange(URI.create("http://127.0.0.1/ontology/SUMO.owl#EuroDollar"), DiscoMatchType.Subsume, DiscoMatchType.Plugin);
stopwatch.stop();
log.info("Obtained Subsumes >= matches >= Plugin ({}) in {} \n", matches.size(), stopwatch, matches);
Assert.assertEquals(matches.size(), 5);
stopwatch.reset();
// Invert limits
stopwatch.start();
matches = matcher.listMatchesWithinRange(URI.create("http://127.0.0.1/ontology/SUMO.owl#EuroDollar"), DiscoMatchType.Exact, DiscoMatchType.Plugin);
stopwatch.stop();
log.info("Obtained Exact >= matches >= Plugin ({}) in {} \n", matches.size(), stopwatch, matches);
Assert.assertEquals(matches.size(), 0);
stopwatch.reset();
}*/
}
| More tests added to LogicConceptMatcherWSC08Test
| iserve-discovery-disco/src/test/java/uk/ac/open/kmi/iserve/discovery/disco/impl/LogicConceptMatcherWSC08Test.java | More tests added to LogicConceptMatcherWSC08Test | <ide><path>serve-discovery-disco/src/test/java/uk/ac/open/kmi/iserve/discovery/disco/impl/LogicConceptMatcherWSC08Test.java
<ide> return setup;
<ide> }
<ide>
<del> public void testMatch() throws Exception {
<del>
<del> URI origin = URI.create("http://127.0.0.1/ontology/taxonomy.owl#con1981452129");
<del> URI destination = URI.create("http://127.0.0.1/ontology/taxonomy.owl#con596084519");
<add> public void testDirectPluginMatch() throws Exception {
<add>
<add> URI origin = URI.create("http://127.0.0.1/ontology/taxonomy.owl#con1655991159");
<add> URI destination = URI.create("http://127.0.0.1/ontology/taxonomy.owl#con409488015");
<add>
<add> // Obtain matches
<add> Stopwatch stopwatch = new Stopwatch().start();
<add> MatchResult match = matcher.match(origin, destination);
<add> stopwatch.stop();
<add>
<add> log.info("Obtained match in {} \n {}", stopwatch, match);
<add> Assert.assertEquals(DiscoMatchType.Plugin, match.getMatchType());
<add> }
<add>
<add> public void testDirectSubsumeMatch() throws Exception {
<add>
<add> URI origin = URI.create("http://127.0.0.1/ontology/taxonomy.owl#con1655991159");
<add> URI destination = URI.create("http://127.0.0.1/ontology/taxonomy.owl#con409488015");
<add>
<add> // Obtain matches
<add> Stopwatch stopwatch = new Stopwatch().start();
<add> MatchResult match = matcher.match(destination, origin);
<add> stopwatch.stop();
<add>
<add> log.info("Obtained match in {} \n {}", stopwatch, match);
<add> Assert.assertEquals(DiscoMatchType.Subsume, match.getMatchType());
<add> }
<add>
<add> public void testIndirectPluginMatch() throws Exception {
<add>
<add> URI origin = URI.create("http://127.0.0.1/ontology/taxonomy.owl#con1901563774");
<add> URI destination = URI.create("http://127.0.0.1/ontology/taxonomy.owl#con241744282");
<ide>
<ide> // Obtain matches
<ide> Stopwatch stopwatch = new Stopwatch().start(); |
|
Java | bsd-3-clause | 8dfeb6d148f7201125bd2a2de2ae6c2a23c0dd72 | 0 | abryant/Plinth,abryant/Plinth,abryant/Plinth,abryant/Plinth | package eu.bryants.anthony.toylanguage.compiler.passes;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import nativelib.c.C;
import nativelib.llvm.LLVM;
import nativelib.llvm.LLVM.LLVMBasicBlockRef;
import nativelib.llvm.LLVM.LLVMBuilderRef;
import nativelib.llvm.LLVM.LLVMModuleRef;
import nativelib.llvm.LLVM.LLVMTypeRef;
import nativelib.llvm.LLVM.LLVMValueRef;
import com.sun.jna.Pointer;
import eu.bryants.anthony.toylanguage.ast.CompoundDefinition;
import eu.bryants.anthony.toylanguage.ast.expression.ArithmeticExpression;
import eu.bryants.anthony.toylanguage.ast.expression.ArrayAccessExpression;
import eu.bryants.anthony.toylanguage.ast.expression.ArrayCreationExpression;
import eu.bryants.anthony.toylanguage.ast.expression.BitwiseNotExpression;
import eu.bryants.anthony.toylanguage.ast.expression.BooleanLiteralExpression;
import eu.bryants.anthony.toylanguage.ast.expression.BooleanNotExpression;
import eu.bryants.anthony.toylanguage.ast.expression.BracketedExpression;
import eu.bryants.anthony.toylanguage.ast.expression.CastExpression;
import eu.bryants.anthony.toylanguage.ast.expression.ComparisonExpression;
import eu.bryants.anthony.toylanguage.ast.expression.ComparisonExpression.ComparisonOperator;
import eu.bryants.anthony.toylanguage.ast.expression.Expression;
import eu.bryants.anthony.toylanguage.ast.expression.FieldAccessExpression;
import eu.bryants.anthony.toylanguage.ast.expression.FloatingLiteralExpression;
import eu.bryants.anthony.toylanguage.ast.expression.FunctionCallExpression;
import eu.bryants.anthony.toylanguage.ast.expression.InlineIfExpression;
import eu.bryants.anthony.toylanguage.ast.expression.IntegerLiteralExpression;
import eu.bryants.anthony.toylanguage.ast.expression.LogicalExpression;
import eu.bryants.anthony.toylanguage.ast.expression.LogicalExpression.LogicalOperator;
import eu.bryants.anthony.toylanguage.ast.expression.MinusExpression;
import eu.bryants.anthony.toylanguage.ast.expression.NullLiteralExpression;
import eu.bryants.anthony.toylanguage.ast.expression.ShiftExpression;
import eu.bryants.anthony.toylanguage.ast.expression.ThisExpression;
import eu.bryants.anthony.toylanguage.ast.expression.TupleExpression;
import eu.bryants.anthony.toylanguage.ast.expression.TupleIndexExpression;
import eu.bryants.anthony.toylanguage.ast.expression.VariableExpression;
import eu.bryants.anthony.toylanguage.ast.member.ArrayLengthMember;
import eu.bryants.anthony.toylanguage.ast.member.Constructor;
import eu.bryants.anthony.toylanguage.ast.member.Field;
import eu.bryants.anthony.toylanguage.ast.member.Member;
import eu.bryants.anthony.toylanguage.ast.member.Method;
import eu.bryants.anthony.toylanguage.ast.metadata.GlobalVariable;
import eu.bryants.anthony.toylanguage.ast.metadata.MemberVariable;
import eu.bryants.anthony.toylanguage.ast.metadata.Variable;
import eu.bryants.anthony.toylanguage.ast.misc.ArrayElementAssignee;
import eu.bryants.anthony.toylanguage.ast.misc.Assignee;
import eu.bryants.anthony.toylanguage.ast.misc.BlankAssignee;
import eu.bryants.anthony.toylanguage.ast.misc.FieldAssignee;
import eu.bryants.anthony.toylanguage.ast.misc.Parameter;
import eu.bryants.anthony.toylanguage.ast.misc.VariableAssignee;
import eu.bryants.anthony.toylanguage.ast.statement.AssignStatement;
import eu.bryants.anthony.toylanguage.ast.statement.Block;
import eu.bryants.anthony.toylanguage.ast.statement.BreakStatement;
import eu.bryants.anthony.toylanguage.ast.statement.BreakableStatement;
import eu.bryants.anthony.toylanguage.ast.statement.ContinueStatement;
import eu.bryants.anthony.toylanguage.ast.statement.ExpressionStatement;
import eu.bryants.anthony.toylanguage.ast.statement.ForStatement;
import eu.bryants.anthony.toylanguage.ast.statement.IfStatement;
import eu.bryants.anthony.toylanguage.ast.statement.PrefixIncDecStatement;
import eu.bryants.anthony.toylanguage.ast.statement.ReturnStatement;
import eu.bryants.anthony.toylanguage.ast.statement.ShorthandAssignStatement;
import eu.bryants.anthony.toylanguage.ast.statement.Statement;
import eu.bryants.anthony.toylanguage.ast.statement.WhileStatement;
import eu.bryants.anthony.toylanguage.ast.type.ArrayType;
import eu.bryants.anthony.toylanguage.ast.type.FunctionType;
import eu.bryants.anthony.toylanguage.ast.type.NamedType;
import eu.bryants.anthony.toylanguage.ast.type.NullType;
import eu.bryants.anthony.toylanguage.ast.type.PrimitiveType;
import eu.bryants.anthony.toylanguage.ast.type.PrimitiveType.PrimitiveTypeType;
import eu.bryants.anthony.toylanguage.ast.type.TupleType;
import eu.bryants.anthony.toylanguage.ast.type.Type;
import eu.bryants.anthony.toylanguage.ast.type.VoidType;
/*
* Created on 5 Apr 2012
*/
/**
* @author Anthony Bryant
*/
public class CodeGenerator
{
private CompoundDefinition compoundDefinition;
private LLVMModuleRef module;
private LLVMBuilderRef builder;
private LLVMValueRef callocFunction;
private Map<GlobalVariable, LLVMValueRef> globalVariables = new HashMap<GlobalVariable, LLVMValueRef>();
public CodeGenerator(CompoundDefinition compoundDefinition)
{
this.compoundDefinition = compoundDefinition;
module = LLVM.LLVMModuleCreateWithName(compoundDefinition.getQualifiedName().toString());
builder = LLVM.LLVMCreateBuilder();
}
public void generate(String outputPath)
{
// add all of the global (static) variables
addGlobalVariables();
// add all of the LLVM functions, including constructors, methods, and normal functions
addFunctions();
addConstructorBodies(compoundDefinition);
addMethodBodies(compoundDefinition);
LLVM.LLVMWriteBitcodeToFile(module, outputPath);
}
private void addGlobalVariables()
{
for (Field field : compoundDefinition.getFields())
{
if (field.isStatic())
{
GlobalVariable globalVariable = field.getGlobalVariable();
LLVMValueRef value = LLVM.LLVMAddGlobal(module, findNativeType(field.getType()), globalVariable.getMangledName());
LLVM.LLVMSetInitializer(value, LLVM.LLVMConstNull(findNativeType(field.getType())));
globalVariables.put(globalVariable, value);
}
}
}
private LLVMValueRef getGlobal(GlobalVariable globalVariable)
{
LLVMValueRef value = globalVariables.get(globalVariable);
if (value != null)
{
return value;
}
// lazily initialise globals which do not yet exist
Type type = globalVariable.getType();
LLVMValueRef newValue = LLVM.LLVMAddGlobal(module, findNativeType(type), globalVariable.getMangledName());
LLVM.LLVMSetInitializer(newValue, LLVM.LLVMConstNull(findNativeType(type)));
globalVariables.put(globalVariable, newValue);
return newValue;
}
private void addFunctions()
{
// add calloc() as an external function
LLVMTypeRef callocReturnType = LLVM.LLVMPointerType(LLVM.LLVMInt8Type(), 0);
LLVMTypeRef[] callocParamTypes = new LLVMTypeRef[] {LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount())};
callocFunction = LLVM.LLVMAddFunction(module, "calloc", LLVM.LLVMFunctionType(callocReturnType, C.toNativePointerArray(callocParamTypes, false, true), callocParamTypes.length, false));
for (Constructor constructor : compoundDefinition.getConstructors())
{
getConstructorFunction(constructor);
}
for (Method method : compoundDefinition.getAllMethods())
{
getMethodFunction(method);
}
}
/**
* Gets the function definition for the specified Constructor. If necessary, it is added first.
* @param constructor - the Constructor to find the declaration of (or to declare)
* @return the function declaration for the specified Constructor
*/
private LLVMValueRef getConstructorFunction(Constructor constructor)
{
String mangledName = constructor.getMangledName();
LLVMValueRef existingFunc = LLVM.LLVMGetNamedFunction(module, mangledName);
if (existingFunc != null)
{
return existingFunc;
}
Parameter[] parameters = constructor.getParameters();
LLVMTypeRef[] types = new LLVMTypeRef[parameters.length];
for (int i = 0; i < types.length; i++)
{
types[i] = findNativeType(parameters[i].getType());
}
LLVMTypeRef resultType = findNativeType(new NamedType(false, compoundDefinition));
Pointer paramTypes = C.toNativePointerArray(types, false, true);
LLVMTypeRef functionType = LLVM.LLVMFunctionType(resultType, paramTypes, types.length, false);
LLVMValueRef llvmFunc = LLVM.LLVMAddFunction(module, mangledName, functionType);
LLVM.LLVMSetFunctionCallConv(llvmFunc, LLVM.LLVMCallConv.LLVMCCallConv);
int paramCount = LLVM.LLVMCountParams(llvmFunc);
if (paramCount != parameters.length)
{
throw new IllegalStateException("LLVM returned wrong number of parameters");
}
for (int i = 0; i < paramCount; i++)
{
LLVMValueRef parameter = LLVM.LLVMGetParam(llvmFunc, i);
LLVM.LLVMSetValueName(parameter, parameters[i].getName());
}
return llvmFunc;
}
/**
* Gets the function definition for the specified Method. If necessary, it is added first.
* @param method - the Method to find the declaration of (or to declare)
* @return the function declaration for the specified Method
*/
private LLVMValueRef getMethodFunction(Method method)
{
String mangledName = method.getMangledName();
LLVMValueRef existingFunc = LLVM.LLVMGetNamedFunction(module, mangledName);
if (existingFunc != null)
{
return existingFunc;
}
Parameter[] parameters = method.getParameters();
LLVMTypeRef[] types;
if (method.isStatic())
{
types = new LLVMTypeRef[parameters.length];
for (int i = 0; i < parameters.length; ++i)
{
types[i] = findNativeType(parameters[i].getType());
}
}
else
{
types = new LLVMTypeRef[1 + parameters.length];
// add the 'this' type to the function
types[0] = LLVM.LLVMPointerType(findNativeType(new NamedType(false, compoundDefinition)), 0);
for (int i = 0; i < parameters.length; i++)
{
types[i + 1] = findNativeType(parameters[i].getType());
}
}
LLVMTypeRef resultType = findNativeType(method.getReturnType());
Pointer paramTypes = C.toNativePointerArray(types, false, true);
LLVMTypeRef functionType = LLVM.LLVMFunctionType(resultType, paramTypes, types.length, false);
LLVMValueRef llvmFunc = LLVM.LLVMAddFunction(module, mangledName, functionType);
LLVM.LLVMSetFunctionCallConv(llvmFunc, LLVM.LLVMCallConv.LLVMCCallConv);
int paramCount = LLVM.LLVMCountParams(llvmFunc);
if (paramCount != types.length)
{
throw new IllegalStateException("LLVM returned wrong number of parameters");
}
if (method.isStatic())
{
for (int i = 0; i < paramCount; i++)
{
LLVMValueRef parameter = LLVM.LLVMGetParam(llvmFunc, i);
LLVM.LLVMSetValueName(parameter, parameters[i].getName());
}
}
else
{
LLVM.LLVMSetValueName(LLVM.LLVMGetParam(llvmFunc, 0), "this");
for (int i = 1; i < paramCount; i++)
{
LLVMValueRef parameter = LLVM.LLVMGetParam(llvmFunc, i);
LLVM.LLVMSetValueName(parameter, parameters[i - 1].getName());
}
}
// add the native function if the programmer specified one
if (method.getNativeName() != null)
{
addNativeFunction(method.getNativeName(), !(method.getReturnType() instanceof VoidType), functionType, llvmFunc);
}
return llvmFunc;
}
/**
* Adds a native function which calls the specified non-native function.
* This consists simply of a new function with the specified native name, which calls the non-native function and returns its result.
* @param nativeName - the native name to export
* @param hasReturnValue - true if this method returns a value, false otherwise
* @param functionType - the type of the non-native function
* @param nonNativeFunction - the non-native function to call
*/
private void addNativeFunction(String nativeName, boolean hasReturnValue, LLVMTypeRef functionType, LLVMValueRef nonNativeFunction)
{
LLVMValueRef nativeFunction = LLVM.LLVMAddFunction(module, nativeName, functionType);
LLVM.LLVMSetFunctionCallConv(nativeFunction, LLVM.LLVMCallConv.LLVMCCallConv);
int paramCount = LLVM.LLVMCountParams(nativeFunction);
LLVMValueRef[] arguments = new LLVMValueRef[paramCount];
for (int i = 0; i < paramCount; ++i)
{
arguments[i] = LLVM.LLVMGetParam(nativeFunction, i);
}
LLVMBasicBlockRef block = LLVM.LLVMAppendBasicBlock(nativeFunction, "entry");
LLVM.LLVMPositionBuilderAtEnd(builder, block);
LLVMValueRef result = LLVM.LLVMBuildCall(builder, nonNativeFunction, C.toNativePointerArray(arguments, false, true), arguments.length, "");
if (hasReturnValue)
{
LLVM.LLVMBuildRet(builder, result);
}
else
{
LLVM.LLVMBuildRetVoid(builder);
}
}
private LLVMTypeRef findNativeType(Type type)
{
if (type instanceof PrimitiveType)
{
LLVMTypeRef nonNullableType;
PrimitiveTypeType primitiveTypeType = ((PrimitiveType) type).getPrimitiveTypeType();
if (primitiveTypeType == PrimitiveTypeType.DOUBLE)
{
nonNullableType = LLVM.LLVMDoubleType();
}
else if (primitiveTypeType == PrimitiveTypeType.FLOAT)
{
nonNullableType = LLVM.LLVMFloatType();
}
else
{
nonNullableType = LLVM.LLVMIntType(primitiveTypeType.getBitCount());
}
if (type.isNullable())
{
// tuple the non-nullable type with a boolean, so that we can tell whether or not the value is null
LLVMTypeRef[] types = new LLVMTypeRef[] {LLVM.LLVMInt1Type(), nonNullableType};
return LLVM.LLVMStructType(C.toNativePointerArray(types, false, true), types.length, false);
}
return nonNullableType;
}
if (type instanceof ArrayType)
{
ArrayType arrayType = (ArrayType) type;
LLVMTypeRef baseType = findNativeType(arrayType.getBaseType());
LLVMTypeRef llvmArray = LLVM.LLVMArrayType(baseType, 0);
LLVMTypeRef[] structureTypes = new LLVMTypeRef[] {LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), llvmArray};
LLVMTypeRef llvmStructure = LLVM.LLVMStructType(C.toNativePointerArray(structureTypes, false, true), 2, false);
return LLVM.LLVMPointerType(llvmStructure, 0);
}
if (type instanceof TupleType)
{
TupleType tupleType = (TupleType) type;
Type[] subTypes = tupleType.getSubTypes();
LLVMTypeRef[] llvmSubTypes = new LLVMTypeRef[subTypes.length];
for (int i = 0; i < subTypes.length; i++)
{
llvmSubTypes[i] = findNativeType(subTypes[i]);
}
LLVMTypeRef nonNullableType = LLVM.LLVMStructType(C.toNativePointerArray(llvmSubTypes, false, true), llvmSubTypes.length, false);
if (tupleType.isNullable())
{
// tuple the non-nullable type with a boolean, so that we can tell whether or not the value is null
LLVMTypeRef[] types = new LLVMTypeRef[] {LLVM.LLVMInt1Type(), nonNullableType};
return LLVM.LLVMStructType(C.toNativePointerArray(types, false, true), types.length, false);
}
return nonNullableType;
}
if (type instanceof NamedType)
{
NamedType namedType = (NamedType) type;
CompoundDefinition compound = namedType.getResolvedDefinition();
Field[] fields = compound.getNonStaticFields();
LLVMTypeRef[] llvmSubTypes = new LLVMTypeRef[fields.length];
for (int i = 0; i < fields.length; i++)
{
llvmSubTypes[i] = findNativeType(fields[i].getType());
}
LLVMTypeRef nonNullableType = LLVM.LLVMStructType(C.toNativePointerArray(llvmSubTypes, false, true), llvmSubTypes.length, false);
if (namedType.isNullable())
{
// tuple the non-nullable type with a boolean, so that we can tell whether or not the value is null
LLVMTypeRef[] types = new LLVMTypeRef[] {LLVM.LLVMInt1Type(), nonNullableType};
return LLVM.LLVMStructType(C.toNativePointerArray(types, false, true), types.length, false);
}
return nonNullableType;
}
if (type instanceof NullType)
{
return LLVM.LLVMStructType(C.toNativePointerArray(new LLVMTypeRef[0], false, true), 0, false);
}
if (type instanceof VoidType)
{
return LLVM.LLVMVoidType();
}
throw new IllegalStateException("Unexpected Type: " + type);
}
private void addConstructorBodies(CompoundDefinition compoundDefinition)
{
for (Constructor constructor : compoundDefinition.getConstructors())
{
LLVMValueRef llvmFunction = getConstructorFunction(constructor);
LLVMBasicBlockRef block = LLVM.LLVMAppendBasicBlock(llvmFunction, "entry");
LLVM.LLVMPositionBuilderAtEnd(builder, block);
// create LLVMValueRefs for all of the variables, including paramters
Set<Variable> allVariables = Resolver.getAllNestedVariables(constructor.getBlock());
Map<Variable, LLVMValueRef> variables = new HashMap<Variable, LLVM.LLVMValueRef>();
for (Variable v : allVariables)
{
LLVMValueRef allocaInst = LLVM.LLVMBuildAlloca(builder, findNativeType(v.getType()), v.getName());
variables.put(v, allocaInst);
}
// store the parameter values to the LLVMValueRefs
for (Parameter p : constructor.getParameters())
{
LLVM.LLVMBuildStore(builder, LLVM.LLVMGetParam(llvmFunction, p.getIndex()), variables.get(p.getVariable()));
}
final LLVMValueRef thisValue = LLVM.LLVMBuildAlloca(builder, findNativeType(new NamedType(false, compoundDefinition)), "this");
buildStatement(constructor.getBlock(), VoidType.VOID_TYPE, llvmFunction, thisValue, variables, new HashMap<BreakableStatement, LLVM.LLVMBasicBlockRef>(), new HashMap<BreakableStatement, LLVM.LLVMBasicBlockRef>(), new Runnable()
{
@Override
public void run()
{
// this will be called whenever a return void is found
// so return the created object
LLVMValueRef result = LLVM.LLVMBuildLoad(builder, thisValue, "");
LLVM.LLVMBuildRet(builder, result);
}
});
if (!constructor.getBlock().stopsExecution())
{
LLVMValueRef result = LLVM.LLVMBuildLoad(builder, thisValue, "");
LLVM.LLVMBuildRet(builder, result);
}
}
}
private void addMethodBodies(CompoundDefinition compoundDefinition)
{
for (Method method : compoundDefinition.getAllMethods())
{
LLVMValueRef llvmFunction = getMethodFunction(method);
LLVMBasicBlockRef block = LLVM.LLVMAppendBasicBlock(llvmFunction, "entry");
LLVM.LLVMPositionBuilderAtEnd(builder, block);
// create LLVMValueRefs for all of the variables, including parameters
Set<Variable> allVariables = Resolver.getAllNestedVariables(method.getBlock());
Map<Variable, LLVMValueRef> variables = new HashMap<Variable, LLVM.LLVMValueRef>();
for (Variable v : allVariables)
{
LLVMValueRef allocaInst = LLVM.LLVMBuildAlloca(builder, findNativeType(v.getType()), v.getName());
variables.put(v, allocaInst);
}
// store the parameter values to the LLVMValueRefs
for (Parameter p : method.getParameters())
{
LLVM.LLVMBuildStore(builder, LLVM.LLVMGetParam(llvmFunction, p.getIndex() + (method.isStatic() ? 0 : 1)), variables.get(p.getVariable()));
}
LLVMValueRef thisValue = method.isStatic() ? null : LLVM.LLVMGetParam(llvmFunction, 0);
buildStatement(method.getBlock(), method.getReturnType(), llvmFunction, thisValue, variables, new HashMap<BreakableStatement, LLVM.LLVMBasicBlockRef>(), new HashMap<BreakableStatement, LLVM.LLVMBasicBlockRef>(), new Runnable()
{
@Override
public void run()
{
// this will be run whenever a return void is found
// so return void
LLVM.LLVMBuildRetVoid(builder);
}
});
// add a "ret void" if control reaches the end of the function
if (!method.getBlock().stopsExecution())
{
LLVM.LLVMBuildRetVoid(builder);
}
}
}
private void buildStatement(Statement statement, Type returnType, LLVMValueRef llvmFunction, LLVMValueRef thisValue, Map<Variable, LLVMValueRef> variables,
Map<BreakableStatement, LLVMBasicBlockRef> breakBlocks, Map<BreakableStatement, LLVMBasicBlockRef> continueBlocks, Runnable returnVoidCallback)
{
if (statement instanceof AssignStatement)
{
AssignStatement assignStatement = (AssignStatement) statement;
Assignee[] assignees = assignStatement.getAssignees();
LLVMValueRef[] llvmAssigneePointers = new LLVMValueRef[assignees.length];
for (int i = 0; i < assignees.length; i++)
{
if (assignees[i] instanceof VariableAssignee)
{
Variable resolvedVariable = ((VariableAssignee) assignees[i]).getResolvedVariable();
if (resolvedVariable instanceof MemberVariable)
{
Field field = ((MemberVariable) resolvedVariable).getField();
LLVMValueRef[] indices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false),
LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), field.getMemberIndex(), false)};
llvmAssigneePointers[i] = LLVM.LLVMBuildGEP(builder, thisValue, C.toNativePointerArray(indices, false, true), indices.length, "");
}
else if (resolvedVariable instanceof GlobalVariable)
{
llvmAssigneePointers[i] = getGlobal((GlobalVariable) resolvedVariable);
}
else
{
llvmAssigneePointers[i] = variables.get(((VariableAssignee) assignees[i]).getResolvedVariable());
}
}
else if (assignees[i] instanceof ArrayElementAssignee)
{
ArrayElementAssignee arrayElementAssignee = (ArrayElementAssignee) assignees[i];
LLVMValueRef array = buildExpression(arrayElementAssignee.getArrayExpression(), llvmFunction, thisValue, variables);
LLVMValueRef dimension = buildExpression(arrayElementAssignee.getDimensionExpression(), llvmFunction, thisValue, variables);
LLVMValueRef convertedDimension = convertType(dimension, arrayElementAssignee.getDimensionExpression().getType(), ArrayLengthMember.ARRAY_LENGTH_TYPE, llvmFunction);
LLVMValueRef[] indices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false),
LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 1, false),
convertedDimension};
llvmAssigneePointers[i] = LLVM.LLVMBuildGEP(builder, array, C.toNativePointerArray(indices, false, true), indices.length, "");
}
else if (assignees[i] instanceof FieldAssignee)
{
FieldAssignee fieldAssignee = (FieldAssignee) assignees[i];
FieldAccessExpression fieldAccessExpression = fieldAssignee.getFieldAccessExpression();
if (fieldAccessExpression.getResolvedMember() instanceof Field)
{
Field field = (Field) fieldAccessExpression.getResolvedMember();
if (field.isStatic())
{
llvmAssigneePointers[i] = getGlobal(field.getGlobalVariable());
}
else
{
LLVMValueRef expressionValue = buildExpression(fieldAccessExpression.getBaseExpression(), llvmFunction, thisValue, variables);
LLVMValueRef[] indices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false),
LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), field.getMemberIndex(), false)};
llvmAssigneePointers[i] = LLVM.LLVMBuildGEP(builder, expressionValue, C.toNativePointerArray(indices, false, true), indices.length, "");
}
}
else
{
throw new IllegalArgumentException("Unknown member assigned to in a FieldAssignee: " + fieldAccessExpression.getResolvedMember());
}
}
else if (assignees[i] instanceof BlankAssignee)
{
// this assignee doesn't actually get assigned to
llvmAssigneePointers[i] = null;
}
else
{
throw new IllegalStateException("Unknown Assignee type: " + assignees[i]);
}
}
if (assignStatement.getExpression() != null)
{
LLVMValueRef value = buildExpression(assignStatement.getExpression(), llvmFunction, thisValue, variables);
if (llvmAssigneePointers.length == 1)
{
if (llvmAssigneePointers[0] != null)
{
LLVMValueRef convertedValue = convertType(value, assignStatement.getExpression().getType(), assignees[0].getResolvedType(), llvmFunction);
Type type = assignees[0].getResolvedType();
if (type instanceof NamedType) // TODO: when this does not cause a warning, add it: && ((NamedType) type).getResolvedDefinition() instanceof CompoundDefinition)
{
// for compound types, we need to load from the result of the expression and store a copy in the new pointer
convertedValue = LLVM.LLVMBuildLoad(builder, convertedValue, "");
}
LLVM.LLVMBuildStore(builder, convertedValue, llvmAssigneePointers[0]);
}
}
else
{
Type[] expressionSubTypes = ((TupleType) assignStatement.getExpression().getType()).getSubTypes();
for (int i = 0; i < llvmAssigneePointers.length; i++)
{
if (llvmAssigneePointers[i] != null)
{
LLVMValueRef extracted = LLVM.LLVMBuildExtractValue(builder, value, i, "");
LLVMValueRef convertedValue = convertType(extracted, expressionSubTypes[i], assignees[i].getResolvedType(), llvmFunction);
// since we are extracting from a tuple here, we do not need to treat compound types differently
LLVM.LLVMBuildStore(builder, convertedValue, llvmAssigneePointers[i]);
}
}
}
}
}
else if (statement instanceof Block)
{
for (Statement s : ((Block) statement).getStatements())
{
buildStatement(s, returnType, llvmFunction, thisValue, variables, breakBlocks, continueBlocks, returnVoidCallback);
}
}
else if (statement instanceof BreakStatement)
{
LLVMBasicBlockRef block = breakBlocks.get(((BreakStatement) statement).getResolvedBreakable());
if (block == null)
{
throw new IllegalStateException("Break statement leads to a null block during code generation: " + statement);
}
LLVM.LLVMBuildBr(builder, block);
}
else if (statement instanceof ContinueStatement)
{
LLVMBasicBlockRef block = continueBlocks.get(((ContinueStatement) statement).getResolvedBreakable());
if (block == null)
{
throw new IllegalStateException("Continue statement leads to a null block during code generation: " + statement);
}
LLVM.LLVMBuildBr(builder, block);
}
else if (statement instanceof ExpressionStatement)
{
buildExpression(((ExpressionStatement) statement).getExpression(), llvmFunction, thisValue, variables);
}
else if (statement instanceof ForStatement)
{
ForStatement forStatement = (ForStatement) statement;
Statement init = forStatement.getInitStatement();
if (init != null)
{
buildStatement(init, returnType, llvmFunction, thisValue, variables, breakBlocks, continueBlocks, returnVoidCallback);
}
Expression conditional = forStatement.getConditional();
Statement update = forStatement.getUpdateStatement();
LLVMBasicBlockRef loopCheck = conditional == null ? null : LLVM.LLVMAppendBasicBlock(llvmFunction, "forLoopCheck");
LLVMBasicBlockRef loopBody = LLVM.LLVMAppendBasicBlock(llvmFunction, "forLoopBody");
LLVMBasicBlockRef loopUpdate = update == null ? null : LLVM.LLVMAppendBasicBlock(llvmFunction, "forLoopUpdate");
// only generate a continuation block if there is a way to get out of the loop
LLVMBasicBlockRef continuationBlock = forStatement.stopsExecution() ? null : LLVM.LLVMAppendBasicBlock(llvmFunction, "afterForLoop");
if (conditional == null)
{
LLVM.LLVMBuildBr(builder, loopBody);
}
else
{
LLVM.LLVMBuildBr(builder, loopCheck);
LLVM.LLVMPositionBuilderAtEnd(builder, loopCheck);
LLVMValueRef conditionResult = buildExpression(conditional, llvmFunction, thisValue, variables);
LLVM.LLVMBuildCondBr(builder, conditionResult, loopBody, continuationBlock);
}
LLVM.LLVMPositionBuilderAtEnd(builder, loopBody);
if (continuationBlock != null)
{
breakBlocks.put(forStatement, continuationBlock);
}
continueBlocks.put(forStatement, loopUpdate == null ? (loopCheck == null ? loopBody : loopCheck) : loopUpdate);
buildStatement(forStatement.getBlock(), returnType, llvmFunction, thisValue, variables, breakBlocks, continueBlocks, returnVoidCallback);
if (!forStatement.getBlock().stopsExecution())
{
LLVM.LLVMBuildBr(builder, loopUpdate == null ? (loopCheck == null ? loopBody : loopCheck) : loopUpdate);
}
if (update != null)
{
LLVM.LLVMPositionBuilderAtEnd(builder, loopUpdate);
buildStatement(update, returnType, llvmFunction, thisValue, variables, breakBlocks, continueBlocks, returnVoidCallback);
if (update.stopsExecution())
{
throw new IllegalStateException("For loop update stops execution before the branch to the loop check: " + update);
}
LLVM.LLVMBuildBr(builder, loopCheck == null ? loopBody : loopCheck);
}
if (continuationBlock != null)
{
LLVM.LLVMPositionBuilderAtEnd(builder, continuationBlock);
}
}
else if (statement instanceof IfStatement)
{
IfStatement ifStatement = (IfStatement) statement;
LLVMValueRef conditional = buildExpression(ifStatement.getExpression(), llvmFunction, thisValue, variables);
LLVMBasicBlockRef thenClause = LLVM.LLVMAppendBasicBlock(llvmFunction, "then");
LLVMBasicBlockRef elseClause = null;
if (ifStatement.getElseClause() != null)
{
elseClause = LLVM.LLVMAppendBasicBlock(llvmFunction, "else");
}
LLVMBasicBlockRef continuation = null;
if (!ifStatement.stopsExecution())
{
continuation = LLVM.LLVMAppendBasicBlock(llvmFunction, "continuation");
}
// build the branch instruction
if (elseClause == null)
{
// if we have no else clause, then a continuation must have been created, since the if statement cannot stop execution
LLVM.LLVMBuildCondBr(builder, conditional, thenClause, continuation);
}
else
{
LLVM.LLVMBuildCondBr(builder, conditional, thenClause, elseClause);
// build the else clause
LLVM.LLVMPositionBuilderAtEnd(builder, elseClause);
buildStatement(ifStatement.getElseClause(), returnType, llvmFunction, thisValue, variables, breakBlocks, continueBlocks, returnVoidCallback);
if (!ifStatement.getElseClause().stopsExecution())
{
LLVM.LLVMBuildBr(builder, continuation);
}
}
// build the then clause
LLVM.LLVMPositionBuilderAtEnd(builder, thenClause);
buildStatement(ifStatement.getThenClause(), returnType, llvmFunction, thisValue, variables, breakBlocks, continueBlocks, returnVoidCallback);
if (!ifStatement.getThenClause().stopsExecution())
{
LLVM.LLVMBuildBr(builder, continuation);
}
if (continuation != null)
{
LLVM.LLVMPositionBuilderAtEnd(builder, continuation);
}
}
else if (statement instanceof PrefixIncDecStatement)
{
PrefixIncDecStatement prefixIncDecStatement = (PrefixIncDecStatement) statement;
Assignee assignee = prefixIncDecStatement.getAssignee();
LLVMValueRef pointer;
if (assignee instanceof VariableAssignee)
{
pointer = variables.get(((VariableAssignee) assignee).getResolvedVariable());
}
else if (assignee instanceof ArrayElementAssignee)
{
ArrayElementAssignee arrayElementAssignee = (ArrayElementAssignee) assignee;
LLVMValueRef array = buildExpression(arrayElementAssignee.getArrayExpression(), llvmFunction, thisValue, variables);
LLVMValueRef dimension = buildExpression(arrayElementAssignee.getDimensionExpression(), llvmFunction, thisValue, variables);
LLVMValueRef convertedDimension = convertType(dimension, arrayElementAssignee.getDimensionExpression().getType(), ArrayLengthMember.ARRAY_LENGTH_TYPE, llvmFunction);
LLVMValueRef[] indices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false),
LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 1, false),
convertedDimension};
pointer = LLVM.LLVMBuildGEP(builder, array, C.toNativePointerArray(indices, false, true), indices.length, "");
}
else
{
// ignore blank assignees, they shouldn't be able to get through variable resolution
throw new IllegalStateException("Unknown Assignee type: " + assignee);
}
LLVMValueRef loaded = LLVM.LLVMBuildLoad(builder, pointer, "");
PrimitiveType type = (PrimitiveType) assignee.getResolvedType();
LLVMValueRef result;
if (type.getPrimitiveTypeType().isFloating())
{
LLVMValueRef one = LLVM.LLVMConstReal(findNativeType(type), 1);
if (prefixIncDecStatement.isIncrement())
{
result = LLVM.LLVMBuildFAdd(builder, loaded, one, "");
}
else
{
result = LLVM.LLVMBuildFSub(builder, loaded, one, "");
}
}
else
{
LLVMValueRef one = LLVM.LLVMConstInt(findNativeType(type), 1, false);
if (prefixIncDecStatement.isIncrement())
{
result = LLVM.LLVMBuildAdd(builder, loaded, one, "");
}
else
{
result = LLVM.LLVMBuildSub(builder, loaded, one, "");
}
}
LLVM.LLVMBuildStore(builder, result, pointer);
}
else if (statement instanceof ReturnStatement)
{
Expression returnedExpression = ((ReturnStatement) statement).getExpression();
if (returnedExpression == null)
{
returnVoidCallback.run();
}
else
{
LLVMValueRef value = buildExpression(returnedExpression, llvmFunction, thisValue, variables);
LLVMValueRef convertedValue = convertType(value, returnedExpression.getType(), returnType, llvmFunction);
if (returnType instanceof NamedType) // TODO: when this does not cause a warning, add it: && ((NamedType) returnType).getResolvedDefinition() instanceof CompoundDefinition)
{
// for compound types, we need to load from the result of the expression and return that value
convertedValue = LLVM.LLVMBuildLoad(builder, convertedValue, "");
}
LLVM.LLVMBuildRet(builder, convertedValue);
}
}
else if (statement instanceof ShorthandAssignStatement)
{
ShorthandAssignStatement shorthandAssignStatement = (ShorthandAssignStatement) statement;
Assignee[] assignees = shorthandAssignStatement.getAssignees();
LLVMValueRef[] llvmAssigneePointers = new LLVMValueRef[assignees.length];
for (int i = 0; i < assignees.length; ++i)
{
if (assignees[i] instanceof VariableAssignee)
{
Variable resolvedVariable = ((VariableAssignee) assignees[i]).getResolvedVariable();
if (resolvedVariable instanceof MemberVariable)
{
Field field = ((MemberVariable) resolvedVariable).getField();
LLVMValueRef[] indices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false),
LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), field.getMemberIndex(), false)};
llvmAssigneePointers[i] = LLVM.LLVMBuildGEP(builder, thisValue, C.toNativePointerArray(indices, false, true), indices.length, "");
}
else if (resolvedVariable instanceof GlobalVariable)
{
llvmAssigneePointers[i] = getGlobal((GlobalVariable) resolvedVariable);
}
else
{
llvmAssigneePointers[i] = variables.get(((VariableAssignee) assignees[i]).getResolvedVariable());
}
}
else if (assignees[i] instanceof ArrayElementAssignee)
{
ArrayElementAssignee arrayElementAssignee = (ArrayElementAssignee) assignees[i];
LLVMValueRef array = buildExpression(arrayElementAssignee.getArrayExpression(), llvmFunction, thisValue, variables);
LLVMValueRef dimension = buildExpression(arrayElementAssignee.getDimensionExpression(), llvmFunction, thisValue, variables);
LLVMValueRef convertedDimension = convertType(dimension, arrayElementAssignee.getDimensionExpression().getType(), ArrayLengthMember.ARRAY_LENGTH_TYPE, llvmFunction);
LLVMValueRef[] indices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false),
LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 1, false),
convertedDimension};
llvmAssigneePointers[i] = LLVM.LLVMBuildGEP(builder, array, C.toNativePointerArray(indices, false, true), indices.length, "");
}
else if (assignees[i] instanceof FieldAssignee)
{
FieldAssignee fieldAssignee = (FieldAssignee) assignees[i];
FieldAccessExpression fieldAccessExpression = fieldAssignee.getFieldAccessExpression();
if (fieldAccessExpression.getResolvedMember() instanceof Field)
{
Field field = (Field) fieldAccessExpression.getResolvedMember();
if (field.isStatic())
{
llvmAssigneePointers[i] = getGlobal(field.getGlobalVariable());
}
else
{
LLVMValueRef expressionValue = buildExpression(fieldAccessExpression.getBaseExpression(), llvmFunction, thisValue, variables);
LLVMValueRef[] indices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false),
LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), field.getMemberIndex(), false)};
llvmAssigneePointers[i] = LLVM.LLVMBuildGEP(builder, expressionValue, C.toNativePointerArray(indices, false, true), indices.length, "");
}
}
else
{
throw new IllegalArgumentException("Unknown member assigned to in a FieldAssignee: " + fieldAccessExpression.getResolvedMember());
}
}
else if (assignees[i] instanceof BlankAssignee)
{
// this assignee doesn't actually get assigned to
llvmAssigneePointers[i] = null;
}
else
{
throw new IllegalStateException("Unknown Assignee type: " + assignees[i]);
}
}
LLVMValueRef result = buildExpression(shorthandAssignStatement.getExpression(), llvmFunction, thisValue, variables);
Type resultType = shorthandAssignStatement.getExpression().getType();
LLVMValueRef[] resultValues = new LLVMValueRef[assignees.length];
Type[] resultValueTypes = new Type[assignees.length];
if (resultType instanceof TupleType && ((TupleType) resultType).getSubTypes().length == assignees.length)
{
Type[] subTypes = ((TupleType) resultType).getSubTypes();
for (int i = 0; i < assignees.length; ++i)
{
if (assignees[i] instanceof BlankAssignee)
{
continue;
}
resultValues[i] = LLVM.LLVMBuildExtractValue(builder, result, i, "");
resultValueTypes[i] = subTypes[i];
}
}
else
{
for (int i = 0; i < assignees.length; ++i)
{
resultValues[i] = result;
resultValueTypes[i] = resultType;
}
}
for (int i = 0; i < assignees.length; ++i)
{
if (llvmAssigneePointers[i] == null)
{
// this is a blank assignee, so don't try to do anything for it
continue;
}
LLVMValueRef leftValue = LLVM.LLVMBuildLoad(builder, llvmAssigneePointers[i], "");
LLVMValueRef rightValue = convertType(resultValues[i], resultValueTypes[i], assignees[i].getResolvedType(), llvmFunction);
PrimitiveTypeType primitiveType = ((PrimitiveType) assignees[i].getResolvedType()).getPrimitiveTypeType();
boolean floating = primitiveType.isFloating();
boolean signed = primitiveType.isSigned();
LLVMValueRef assigneeResult;
switch (shorthandAssignStatement.getOperator())
{
case AND:
assigneeResult = LLVM.LLVMBuildAnd(builder, leftValue, rightValue, "");
break;
case OR:
assigneeResult = LLVM.LLVMBuildOr(builder, leftValue, rightValue, "");
break;
case XOR:
assigneeResult = LLVM.LLVMBuildXor(builder, leftValue, rightValue, "");
break;
case ADD:
assigneeResult = floating ? LLVM.LLVMBuildFAdd(builder, leftValue, rightValue, "") : LLVM.LLVMBuildAdd(builder, leftValue, rightValue, "");
break;
case SUBTRACT:
assigneeResult = floating ? LLVM.LLVMBuildFSub(builder, leftValue, rightValue, "") : LLVM.LLVMBuildSub(builder, leftValue, rightValue, "");
break;
case MULTIPLY:
assigneeResult = floating ? LLVM.LLVMBuildFMul(builder, leftValue, rightValue, "") : LLVM.LLVMBuildMul(builder, leftValue, rightValue, "");
break;
case DIVIDE:
assigneeResult = floating ? LLVM.LLVMBuildFDiv(builder, leftValue, rightValue, "") : signed ? LLVM.LLVMBuildSDiv(builder, leftValue, rightValue, "") : LLVM.LLVMBuildUDiv(builder, leftValue, rightValue, "");
break;
case REMAINDER:
assigneeResult = floating ? LLVM.LLVMBuildFRem(builder, leftValue, rightValue, "") : signed ? LLVM.LLVMBuildSRem(builder, leftValue, rightValue, "") : LLVM.LLVMBuildURem(builder, leftValue, rightValue, "");
break;
case MODULO:
if (floating)
{
LLVMValueRef rem = LLVM.LLVMBuildFRem(builder, leftValue, rightValue, "");
LLVMValueRef add = LLVM.LLVMBuildFAdd(builder, rem, rightValue, "");
assigneeResult = LLVM.LLVMBuildFRem(builder, add, rightValue, "");
}
else if (signed)
{
LLVMValueRef rem = LLVM.LLVMBuildSRem(builder, leftValue, rightValue, "");
LLVMValueRef add = LLVM.LLVMBuildAdd(builder, rem, rightValue, "");
assigneeResult = LLVM.LLVMBuildSRem(builder, add, rightValue, "");
}
else
{
// unsigned modulo is the same as unsigned remainder
assigneeResult = LLVM.LLVMBuildURem(builder, leftValue, rightValue, "");
}
break;
case LEFT_SHIFT:
assigneeResult = LLVM.LLVMBuildShl(builder, leftValue, rightValue, "");
break;
case RIGHT_SHIFT:
assigneeResult = signed ? LLVM.LLVMBuildAShr(builder, leftValue, rightValue, "") : LLVM.LLVMBuildLShr(builder, leftValue, rightValue, "");
break;
default:
throw new IllegalStateException("Unknown shorthand assignment operator: " + shorthandAssignStatement.getOperator());
}
LLVM.LLVMBuildStore(builder, assigneeResult, llvmAssigneePointers[i]);
}
}
else if (statement instanceof WhileStatement)
{
WhileStatement whileStatement = (WhileStatement) statement;
LLVMBasicBlockRef loopCheck = LLVM.LLVMAppendBasicBlock(llvmFunction, "whileLoopCheck");
LLVM.LLVMBuildBr(builder, loopCheck);
LLVM.LLVMPositionBuilderAtEnd(builder, loopCheck);
LLVMValueRef conditional = buildExpression(whileStatement.getExpression(), llvmFunction, thisValue, variables);
LLVMBasicBlockRef loopBodyBlock = LLVM.LLVMAppendBasicBlock(llvmFunction, "whileLoopBody");
LLVMBasicBlockRef afterLoopBlock = LLVM.LLVMAppendBasicBlock(llvmFunction, "afterWhileLoop");
LLVM.LLVMBuildCondBr(builder, conditional, loopBodyBlock, afterLoopBlock);
LLVM.LLVMPositionBuilderAtEnd(builder, loopBodyBlock);
// add the while statement's afterLoop block to the breakBlocks map before it's statement is built
breakBlocks.put(whileStatement, afterLoopBlock);
continueBlocks.put(whileStatement, loopCheck);
buildStatement(whileStatement.getStatement(), returnType, llvmFunction, thisValue, variables, breakBlocks, continueBlocks, returnVoidCallback);
if (!whileStatement.getStatement().stopsExecution())
{
LLVM.LLVMBuildBr(builder, loopCheck);
}
LLVM.LLVMPositionBuilderAtEnd(builder, afterLoopBlock);
}
}
private LLVMValueRef convertType(LLVMValueRef value, Type from, Type to, LLVMValueRef llvmFunction)
{
if (from.isEquivalent(to))
{
return value;
}
if (from instanceof PrimitiveType && to instanceof PrimitiveType)
{
return convertPrimitiveType(value, (PrimitiveType) from, (PrimitiveType) to);
}
if (from instanceof ArrayType && to instanceof ArrayType)
{
// array casts are illegal unless from and to types are the same, so they must have the same type
// nullability will be checked by the type checker, but has no effect on the native type, so we do not need to do anything special here
// if from and to are nullable and value is null, then the value we are returning here is undefined
// TODO: if from and to are nullable and value is null, throw an exception here instead of having undefined behaviour
return value;
}
if (from instanceof NamedType && to instanceof NamedType) // TODO: when it doesn't cause a warning, add: &&
//((NamedType) from).getResolvedDefinition() instanceof CompoundDefinition &&
//((NamedType) to).getResolvedDefinition() instanceof CompoundDefinition)
{
// compound type casts are illegal unless from and to types are the same, so they must have the same type
LLVMValueRef loadedValue = LLVM.LLVMBuildLoad(builder, value, "");
LLVMValueRef isNotNullValue = null;
LLVMValueRef namedValue = loadedValue;
if (from.isNullable())
{
isNotNullValue = LLVM.LLVMBuildExtractValue(builder, loadedValue, 0, "");
namedValue = LLVM.LLVMBuildExtractValue(builder, loadedValue, 1, "");
}
LLVMValueRef result;
if (to.isNullable())
{
result = LLVM.LLVMGetUndef(findNativeType(to));
if (from.isNullable())
{
result = LLVM.LLVMBuildInsertValue(builder, result, isNotNullValue, 0, "");
}
else
{
// set the flag to one to indicate that this value is not null
result = LLVM.LLVMBuildInsertValue(builder, result, LLVM.LLVMConstInt(LLVM.LLVMInt1Type(), 1, false), 0, "");
}
result = LLVM.LLVMBuildInsertValue(builder, result, namedValue, 1, "");
}
else
{
// return the primitive value directly, since the to type is not nullable
// if from is nullable and value is null, then the value we are returning here is undefined
// TODO: if from is nullable and value is null, throw an exception here instead of having undefined behaviour
result = namedValue;
}
// for compound types, we need to return a pointer to the value
// so build an alloca in the entry block
LLVMBasicBlockRef currentBlock = LLVM.LLVMGetInsertBlock(builder);
LLVM.LLVMPositionBuilderBefore(builder, LLVM.LLVMGetFirstInstruction(LLVM.LLVMGetEntryBasicBlock(llvmFunction)));
LLVMValueRef alloca = LLVM.LLVMBuildAlloca(builder, findNativeType(to), "");
LLVM.LLVMPositionBuilderAtEnd(builder, currentBlock);
LLVM.LLVMBuildStore(builder, result, alloca);
return alloca;
}
if (from instanceof TupleType && !(to instanceof TupleType))
{
TupleType fromTuple = (TupleType) from;
if (fromTuple.getSubTypes().length != 1)
{
throw new IllegalArgumentException("Cannot convert from a " + from + " to a " + to);
}
if (from.isNullable())
{
// extract the value of the tuple from the nullable structure
// if from is nullable and value is null, then the value we are using here is undefined
// TODO: if from is nullable and value is null, throw an exception here instead of having undefined behaviour
value = LLVM.LLVMBuildExtractValue(builder, value, 1, "");
}
return LLVM.LLVMBuildExtractValue(builder, value, 0, "");
}
if (!(from instanceof TupleType) && to instanceof TupleType)
{
TupleType toTuple = (TupleType) to;
if (toTuple.getSubTypes().length != 1)
{
throw new IllegalArgumentException("Cannot convert from a " + from + " to a " + to);
}
LLVMValueRef tupledValue = LLVM.LLVMGetUndef(findNativeType(new TupleType(false, toTuple.getSubTypes(), null)));
tupledValue = LLVM.LLVMBuildInsertValue(builder, tupledValue, value, 0, "");
if (to.isNullable())
{
LLVMValueRef result = LLVM.LLVMGetUndef(findNativeType(to));
result = LLVM.LLVMBuildInsertValue(builder, result, LLVM.LLVMConstInt(LLVM.LLVMInt1Type(), 1, false), 0, "");
return LLVM.LLVMBuildInsertValue(builder, result, tupledValue, 1, "");
}
return tupledValue;
}
if (from instanceof TupleType && to instanceof TupleType)
{
TupleType fromTuple = (TupleType) from;
TupleType toTuple = (TupleType) to;
if (fromTuple.isEquivalent(toTuple))
{
return value;
}
Type[] fromSubTypes = fromTuple.getSubTypes();
Type[] toSubTypes = toTuple.getSubTypes();
if (fromSubTypes.length != toSubTypes.length)
{
throw new IllegalArgumentException("Cannot convert from a " + from + " to a " + to);
}
boolean subTypesEquivalent = true;
for (int i = 0; i < fromSubTypes.length; ++i)
{
if (!fromSubTypes[i].isEquivalent(toSubTypes[i]))
{
subTypesEquivalent = false;
break;
}
}
if (subTypesEquivalent)
{
// just convert the nullability
if (from.isNullable() && !to.isNullable())
{
// extract the value of the tuple from the nullable structure
// if from is nullable and value is null, then the value we are using here is undefined
// TODO: if from is nullable and value is null, throw an exception here instead of having undefined behaviour
return LLVM.LLVMBuildExtractValue(builder, value, 1, "");
}
if (!from.isNullable() && to.isNullable())
{
LLVMValueRef result = LLVM.LLVMGetUndef(findNativeType(to));
// set the flag to one to indicate that this value is not null
result = LLVM.LLVMBuildInsertValue(builder, result, LLVM.LLVMConstInt(LLVM.LLVMInt1Type(), 1, false), 0, "");
return LLVM.LLVMBuildInsertValue(builder, result, value, 1, "");
}
throw new IllegalArgumentException("Unable to convert from a " + from + " to a " + to + " - their sub types and nullability are equivalent, but the types themselves are not");
}
LLVMValueRef isNotNullValue = null;
LLVMValueRef tupleValue = value;
if (from.isNullable())
{
isNotNullValue = LLVM.LLVMBuildExtractValue(builder, value, 0, "");
tupleValue = LLVM.LLVMBuildExtractValue(builder, value, 1, "");
}
LLVMValueRef currentValue = LLVM.LLVMGetUndef(findNativeType(toTuple));
for (int i = 0; i < fromTuple.getSubTypes().length; i++)
{
LLVMValueRef current = LLVM.LLVMBuildExtractValue(builder, tupleValue, i, "");
LLVMValueRef converted = convertType(current, fromSubTypes[i], toSubTypes[i], llvmFunction);
currentValue = LLVM.LLVMBuildInsertValue(builder, currentValue, converted, i, "");
}
if (to.isNullable())
{
LLVMValueRef result = LLVM.LLVMGetUndef(findNativeType(to));
if (from.isNullable())
{
result = LLVM.LLVMBuildInsertValue(builder, result, isNotNullValue, 0, "");
}
else
{
// set the flag to one to indicate that this value is not null
result = LLVM.LLVMBuildInsertValue(builder, result, LLVM.LLVMConstInt(LLVM.LLVMInt1Type(), 1, false), 0, "");
}
return LLVM.LLVMBuildInsertValue(builder, result, currentValue, 1, "");
}
// return the primitive value directly, since the to type is not nullable
// if from is nullable and value is null, then the value we are using here is undefined
// TODO: if from is nullable and value is null, throw an exception here instead of having undefined behaviour
return currentValue;
}
throw new IllegalArgumentException("Unknown type conversion, from '" + from + "' to '" + to + "'");
}
private LLVMValueRef convertPrimitiveType(LLVMValueRef value, PrimitiveType from, PrimitiveType to)
{
PrimitiveTypeType fromType = from.getPrimitiveTypeType();
PrimitiveTypeType toType = to.getPrimitiveTypeType();
if (fromType == toType && from.isNullable() == to.isNullable())
{
return value;
}
LLVMValueRef isNotNullValue = null;
LLVMValueRef primitiveValue = value;
if (from.isNullable())
{
isNotNullValue = LLVM.LLVMBuildExtractValue(builder, value, 0, "");
primitiveValue = LLVM.LLVMBuildExtractValue(builder, value, 1, "");
}
// perform the conversion
LLVMTypeRef toNativeType = findNativeType(new PrimitiveType(false, toType, null));
if (fromType == toType)
{
// do not alter primitiveValue, we only need to change the nullability
}
else if (fromType.isFloating() && toType.isFloating())
{
primitiveValue = LLVM.LLVMBuildFPCast(builder, primitiveValue, toNativeType, "");
}
else if (fromType.isFloating() && !toType.isFloating())
{
if (toType.isSigned())
{
primitiveValue = LLVM.LLVMBuildFPToSI(builder, primitiveValue, toNativeType, "");
}
else
{
primitiveValue = LLVM.LLVMBuildFPToUI(builder, primitiveValue, toNativeType, "");
}
}
else if (!fromType.isFloating() && toType.isFloating())
{
if (fromType.isSigned())
{
primitiveValue = LLVM.LLVMBuildSIToFP(builder, primitiveValue, toNativeType, "");
}
else
{
primitiveValue = LLVM.LLVMBuildUIToFP(builder, primitiveValue, toNativeType, "");
}
}
// both integer types, so perform a sign-extend, zero-extend, or truncation
else if (fromType.getBitCount() > toType.getBitCount())
{
primitiveValue = LLVM.LLVMBuildTrunc(builder, primitiveValue, toNativeType, "");
}
else if (fromType.getBitCount() == toType.getBitCount() && fromType.isSigned() != toType.isSigned())
{
primitiveValue = LLVM.LLVMBuildBitCast(builder, primitiveValue, toNativeType, "");
}
// the value needs extending, so decide whether to do a sign-extend or a zero-extend based on whether the from type is signed
else if (fromType.isSigned())
{
primitiveValue = LLVM.LLVMBuildSExt(builder, primitiveValue, toNativeType, "");
}
else
{
primitiveValue = LLVM.LLVMBuildZExt(builder, primitiveValue, toNativeType, "");
}
// pack up the result before returning it
if (to.isNullable())
{
LLVMValueRef result = LLVM.LLVMGetUndef(findNativeType(to));
if (from.isNullable())
{
result = LLVM.LLVMBuildInsertValue(builder, result, isNotNullValue, 0, "");
}
else
{
// set the flag to one to indicate that this value is not null
result = LLVM.LLVMBuildInsertValue(builder, result, LLVM.LLVMConstInt(LLVM.LLVMInt1Type(), 1, false), 0, "");
}
return LLVM.LLVMBuildInsertValue(builder, result, primitiveValue, 1, "");
}
// return the primitive value directly, since the to type is not nullable
// if from was null, then the value we are returning here is undefined
// TODO: if from was null, throw an exception here instead of having undefined behaviour
return primitiveValue;
}
private int getPredicate(ComparisonOperator operator, boolean floating, boolean signed)
{
if (floating)
{
switch (operator)
{
case EQUAL:
return LLVM.LLVMRealPredicate.LLVMRealOEQ;
case LESS_THAN:
return LLVM.LLVMRealPredicate.LLVMRealOLT;
case LESS_THAN_EQUAL:
return LLVM.LLVMRealPredicate.LLVMRealOLE;
case MORE_THAN:
return LLVM.LLVMRealPredicate.LLVMRealOGT;
case MORE_THAN_EQUAL:
return LLVM.LLVMRealPredicate.LLVMRealOGE;
case NOT_EQUAL:
return LLVM.LLVMRealPredicate.LLVMRealONE;
}
}
else
{
switch (operator)
{
case EQUAL:
return LLVM.LLVMIntPredicate.LLVMIntEQ;
case LESS_THAN:
return signed ? LLVM.LLVMIntPredicate.LLVMIntSLT : LLVM.LLVMIntPredicate.LLVMIntULT;
case LESS_THAN_EQUAL:
return signed ? LLVM.LLVMIntPredicate.LLVMIntSLE : LLVM.LLVMIntPredicate.LLVMIntULE;
case MORE_THAN:
return signed ? LLVM.LLVMIntPredicate.LLVMIntSGT : LLVM.LLVMIntPredicate.LLVMIntUGT;
case MORE_THAN_EQUAL:
return signed ? LLVM.LLVMIntPredicate.LLVMIntSGE : LLVM.LLVMIntPredicate.LLVMIntUGE;
case NOT_EQUAL:
return LLVM.LLVMIntPredicate.LLVMIntNE;
}
}
throw new IllegalArgumentException("Unknown predicate '" + operator + "'");
}
private LLVMValueRef buildArrayCreation(LLVMValueRef llvmFunction, LLVMValueRef[] llvmLengths, ArrayType type)
{
LLVMTypeRef llvmArrayType = findNativeType(type);
LLVMValueRef[] indices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false), // go into the pointer to the {i32, [0 x <type>]}
LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 1, false), // go into the structure to get the [0 x <type>]
llvmLengths[0]}; // go length elements along the array, to get the byte directly after the whole structure, which is also our size
LLVMValueRef llvmArraySize = LLVM.LLVMBuildGEP(builder, LLVM.LLVMConstNull(llvmArrayType), C.toNativePointerArray(indices, false, true), indices.length, "");
LLVMValueRef llvmSize = LLVM.LLVMBuildPtrToInt(builder, llvmArraySize, LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), "");
// call calloc to allocate the memory and initialise it to a string of zeros
LLVMValueRef[] arguments = new LLVMValueRef[] {llvmSize, LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 1, false)};
LLVMValueRef memoryPointer = LLVM.LLVMBuildCall(builder, callocFunction, C.toNativePointerArray(arguments, false, true), arguments.length, "");
LLVMValueRef allocatedPointer = LLVM.LLVMBuildBitCast(builder, memoryPointer, llvmArrayType, "");
LLVMValueRef[] sizeIndices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false),
LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false)};
LLVMValueRef sizeElementPointer = LLVM.LLVMBuildGEP(builder, allocatedPointer, C.toNativePointerArray(sizeIndices, false, true), sizeIndices.length, "");
LLVM.LLVMBuildStore(builder, llvmLengths[0], sizeElementPointer);
if (llvmLengths.length > 1)
{
// build a loop to create all of the elements of this array by recursively calling buildArrayCreation()
ArrayType subType = (ArrayType) type.getBaseType();
LLVMBasicBlockRef startBlock = LLVM.LLVMGetInsertBlock(builder);
LLVMBasicBlockRef loopCheckBlock = LLVM.LLVMAppendBasicBlock(llvmFunction, "arrayCreationCheck");
LLVMBasicBlockRef loopBlock = LLVM.LLVMAppendBasicBlock(llvmFunction, "arrayCreation");
LLVMBasicBlockRef exitBlock = LLVM.LLVMAppendBasicBlock(llvmFunction, "arrayCreationEnd");
LLVM.LLVMBuildBr(builder, loopCheckBlock);
LLVM.LLVMPositionBuilderAtEnd(builder, loopCheckBlock);
LLVMValueRef phiNode = LLVM.LLVMBuildPhi(builder, LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), "arrayCounter");
LLVMValueRef breakBoolean = LLVM.LLVMBuildICmp(builder, LLVM.LLVMIntPredicate.LLVMIntULT, phiNode, llvmLengths[0], "");
LLVM.LLVMBuildCondBr(builder, breakBoolean, loopBlock, exitBlock);
LLVM.LLVMPositionBuilderAtEnd(builder, loopBlock);
// recurse to create this element of the array
LLVMValueRef[] subLengths = new LLVMValueRef[llvmLengths.length - 1];
System.arraycopy(llvmLengths, 1, subLengths, 0, subLengths.length);
LLVMValueRef subArray = buildArrayCreation(llvmFunction, subLengths, subType);
// find the indices for the current location in the array
LLVMValueRef[] assignmentIndices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false),
LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 1, false),
phiNode};
LLVMValueRef elementPointer = LLVM.LLVMBuildGEP(builder, allocatedPointer, C.toNativePointerArray(assignmentIndices, false, true), assignmentIndices.length, "");
LLVM.LLVMBuildStore(builder, subArray, elementPointer);
// add the incoming values to the phi node
LLVMValueRef nextCounterValue = LLVM.LLVMBuildAdd(builder, phiNode, LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 1, false), "");
LLVMValueRef[] incomingValues = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false), nextCounterValue};
LLVMBasicBlockRef[] incomingBlocks = new LLVMBasicBlockRef[] {startBlock, LLVM.LLVMGetInsertBlock(builder)};
LLVM.LLVMAddIncoming(phiNode, C.toNativePointerArray(incomingValues, false, true), C.toNativePointerArray(incomingBlocks, false, true), 2);
LLVM.LLVMBuildBr(builder, loopCheckBlock);
LLVM.LLVMPositionBuilderAtEnd(builder, exitBlock);
}
return allocatedPointer;
}
private LLVMValueRef buildExpression(Expression expression, LLVMValueRef llvmFunction, LLVMValueRef thisValue, Map<Variable, LLVMValueRef> variables)
{
if (expression instanceof ArithmeticExpression)
{
ArithmeticExpression arithmeticExpression = (ArithmeticExpression) expression;
LLVMValueRef left = buildExpression(arithmeticExpression.getLeftSubExpression(), llvmFunction, thisValue, variables);
LLVMValueRef right = buildExpression(arithmeticExpression.getRightSubExpression(), llvmFunction, thisValue, variables);
PrimitiveType leftType = (PrimitiveType) arithmeticExpression.getLeftSubExpression().getType();
PrimitiveType rightType = (PrimitiveType) arithmeticExpression.getRightSubExpression().getType();
// cast if necessary
PrimitiveType resultType = (PrimitiveType) arithmeticExpression.getType();
left = convertPrimitiveType(left, leftType, resultType);
right = convertPrimitiveType(right, rightType, resultType);
boolean floating = resultType.getPrimitiveTypeType().isFloating();
boolean signed = resultType.getPrimitiveTypeType().isSigned();
switch (arithmeticExpression.getOperator())
{
case ADD:
return floating ? LLVM.LLVMBuildFAdd(builder, left, right, "") : LLVM.LLVMBuildAdd(builder, left, right, "");
case SUBTRACT:
return floating ? LLVM.LLVMBuildFSub(builder, left, right, "") : LLVM.LLVMBuildSub(builder, left, right, "");
case MULTIPLY:
return floating ? LLVM.LLVMBuildFMul(builder, left, right, "") : LLVM.LLVMBuildMul(builder, left, right, "");
case DIVIDE:
return floating ? LLVM.LLVMBuildFDiv(builder, left, right, "") : signed ? LLVM.LLVMBuildSDiv(builder, left, right, "") : LLVM.LLVMBuildUDiv(builder, left, right, "");
case REMAINDER:
return floating ? LLVM.LLVMBuildFRem(builder, left, right, "") : signed ? LLVM.LLVMBuildSRem(builder, left, right, "") : LLVM.LLVMBuildURem(builder, left, right, "");
case MODULO:
if (floating)
{
LLVMValueRef rem = LLVM.LLVMBuildFRem(builder, left, right, "");
LLVMValueRef add = LLVM.LLVMBuildFAdd(builder, rem, right, "");
return LLVM.LLVMBuildFRem(builder, add, right, "");
}
if (signed)
{
LLVMValueRef rem = LLVM.LLVMBuildSRem(builder, left, right, "");
LLVMValueRef add = LLVM.LLVMBuildAdd(builder, rem, right, "");
return LLVM.LLVMBuildSRem(builder, add, right, "");
}
// unsigned modulo is the same as unsigned remainder
return LLVM.LLVMBuildURem(builder, left, right, "");
}
throw new IllegalArgumentException("Unknown arithmetic operator: " + arithmeticExpression.getOperator());
}
if (expression instanceof ArrayAccessExpression)
{
ArrayAccessExpression arrayAccessExpression = (ArrayAccessExpression) expression;
LLVMValueRef arrayValue = buildExpression(arrayAccessExpression.getArrayExpression(), llvmFunction, thisValue, variables);
LLVMValueRef dimensionValue = buildExpression(arrayAccessExpression.getDimensionExpression(), llvmFunction, thisValue, variables);
LLVMValueRef convertedDimensionValue = convertType(dimensionValue, arrayAccessExpression.getDimensionExpression().getType(), ArrayLengthMember.ARRAY_LENGTH_TYPE, llvmFunction);
LLVMValueRef[] indices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false),
LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 1, false),
convertedDimensionValue};
LLVMValueRef elementPointer = LLVM.LLVMBuildGEP(builder, arrayValue, C.toNativePointerArray(indices, false, true), indices.length, "");
ArrayType arrayType = (ArrayType) arrayAccessExpression.getArrayExpression().getType();
if (arrayType.getBaseType() instanceof NamedType) // TODO (when it doesn't cause a warning): && ((NamedType) arrayAccessExpression.getType()).getResolvedDefinition() instanceof CompoundDefinition)
{
// for compound types, we do not need to load anything here
return convertType(elementPointer, arrayType.getBaseType(), arrayAccessExpression.getType(), llvmFunction);
}
LLVMValueRef value = LLVM.LLVMBuildLoad(builder, elementPointer, "");
return convertType(value, arrayType.getBaseType(), arrayAccessExpression.getType(), llvmFunction);
}
if (expression instanceof ArrayCreationExpression)
{
ArrayCreationExpression arrayCreationExpression = (ArrayCreationExpression) expression;
ArrayType type = arrayCreationExpression.getType();
Expression[] dimensionExpressions = arrayCreationExpression.getDimensionExpressions();
if (dimensionExpressions == null)
{
Expression[] valueExpressions = arrayCreationExpression.getValueExpressions();
LLVMValueRef llvmLength = LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), valueExpressions.length, false);
LLVMValueRef array = buildArrayCreation(llvmFunction, new LLVMValueRef[] {llvmLength}, type);
for (int i = 0; i < valueExpressions.length; i++)
{
LLVMValueRef expressionValue = buildExpression(valueExpressions[i], llvmFunction, thisValue, variables);
LLVMValueRef convertedValue = convertType(expressionValue, valueExpressions[i].getType(), type.getBaseType(), llvmFunction);
Type valueType = valueExpressions[i].getType();
if (valueType instanceof NamedType) // TODO: when it doesn't cause a warning, add: && ((NamedType) valueType).getResolvedDefinition() instanceof CompoundDefinition)
{
convertedValue = LLVM.LLVMBuildLoad(builder, convertedValue, "");
}
LLVMValueRef[] indices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false),
LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 1, false),
LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), i, false)};
LLVMValueRef elementPointer = LLVM.LLVMBuildGEP(builder, array, C.toNativePointerArray(indices, false, true), indices.length, "");
LLVM.LLVMBuildStore(builder, convertedValue, elementPointer);
}
return array;
}
LLVMValueRef[] llvmLengths = new LLVMValueRef[dimensionExpressions.length];
for (int i = 0; i < llvmLengths.length; i++)
{
LLVMValueRef expressionValue = buildExpression(dimensionExpressions[i], llvmFunction, thisValue, variables);
llvmLengths[i] = convertType(expressionValue, dimensionExpressions[i].getType(), ArrayLengthMember.ARRAY_LENGTH_TYPE, llvmFunction);
}
return buildArrayCreation(llvmFunction, llvmLengths, type);
}
if (expression instanceof BitwiseNotExpression)
{
LLVMValueRef value = buildExpression(((BitwiseNotExpression) expression).getExpression(), llvmFunction, thisValue, variables);
return LLVM.LLVMBuildNot(builder, value, "");
}
if (expression instanceof BooleanLiteralExpression)
{
return LLVM.LLVMConstInt(LLVM.LLVMInt1Type(), ((BooleanLiteralExpression) expression).getValue() ? 1 : 0, false);
}
if (expression instanceof BooleanNotExpression)
{
LLVMValueRef value = buildExpression(((BooleanNotExpression) expression).getExpression(), llvmFunction, thisValue, variables);
return LLVM.LLVMBuildNot(builder, value, "");
}
if (expression instanceof BracketedExpression)
{
BracketedExpression bracketedExpression = (BracketedExpression) expression;
LLVMValueRef value = buildExpression(bracketedExpression.getExpression(), llvmFunction, thisValue, variables);
return convertType(value, bracketedExpression.getExpression().getType(), expression.getType(), llvmFunction);
}
if (expression instanceof CastExpression)
{
CastExpression castExpression = (CastExpression) expression;
LLVMValueRef value = buildExpression(castExpression.getExpression(), llvmFunction, thisValue, variables);
return convertType(value, castExpression.getExpression().getType(), castExpression.getType(), llvmFunction);
}
if (expression instanceof ComparisonExpression)
{
ComparisonExpression comparisonExpression = (ComparisonExpression) expression;
LLVMValueRef left = buildExpression(comparisonExpression.getLeftSubExpression(), llvmFunction, thisValue, variables);
LLVMValueRef right = buildExpression(comparisonExpression.getRightSubExpression(), llvmFunction, thisValue, variables);
PrimitiveType leftType = (PrimitiveType) comparisonExpression.getLeftSubExpression().getType();
PrimitiveType rightType = (PrimitiveType) comparisonExpression.getRightSubExpression().getType();
// cast if necessary
PrimitiveType resultType = comparisonExpression.getComparisonType();
if (resultType == null)
{
PrimitiveTypeType leftTypeType = leftType.getPrimitiveTypeType();
PrimitiveTypeType rightTypeType = rightType.getPrimitiveTypeType();
if (!leftTypeType.isFloating() && !rightTypeType.isFloating() &&
leftTypeType.getBitCount() == rightTypeType.getBitCount() &&
leftTypeType.isSigned() != rightTypeType.isSigned())
{
// compare the signed and non-signed integers as (bitCount + 1) bit numbers, since they will not fit in bitCount bits
LLVMTypeRef comparisonType = LLVM.LLVMIntType(leftType.getPrimitiveTypeType().getBitCount() + 1);
if (leftTypeType.isSigned())
{
left = LLVM.LLVMBuildSExt(builder, left, comparisonType, "");
right = LLVM.LLVMBuildZExt(builder, right, comparisonType, "");
}
else
{
left = LLVM.LLVMBuildZExt(builder, left, comparisonType, "");
right = LLVM.LLVMBuildSExt(builder, right, comparisonType, "");
}
return LLVM.LLVMBuildICmp(builder, getPredicate(comparisonExpression.getOperator(), false, true), left, right, "");
}
throw new IllegalArgumentException("Unknown result type, unable to generate comparison expression: " + expression);
}
left = convertPrimitiveType(left, leftType, resultType);
right = convertPrimitiveType(right, rightType, resultType);
if (resultType.getPrimitiveTypeType().isFloating())
{
return LLVM.LLVMBuildFCmp(builder, getPredicate(comparisonExpression.getOperator(), true, true), left, right, "");
}
return LLVM.LLVMBuildICmp(builder, getPredicate(comparisonExpression.getOperator(), false, resultType.getPrimitiveTypeType().isSigned()), left, right, "");
}
if (expression instanceof FieldAccessExpression)
{
FieldAccessExpression fieldAccessExpression = (FieldAccessExpression) expression;
Member member = fieldAccessExpression.getResolvedMember();
if (member instanceof ArrayLengthMember)
{
LLVMValueRef array = buildExpression(fieldAccessExpression.getBaseExpression(), llvmFunction, thisValue, variables);
LLVMValueRef[] sizeIndices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false),
LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false)};
LLVMValueRef elementPointer = LLVM.LLVMBuildGEP(builder, array, C.toNativePointerArray(sizeIndices, false, true), sizeIndices.length, "");
return LLVM.LLVMBuildLoad(builder, elementPointer, "");
}
if (member instanceof Field)
{
Field field = (Field) member;
if (field.isStatic())
{
LLVMValueRef global = getGlobal(field.getGlobalVariable());
if (field.getType() instanceof NamedType) // TODO (when it doesn't cause a warning): && ((NamedType) field.getType()).getResolvedDefinition() instanceof CompoundDefinition)
{
// for compound types, we do not need to load anything here
return global;
}
return LLVM.LLVMBuildLoad(builder, global, "");
}
LLVMValueRef baseValue = buildExpression(fieldAccessExpression.getBaseExpression(), llvmFunction, thisValue, variables);
LLVMValueRef[] indices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false),
LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), field.getMemberIndex(), false)};
LLVMValueRef elementPointer = LLVM.LLVMBuildGEP(builder, baseValue, C.toNativePointerArray(indices, false, true), indices.length, "");
if (field.getType() instanceof NamedType) // TODO (when it doesn't cause a warning): && ((NamedType) field.getType()).getResolvedDefinition() instanceof CompoundDefinition)
{
// for compound types, we do not need to load anything here
return elementPointer;
}
return LLVM.LLVMBuildLoad(builder, elementPointer, "");
}
}
if (expression instanceof FloatingLiteralExpression)
{
double value = Double.parseDouble(((FloatingLiteralExpression) expression).getLiteral().toString());
return LLVM.LLVMConstReal(findNativeType(expression.getType()), value);
}
if (expression instanceof FunctionCallExpression)
{
FunctionCallExpression functionExpression = (FunctionCallExpression) expression;
Constructor resolvedConstructor = functionExpression.getResolvedConstructor();
Method resolvedMethod = functionExpression.getResolvedMethod();
Expression resolvedBaseExpression = functionExpression.getResolvedBaseExpression();
Type[] parameterTypes;
Type returnType;
LLVMValueRef llvmResolvedFunction;
if (resolvedConstructor != null)
{
Parameter[] params = resolvedConstructor.getParameters();
parameterTypes = new Type[params.length];
for (int i = 0; i < params.length; ++i)
{
parameterTypes[i] = params[i].getType();
}
returnType = new NamedType(false, resolvedConstructor.getContainingDefinition());
llvmResolvedFunction = getConstructorFunction(resolvedConstructor);
}
else if (resolvedMethod != null)
{
Parameter[] params = resolvedMethod.getParameters();
parameterTypes = new Type[params.length];
for (int i = 0; i < params.length; ++i)
{
parameterTypes[i] = params[i].getType();
}
returnType = resolvedMethod.getReturnType();
llvmResolvedFunction = getMethodFunction(resolvedMethod);
}
else if (resolvedBaseExpression != null)
{
FunctionType baseType = (FunctionType) resolvedBaseExpression.getType();
parameterTypes = baseType.getParameterTypes();
returnType = baseType.getReturnType();
llvmResolvedFunction = null;
}
else
{
throw new IllegalArgumentException("Unresolved function call expression: " + functionExpression);
}
LLVMValueRef callee = null;
if (resolvedBaseExpression != null)
{
callee = buildExpression(resolvedBaseExpression, llvmFunction, thisValue, variables);
}
Expression[] arguments = functionExpression.getArguments();
LLVMValueRef[] values = new LLVMValueRef[arguments.length];
for (int i = 0; i < arguments.length; i++)
{
LLVMValueRef arg = buildExpression(arguments[i], llvmFunction, thisValue, variables);
values[i] = convertType(arg, arguments[i].getType(), parameterTypes[i], llvmFunction);
if (parameterTypes[i] instanceof NamedType) // TODO: when it doesn't cause a warning, add: && ((NamedType) parameterTypes[i]).getResolvedDefinition() instanceof CompoundDefinition)
{
// for compound types, we need to pass the value itself, not the pointer to the value
values[i] = LLVM.LLVMBuildLoad(builder, values[i], "");
}
}
LLVMValueRef result;
if (resolvedConstructor != null)
{
result = LLVM.LLVMBuildCall(builder, llvmResolvedFunction, C.toNativePointerArray(values, false, true), values.length, "");
}
else if (resolvedMethod != null)
{
LLVMValueRef[] realArguments;
if (resolvedMethod.isStatic())
{
realArguments = values;
}
else
{
realArguments = new LLVMValueRef[values.length + 1];
realArguments[0] = callee;
if (callee == null)
{
realArguments[0] = thisValue;
}
System.arraycopy(values, 0, realArguments, 1, values.length);
}
result = LLVM.LLVMBuildCall(builder, llvmResolvedFunction, C.toNativePointerArray(realArguments, false, true), realArguments.length, "");
}
else if (resolvedBaseExpression != null)
{
// callee here is actually a tuple of an opaque pointer and a function type, where the first argument to the function is the opaque pointer
LLVMValueRef firstArgument = LLVM.LLVMBuildExtractValue(builder, callee, 0, "");
LLVMValueRef calleeFunction = LLVM.LLVMBuildExtractValue(builder, callee, 1, "");
LLVMValueRef[] realArguments = new LLVMValueRef[values.length + 1];
realArguments[0] = firstArgument;
System.arraycopy(values, 0, realArguments, 1, values.length);
result = LLVM.LLVMBuildCall(builder, calleeFunction, C.toNativePointerArray(realArguments, false, true), realArguments.length, "");
}
else
{
throw new IllegalArgumentException("Unresolved function call expression: " + functionExpression);
}
if (returnType instanceof NamedType) // TODO (when it doesn't cause a warning): && ((NamedType) returnType).getResolvedDefinition() instanceof CompoundDefinition)
{
// for compound types, we need to get a pointer from this returned value
// so build an alloca in the entry block
LLVMBasicBlockRef currentBlock = LLVM.LLVMGetInsertBlock(builder);
LLVM.LLVMPositionBuilderBefore(builder, LLVM.LLVMGetFirstInstruction(LLVM.LLVMGetEntryBasicBlock(llvmFunction)));
LLVMValueRef alloca = LLVM.LLVMBuildAlloca(builder, findNativeType(returnType), "");
LLVM.LLVMPositionBuilderAtEnd(builder, currentBlock);
LLVM.LLVMBuildStore(builder, result, alloca);
return alloca;
}
return result;
}
if (expression instanceof InlineIfExpression)
{
InlineIfExpression inlineIf = (InlineIfExpression) expression;
LLVMValueRef conditionValue = buildExpression(inlineIf.getCondition(), llvmFunction, thisValue, variables);
LLVMBasicBlockRef thenBlock = LLVM.LLVMAppendBasicBlock(llvmFunction, "inlineIfThen");
LLVMBasicBlockRef elseBlock = LLVM.LLVMAppendBasicBlock(llvmFunction, "inlineIfElse");
LLVMBasicBlockRef continuationBlock = LLVM.LLVMAppendBasicBlock(llvmFunction, "afterInlineIf");
LLVM.LLVMBuildCondBr(builder, conditionValue, thenBlock, elseBlock);
LLVM.LLVMPositionBuilderAtEnd(builder, thenBlock);
LLVMValueRef thenValue = buildExpression(inlineIf.getThenExpression(), llvmFunction, thisValue, variables);
LLVMValueRef convertedThenValue = convertType(thenValue, inlineIf.getThenExpression().getType(), inlineIf.getType(), llvmFunction);
LLVMBasicBlockRef thenBranchBlock = LLVM.LLVMGetInsertBlock(builder);
LLVM.LLVMBuildBr(builder, continuationBlock);
LLVM.LLVMPositionBuilderAtEnd(builder, elseBlock);
LLVMValueRef elseValue = buildExpression(inlineIf.getElseExpression(), llvmFunction, thisValue, variables);
LLVMValueRef convertedElseValue = convertType(elseValue, inlineIf.getElseExpression().getType(), inlineIf.getType(), llvmFunction);
LLVMBasicBlockRef elseBranchBlock = LLVM.LLVMGetInsertBlock(builder);
LLVM.LLVMBuildBr(builder, continuationBlock);
LLVM.LLVMPositionBuilderAtEnd(builder, continuationBlock);
LLVMValueRef result = LLVM.LLVMBuildPhi(builder, findNativeType(inlineIf.getType()), "");
LLVMValueRef[] incomingValues = new LLVMValueRef[] {convertedThenValue, convertedElseValue};
LLVMBasicBlockRef[] incomingBlocks = new LLVMBasicBlockRef[] {thenBranchBlock, elseBranchBlock};
LLVM.LLVMAddIncoming(result, C.toNativePointerArray(incomingValues, false, true), C.toNativePointerArray(incomingBlocks, false, true), 2);
return result;
}
if (expression instanceof IntegerLiteralExpression)
{
int n = ((IntegerLiteralExpression) expression).getLiteral().getValue().intValue();
return LLVM.LLVMConstInt(findNativeType(expression.getType()), n, false);
}
if (expression instanceof LogicalExpression)
{
LogicalExpression logicalExpression = (LogicalExpression) expression;
LLVMValueRef left = buildExpression(logicalExpression.getLeftSubExpression(), llvmFunction, thisValue, variables);
PrimitiveType leftType = (PrimitiveType) logicalExpression.getLeftSubExpression().getType();
PrimitiveType rightType = (PrimitiveType) logicalExpression.getRightSubExpression().getType();
// cast if necessary
PrimitiveType resultType = (PrimitiveType) logicalExpression.getType();
left = convertPrimitiveType(left, leftType, resultType);
LogicalOperator operator = logicalExpression.getOperator();
if (operator != LogicalOperator.SHORT_CIRCUIT_AND && operator != LogicalOperator.SHORT_CIRCUIT_OR)
{
LLVMValueRef right = buildExpression(logicalExpression.getRightSubExpression(), llvmFunction, thisValue, variables);
right = convertPrimitiveType(right, rightType, resultType);
switch (operator)
{
case AND:
return LLVM.LLVMBuildAnd(builder, left, right, "");
case OR:
return LLVM.LLVMBuildOr(builder, left, right, "");
case XOR:
return LLVM.LLVMBuildXor(builder, left, right, "");
default:
throw new IllegalStateException("Unexpected non-short-circuit operator: " + logicalExpression.getOperator());
}
}
LLVMBasicBlockRef currentBlock = LLVM.LLVMGetInsertBlock(builder);
LLVMBasicBlockRef rightCheckBlock = LLVM.LLVMAppendBasicBlock(llvmFunction, "shortCircuitCheck");
LLVMBasicBlockRef continuationBlock = LLVM.LLVMAppendBasicBlock(llvmFunction, "shortCircuitContinue");
// the only difference between short circuit AND and OR is whether they jump to the check block when the left hand side is true or false
LLVMBasicBlockRef trueDest = operator == LogicalOperator.SHORT_CIRCUIT_AND ? rightCheckBlock : continuationBlock;
LLVMBasicBlockRef falseDest = operator == LogicalOperator.SHORT_CIRCUIT_AND ? continuationBlock : rightCheckBlock;
LLVM.LLVMBuildCondBr(builder, left, trueDest, falseDest);
LLVM.LLVMPositionBuilderAtEnd(builder, rightCheckBlock);
LLVMValueRef right = buildExpression(logicalExpression.getRightSubExpression(), llvmFunction, thisValue, variables);
right = convertPrimitiveType(right, rightType, resultType);
LLVM.LLVMBuildBr(builder, continuationBlock);
LLVM.LLVMPositionBuilderAtEnd(builder, continuationBlock);
// create a phi node for the result, and return it
LLVMValueRef phi = LLVM.LLVMBuildPhi(builder, findNativeType(resultType), "");
LLVMValueRef[] incomingValues = new LLVMValueRef[] {left, right};
LLVMBasicBlockRef[] incomingBlocks = new LLVMBasicBlockRef[] {currentBlock, rightCheckBlock};
LLVM.LLVMAddIncoming(phi, C.toNativePointerArray(incomingValues, false, true), C.toNativePointerArray(incomingBlocks, false, true), 2);
return phi;
}
if (expression instanceof MinusExpression)
{
MinusExpression minusExpression = (MinusExpression) expression;
LLVMValueRef value = buildExpression(minusExpression.getExpression(), llvmFunction, thisValue, variables);
value = convertPrimitiveType(value, (PrimitiveType) minusExpression.getExpression().getType(), (PrimitiveType) minusExpression.getType());
PrimitiveTypeType primitiveTypeType = ((PrimitiveType) minusExpression.getType()).getPrimitiveTypeType();
if (primitiveTypeType.isFloating())
{
return LLVM.LLVMBuildFNeg(builder, value, "");
}
return LLVM.LLVMBuildNeg(builder, value, "");
}
if (expression instanceof NullLiteralExpression)
{
Type type = expression.getType();
LLVMValueRef value = LLVM.LLVMConstNull(findNativeType(type));
if (type instanceof NamedType) // TODO (when it doesn't cause a warning): && ((NamedType) type).getResolvedDefinition() instanceof CompoundDefinition)
{
// for compound types, we need to get a pointer from this null value
// so build an alloca in the entry block
LLVMBasicBlockRef currentBlock = LLVM.LLVMGetInsertBlock(builder);
LLVM.LLVMPositionBuilderBefore(builder, LLVM.LLVMGetFirstInstruction(LLVM.LLVMGetEntryBasicBlock(llvmFunction)));
LLVMValueRef alloca = LLVM.LLVMBuildAlloca(builder, findNativeType(type), "");
LLVM.LLVMPositionBuilderAtEnd(builder, currentBlock);
LLVM.LLVMBuildStore(builder, value, alloca);
return alloca;
}
return value;
}
if (expression instanceof ShiftExpression)
{
ShiftExpression shiftExpression = (ShiftExpression) expression;
LLVMValueRef leftValue = buildExpression(shiftExpression.getLeftExpression(), llvmFunction, thisValue, variables);
LLVMValueRef rightValue = buildExpression(shiftExpression.getRightExpression(), llvmFunction, thisValue, variables);
LLVMValueRef convertedLeft = convertType(leftValue, shiftExpression.getLeftExpression().getType(), shiftExpression.getType(), llvmFunction);
LLVMValueRef convertedRight = convertType(rightValue, shiftExpression.getRightExpression().getType(), shiftExpression.getType(), llvmFunction);
switch (shiftExpression.getOperator())
{
case RIGHT_SHIFT:
if (((PrimitiveType) shiftExpression.getType()).getPrimitiveTypeType().isSigned())
{
return LLVM.LLVMBuildAShr(builder, convertedLeft, convertedRight, "");
}
return LLVM.LLVMBuildLShr(builder, convertedLeft, convertedRight, "");
case LEFT_SHIFT:
return LLVM.LLVMBuildShl(builder, convertedLeft, convertedRight, "");
}
throw new IllegalArgumentException("Unknown shift operator: " + shiftExpression.getOperator());
}
if (expression instanceof ThisExpression)
{
return thisValue;
}
if (expression instanceof TupleExpression)
{
TupleExpression tupleExpression = (TupleExpression) expression;
Type[] tupleTypes = ((TupleType) tupleExpression.getType()).getSubTypes();
Expression[] subExpressions = tupleExpression.getSubExpressions();
LLVMValueRef currentValue = LLVM.LLVMGetUndef(findNativeType(tupleExpression.getType()));
for (int i = 0; i < subExpressions.length; i++)
{
LLVMValueRef value = buildExpression(subExpressions[i], llvmFunction, thisValue, variables);
Type type = tupleTypes[i];
value = convertType(value, subExpressions[i].getType(), type, llvmFunction);
if (type instanceof NamedType) // TODO: when this does not cause a warning, add it: && ((NamedType) type).getResolvedDefinition() instanceof CompoundDefinition)
{
// for compound types, we need to load from the result of the expression before storing the result in the tuple
value = LLVM.LLVMBuildLoad(builder, value, "");
}
currentValue = LLVM.LLVMBuildInsertValue(builder, currentValue, value, i, "");
}
return currentValue;
}
if (expression instanceof TupleIndexExpression)
{
TupleIndexExpression tupleIndexExpression = (TupleIndexExpression) expression;
TupleType tupleType = (TupleType) tupleIndexExpression.getExpression().getType();
LLVMValueRef result = buildExpression(tupleIndexExpression.getExpression(), llvmFunction, thisValue, variables);
// convert the 1-based indexing to 0-based before extracting the value
int index = tupleIndexExpression.getIndexLiteral().getValue().intValue() - 1;
LLVMValueRef value = LLVM.LLVMBuildExtractValue(builder, result, index, "");
LLVMValueRef convertedValue = convertType(value, tupleType.getSubTypes()[index], tupleIndexExpression.getType(), llvmFunction);
Type type = tupleIndexExpression.getType();
if (type instanceof NamedType) // TODO: when the doesn't cause a warning, add it: && ((NamedType) type).getResolvedDefinition() instanceof CompoundDefinition)
{
// for compound types, we need to get a pointer to the extracted value
// so build an alloca in the entry block
LLVMBasicBlockRef currentBlock = LLVM.LLVMGetInsertBlock(builder);
LLVM.LLVMPositionBuilderBefore(builder, LLVM.LLVMGetFirstInstruction(LLVM.LLVMGetEntryBasicBlock(llvmFunction)));
LLVMValueRef alloca = LLVM.LLVMBuildAlloca(builder, findNativeType(type), "");
LLVM.LLVMPositionBuilderAtEnd(builder, currentBlock);
LLVM.LLVMBuildStore(builder, convertedValue, alloca);
return alloca;
}
return convertedValue;
}
if (expression instanceof VariableExpression)
{
Variable variable = ((VariableExpression) expression).getResolvedVariable();
if (variable instanceof MemberVariable)
{
Field field = ((MemberVariable) variable).getField();
LLVMValueRef[] indices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false),
LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), field.getMemberIndex(), false)};
LLVMValueRef elementPointer = LLVM.LLVMBuildGEP(builder, thisValue, C.toNativePointerArray(indices, false, true), indices.length, "");
if (field.getType() instanceof NamedType) // TODO (when it doesn't cause a warning): && ((NamedType) field.getType()).getResolvedDefinition() instanceof CompoundDefinition)
{
// for compound types, we do not need to load anything here
return elementPointer;
}
return LLVM.LLVMBuildLoad(builder, elementPointer, "");
}
if (variable instanceof GlobalVariable)
{
LLVMValueRef global = getGlobal((GlobalVariable) variable);
if (expression.getType() instanceof NamedType) // TODO (when it doesn't cause a warning): && ((NamedType) field.getType()).getResolvedDefinition() instanceof CompoundDefinition)
{
// for compound types, we do not need to load anything here
return global;
}
return LLVM.LLVMBuildLoad(builder, global, "");
}
LLVMValueRef value = variables.get(variable);
if (value == null)
{
throw new IllegalStateException("Missing LLVMValueRef in variable Map: " + ((VariableExpression) expression).getName());
}
if (variable.getType() instanceof NamedType) // TODO (when it doesn't cause a warning): && ((NamedType) variable.getType()).getResolvedDefinition() instanceof CompoundDefinition)
{
// for compound types, we do not need to load anything here
return value;
}
return LLVM.LLVMBuildLoad(builder, value, "");
}
throw new IllegalArgumentException("Unknown Expression type: " + expression);
}
}
| src/eu/bryants/anthony/toylanguage/compiler/passes/CodeGenerator.java | package eu.bryants.anthony.toylanguage.compiler.passes;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import nativelib.c.C;
import nativelib.llvm.LLVM;
import nativelib.llvm.LLVM.LLVMBasicBlockRef;
import nativelib.llvm.LLVM.LLVMBuilderRef;
import nativelib.llvm.LLVM.LLVMModuleRef;
import nativelib.llvm.LLVM.LLVMTypeRef;
import nativelib.llvm.LLVM.LLVMValueRef;
import com.sun.jna.Pointer;
import eu.bryants.anthony.toylanguage.ast.CompoundDefinition;
import eu.bryants.anthony.toylanguage.ast.expression.ArithmeticExpression;
import eu.bryants.anthony.toylanguage.ast.expression.ArrayAccessExpression;
import eu.bryants.anthony.toylanguage.ast.expression.ArrayCreationExpression;
import eu.bryants.anthony.toylanguage.ast.expression.BitwiseNotExpression;
import eu.bryants.anthony.toylanguage.ast.expression.BooleanLiteralExpression;
import eu.bryants.anthony.toylanguage.ast.expression.BooleanNotExpression;
import eu.bryants.anthony.toylanguage.ast.expression.BracketedExpression;
import eu.bryants.anthony.toylanguage.ast.expression.CastExpression;
import eu.bryants.anthony.toylanguage.ast.expression.ComparisonExpression;
import eu.bryants.anthony.toylanguage.ast.expression.ComparisonExpression.ComparisonOperator;
import eu.bryants.anthony.toylanguage.ast.expression.Expression;
import eu.bryants.anthony.toylanguage.ast.expression.FieldAccessExpression;
import eu.bryants.anthony.toylanguage.ast.expression.FloatingLiteralExpression;
import eu.bryants.anthony.toylanguage.ast.expression.FunctionCallExpression;
import eu.bryants.anthony.toylanguage.ast.expression.InlineIfExpression;
import eu.bryants.anthony.toylanguage.ast.expression.IntegerLiteralExpression;
import eu.bryants.anthony.toylanguage.ast.expression.LogicalExpression;
import eu.bryants.anthony.toylanguage.ast.expression.LogicalExpression.LogicalOperator;
import eu.bryants.anthony.toylanguage.ast.expression.MinusExpression;
import eu.bryants.anthony.toylanguage.ast.expression.NullLiteralExpression;
import eu.bryants.anthony.toylanguage.ast.expression.ShiftExpression;
import eu.bryants.anthony.toylanguage.ast.expression.ThisExpression;
import eu.bryants.anthony.toylanguage.ast.expression.TupleExpression;
import eu.bryants.anthony.toylanguage.ast.expression.TupleIndexExpression;
import eu.bryants.anthony.toylanguage.ast.expression.VariableExpression;
import eu.bryants.anthony.toylanguage.ast.member.ArrayLengthMember;
import eu.bryants.anthony.toylanguage.ast.member.Constructor;
import eu.bryants.anthony.toylanguage.ast.member.Field;
import eu.bryants.anthony.toylanguage.ast.member.Member;
import eu.bryants.anthony.toylanguage.ast.member.Method;
import eu.bryants.anthony.toylanguage.ast.metadata.GlobalVariable;
import eu.bryants.anthony.toylanguage.ast.metadata.MemberVariable;
import eu.bryants.anthony.toylanguage.ast.metadata.Variable;
import eu.bryants.anthony.toylanguage.ast.misc.ArrayElementAssignee;
import eu.bryants.anthony.toylanguage.ast.misc.Assignee;
import eu.bryants.anthony.toylanguage.ast.misc.BlankAssignee;
import eu.bryants.anthony.toylanguage.ast.misc.FieldAssignee;
import eu.bryants.anthony.toylanguage.ast.misc.Parameter;
import eu.bryants.anthony.toylanguage.ast.misc.VariableAssignee;
import eu.bryants.anthony.toylanguage.ast.statement.AssignStatement;
import eu.bryants.anthony.toylanguage.ast.statement.Block;
import eu.bryants.anthony.toylanguage.ast.statement.BreakStatement;
import eu.bryants.anthony.toylanguage.ast.statement.BreakableStatement;
import eu.bryants.anthony.toylanguage.ast.statement.ContinueStatement;
import eu.bryants.anthony.toylanguage.ast.statement.ExpressionStatement;
import eu.bryants.anthony.toylanguage.ast.statement.ForStatement;
import eu.bryants.anthony.toylanguage.ast.statement.IfStatement;
import eu.bryants.anthony.toylanguage.ast.statement.PrefixIncDecStatement;
import eu.bryants.anthony.toylanguage.ast.statement.ReturnStatement;
import eu.bryants.anthony.toylanguage.ast.statement.ShorthandAssignStatement;
import eu.bryants.anthony.toylanguage.ast.statement.Statement;
import eu.bryants.anthony.toylanguage.ast.statement.WhileStatement;
import eu.bryants.anthony.toylanguage.ast.type.ArrayType;
import eu.bryants.anthony.toylanguage.ast.type.FunctionType;
import eu.bryants.anthony.toylanguage.ast.type.NamedType;
import eu.bryants.anthony.toylanguage.ast.type.NullType;
import eu.bryants.anthony.toylanguage.ast.type.PrimitiveType;
import eu.bryants.anthony.toylanguage.ast.type.PrimitiveType.PrimitiveTypeType;
import eu.bryants.anthony.toylanguage.ast.type.TupleType;
import eu.bryants.anthony.toylanguage.ast.type.Type;
import eu.bryants.anthony.toylanguage.ast.type.VoidType;
/*
* Created on 5 Apr 2012
*/
/**
* @author Anthony Bryant
*/
public class CodeGenerator
{
private CompoundDefinition compoundDefinition;
private LLVMModuleRef module;
private LLVMBuilderRef builder;
private LLVMValueRef callocFunction;
private Map<GlobalVariable, LLVMValueRef> globalVariables = new HashMap<GlobalVariable, LLVMValueRef>();
public CodeGenerator(CompoundDefinition compoundDefinition)
{
this.compoundDefinition = compoundDefinition;
module = LLVM.LLVMModuleCreateWithName(compoundDefinition.getQualifiedName().toString());
builder = LLVM.LLVMCreateBuilder();
}
public void generate(String outputPath)
{
// add all of the global (static) variables
addGlobalVariables();
// add all of the LLVM functions, including constructors, methods, and normal functions
addFunctions();
addConstructorBodies(compoundDefinition);
addMethodBodies(compoundDefinition);
LLVM.LLVMWriteBitcodeToFile(module, outputPath);
}
private void addGlobalVariables()
{
for (Field field : compoundDefinition.getFields())
{
if (field.isStatic())
{
GlobalVariable globalVariable = field.getGlobalVariable();
LLVMValueRef value = LLVM.LLVMAddGlobal(module, findNativeType(field.getType()), globalVariable.getMangledName());
LLVM.LLVMSetInitializer(value, LLVM.LLVMConstNull(findNativeType(field.getType())));
globalVariables.put(globalVariable, value);
}
}
}
private LLVMValueRef getGlobal(GlobalVariable globalVariable)
{
LLVMValueRef value = globalVariables.get(globalVariable);
if (value != null)
{
return value;
}
// lazily initialise globals which do not yet exist
Type type = globalVariable.getType();
LLVMValueRef newValue = LLVM.LLVMAddGlobal(module, findNativeType(type), globalVariable.getMangledName());
LLVM.LLVMSetInitializer(newValue, LLVM.LLVMConstNull(findNativeType(type)));
globalVariables.put(globalVariable, newValue);
return newValue;
}
private void addFunctions()
{
// add calloc() as an external function
LLVMTypeRef callocReturnType = LLVM.LLVMPointerType(LLVM.LLVMInt8Type(), 0);
LLVMTypeRef[] callocParamTypes = new LLVMTypeRef[] {LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount())};
callocFunction = LLVM.LLVMAddFunction(module, "calloc", LLVM.LLVMFunctionType(callocReturnType, C.toNativePointerArray(callocParamTypes, false, true), callocParamTypes.length, false));
for (Constructor constructor : compoundDefinition.getConstructors())
{
getConstructorFunction(constructor);
}
for (Method method : compoundDefinition.getAllMethods())
{
getMethodFunction(method);
}
}
/**
* Gets the function definition for the specified Constructor. If necessary, it is added first.
* @param constructor - the Constructor to find the declaration of (or to declare)
* @return the function declaration for the specified Constructor
*/
private LLVMValueRef getConstructorFunction(Constructor constructor)
{
String mangledName = constructor.getMangledName();
LLVMValueRef existingFunc = LLVM.LLVMGetNamedFunction(module, mangledName);
if (existingFunc != null)
{
return existingFunc;
}
Parameter[] parameters = constructor.getParameters();
LLVMTypeRef[] types = new LLVMTypeRef[parameters.length];
for (int i = 0; i < types.length; i++)
{
types[i] = findNativeType(parameters[i].getType());
}
LLVMTypeRef resultType = findNativeType(new NamedType(false, compoundDefinition));
Pointer paramTypes = C.toNativePointerArray(types, false, true);
LLVMTypeRef functionType = LLVM.LLVMFunctionType(resultType, paramTypes, types.length, false);
LLVMValueRef llvmFunc = LLVM.LLVMAddFunction(module, mangledName, functionType);
LLVM.LLVMSetFunctionCallConv(llvmFunc, LLVM.LLVMCallConv.LLVMCCallConv);
int paramCount = LLVM.LLVMCountParams(llvmFunc);
if (paramCount != parameters.length)
{
throw new IllegalStateException("LLVM returned wrong number of parameters");
}
for (int i = 0; i < paramCount; i++)
{
LLVMValueRef parameter = LLVM.LLVMGetParam(llvmFunc, i);
LLVM.LLVMSetValueName(parameter, parameters[i].getName());
}
return llvmFunc;
}
/**
* Gets the function definition for the specified Method. If necessary, it is added first.
* @param method - the Method to find the declaration of (or to declare)
* @return the function declaration for the specified Method
*/
private LLVMValueRef getMethodFunction(Method method)
{
String mangledName = method.getMangledName();
LLVMValueRef existingFunc = LLVM.LLVMGetNamedFunction(module, mangledName);
if (existingFunc != null)
{
return existingFunc;
}
Parameter[] parameters = method.getParameters();
LLVMTypeRef[] types;
if (method.isStatic())
{
types = new LLVMTypeRef[parameters.length];
for (int i = 0; i < parameters.length; ++i)
{
types[i] = findNativeType(parameters[i].getType());
}
}
else
{
types = new LLVMTypeRef[1 + parameters.length];
// add the 'this' type to the function
types[0] = LLVM.LLVMPointerType(findNativeType(new NamedType(false, compoundDefinition)), 0);
for (int i = 0; i < parameters.length; i++)
{
types[i + 1] = findNativeType(parameters[i].getType());
}
}
LLVMTypeRef resultType = findNativeType(method.getReturnType());
Pointer paramTypes = C.toNativePointerArray(types, false, true);
LLVMTypeRef functionType = LLVM.LLVMFunctionType(resultType, paramTypes, types.length, false);
LLVMValueRef llvmFunc = LLVM.LLVMAddFunction(module, mangledName, functionType);
LLVM.LLVMSetFunctionCallConv(llvmFunc, LLVM.LLVMCallConv.LLVMCCallConv);
int paramCount = LLVM.LLVMCountParams(llvmFunc);
if (paramCount != types.length)
{
throw new IllegalStateException("LLVM returned wrong number of parameters");
}
if (method.isStatic())
{
for (int i = 0; i < paramCount; i++)
{
LLVMValueRef parameter = LLVM.LLVMGetParam(llvmFunc, i);
LLVM.LLVMSetValueName(parameter, parameters[i].getName());
}
}
else
{
LLVM.LLVMSetValueName(LLVM.LLVMGetParam(llvmFunc, 0), "this");
for (int i = 1; i < paramCount; i++)
{
LLVMValueRef parameter = LLVM.LLVMGetParam(llvmFunc, i);
LLVM.LLVMSetValueName(parameter, parameters[i - 1].getName());
}
}
// add the native function if the programmer specified one
if (method.getNativeName() != null)
{
addNativeFunction(method.getNativeName(), !(method.getReturnType() instanceof VoidType), functionType, llvmFunc);
}
return llvmFunc;
}
/**
* Adds a native function which calls the specified non-native function.
* This consists simply of a new function with the specified native name, which calls the non-native function and returns its result.
* @param nativeName - the native name to export
* @param hasReturnValue - true if this method returns a value, false otherwise
* @param functionType - the type of the non-native function
* @param nonNativeFunction - the non-native function to call
*/
private void addNativeFunction(String nativeName, boolean hasReturnValue, LLVMTypeRef functionType, LLVMValueRef nonNativeFunction)
{
LLVMValueRef nativeFunction = LLVM.LLVMAddFunction(module, nativeName, functionType);
LLVM.LLVMSetFunctionCallConv(nativeFunction, LLVM.LLVMCallConv.LLVMCCallConv);
int paramCount = LLVM.LLVMCountParams(nativeFunction);
LLVMValueRef[] arguments = new LLVMValueRef[paramCount];
for (int i = 0; i < paramCount; ++i)
{
arguments[i] = LLVM.LLVMGetParam(nativeFunction, i);
}
LLVMBasicBlockRef block = LLVM.LLVMAppendBasicBlock(nativeFunction, "entry");
LLVM.LLVMPositionBuilderAtEnd(builder, block);
LLVMValueRef result = LLVM.LLVMBuildCall(builder, nonNativeFunction, C.toNativePointerArray(arguments, false, true), arguments.length, "");
if (hasReturnValue)
{
LLVM.LLVMBuildRet(builder, result);
}
else
{
LLVM.LLVMBuildRetVoid(builder);
}
}
private LLVMTypeRef findNativeType(Type type)
{
if (type instanceof PrimitiveType)
{
LLVMTypeRef nonNullableType;
PrimitiveTypeType primitiveTypeType = ((PrimitiveType) type).getPrimitiveTypeType();
if (primitiveTypeType == PrimitiveTypeType.DOUBLE)
{
nonNullableType = LLVM.LLVMDoubleType();
}
else if (primitiveTypeType == PrimitiveTypeType.FLOAT)
{
nonNullableType = LLVM.LLVMFloatType();
}
else
{
nonNullableType = LLVM.LLVMIntType(primitiveTypeType.getBitCount());
}
if (type.isNullable())
{
// tuple the non-nullable type with a boolean, so that we can tell whether or not the value is null
LLVMTypeRef[] types = new LLVMTypeRef[] {LLVM.LLVMInt1Type(), nonNullableType};
return LLVM.LLVMStructType(C.toNativePointerArray(types, false, true), types.length, false);
}
return nonNullableType;
}
if (type instanceof ArrayType)
{
ArrayType arrayType = (ArrayType) type;
LLVMTypeRef baseType = findNativeType(arrayType.getBaseType());
LLVMTypeRef llvmArray = LLVM.LLVMArrayType(baseType, 0);
LLVMTypeRef[] structureTypes = new LLVMTypeRef[] {LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), llvmArray};
LLVMTypeRef llvmStructure = LLVM.LLVMStructType(C.toNativePointerArray(structureTypes, false, true), 2, false);
return LLVM.LLVMPointerType(llvmStructure, 0);
}
if (type instanceof TupleType)
{
TupleType tupleType = (TupleType) type;
Type[] subTypes = tupleType.getSubTypes();
LLVMTypeRef[] llvmSubTypes = new LLVMTypeRef[subTypes.length];
for (int i = 0; i < subTypes.length; i++)
{
llvmSubTypes[i] = findNativeType(subTypes[i]);
}
LLVMTypeRef nonNullableType = LLVM.LLVMStructType(C.toNativePointerArray(llvmSubTypes, false, true), llvmSubTypes.length, false);
if (tupleType.isNullable())
{
// tuple the non-nullable type with a boolean, so that we can tell whether or not the value is null
LLVMTypeRef[] types = new LLVMTypeRef[] {LLVM.LLVMInt1Type(), nonNullableType};
return LLVM.LLVMStructType(C.toNativePointerArray(types, false, true), types.length, false);
}
return nonNullableType;
}
if (type instanceof NamedType)
{
NamedType namedType = (NamedType) type;
CompoundDefinition compound = namedType.getResolvedDefinition();
Field[] fields = compound.getNonStaticFields();
LLVMTypeRef[] llvmSubTypes = new LLVMTypeRef[fields.length];
for (int i = 0; i < fields.length; i++)
{
llvmSubTypes[i] = findNativeType(fields[i].getType());
}
LLVMTypeRef nonNullableType = LLVM.LLVMStructType(C.toNativePointerArray(llvmSubTypes, false, true), llvmSubTypes.length, false);
if (namedType.isNullable())
{
// tuple the non-nullable type with a boolean, so that we can tell whether or not the value is null
LLVMTypeRef[] types = new LLVMTypeRef[] {LLVM.LLVMInt1Type(), nonNullableType};
return LLVM.LLVMStructType(C.toNativePointerArray(types, false, true), types.length, false);
}
return nonNullableType;
}
if (type instanceof NullType)
{
return LLVM.LLVMStructType(C.toNativePointerArray(new LLVMTypeRef[0], false, true), 0, false);
}
if (type instanceof VoidType)
{
return LLVM.LLVMVoidType();
}
throw new IllegalStateException("Unexpected Type: " + type);
}
private void addConstructorBodies(CompoundDefinition compoundDefinition)
{
for (Constructor constructor : compoundDefinition.getConstructors())
{
LLVMValueRef llvmFunction = getConstructorFunction(constructor);
LLVMBasicBlockRef block = LLVM.LLVMAppendBasicBlock(llvmFunction, "entry");
LLVM.LLVMPositionBuilderAtEnd(builder, block);
// create LLVMValueRefs for all of the variables, including paramters
Set<Variable> allVariables = Resolver.getAllNestedVariables(constructor.getBlock());
Map<Variable, LLVMValueRef> variables = new HashMap<Variable, LLVM.LLVMValueRef>();
for (Variable v : allVariables)
{
LLVMValueRef allocaInst = LLVM.LLVMBuildAlloca(builder, findNativeType(v.getType()), v.getName());
variables.put(v, allocaInst);
}
// store the parameter values to the LLVMValueRefs
for (Parameter p : constructor.getParameters())
{
LLVM.LLVMBuildStore(builder, LLVM.LLVMGetParam(llvmFunction, p.getIndex()), variables.get(p.getVariable()));
}
final LLVMValueRef thisValue = LLVM.LLVMBuildAlloca(builder, findNativeType(new NamedType(false, compoundDefinition)), "this");
buildStatement(constructor.getBlock(), VoidType.VOID_TYPE, llvmFunction, thisValue, variables, new HashMap<BreakableStatement, LLVM.LLVMBasicBlockRef>(), new HashMap<BreakableStatement, LLVM.LLVMBasicBlockRef>(), new Runnable()
{
@Override
public void run()
{
// this will be called whenever a return void is found
// so return the created object
LLVMValueRef result = LLVM.LLVMBuildLoad(builder, thisValue, "");
LLVM.LLVMBuildRet(builder, result);
}
});
if (!constructor.getBlock().stopsExecution())
{
LLVMValueRef result = LLVM.LLVMBuildLoad(builder, thisValue, "");
LLVM.LLVMBuildRet(builder, result);
}
}
}
private void addMethodBodies(CompoundDefinition compoundDefinition)
{
for (Method method : compoundDefinition.getAllMethods())
{
LLVMValueRef llvmFunction = getMethodFunction(method);
LLVMBasicBlockRef block = LLVM.LLVMAppendBasicBlock(llvmFunction, "entry");
LLVM.LLVMPositionBuilderAtEnd(builder, block);
// create LLVMValueRefs for all of the variables, including parameters
Set<Variable> allVariables = Resolver.getAllNestedVariables(method.getBlock());
Map<Variable, LLVMValueRef> variables = new HashMap<Variable, LLVM.LLVMValueRef>();
for (Variable v : allVariables)
{
LLVMValueRef allocaInst = LLVM.LLVMBuildAlloca(builder, findNativeType(v.getType()), v.getName());
variables.put(v, allocaInst);
}
// store the parameter values to the LLVMValueRefs
for (Parameter p : method.getParameters())
{
LLVM.LLVMBuildStore(builder, LLVM.LLVMGetParam(llvmFunction, p.getIndex() + (method.isStatic() ? 0 : 1)), variables.get(p.getVariable()));
}
LLVMValueRef thisValue = method.isStatic() ? null : LLVM.LLVMGetParam(llvmFunction, 0);
buildStatement(method.getBlock(), method.getReturnType(), llvmFunction, thisValue, variables, new HashMap<BreakableStatement, LLVM.LLVMBasicBlockRef>(), new HashMap<BreakableStatement, LLVM.LLVMBasicBlockRef>(), new Runnable()
{
@Override
public void run()
{
// this will be run whenever a return void is found
// so return void
LLVM.LLVMBuildRetVoid(builder);
}
});
// add a "ret void" if control reaches the end of the function
if (!method.getBlock().stopsExecution())
{
LLVM.LLVMBuildRetVoid(builder);
}
}
}
private void buildStatement(Statement statement, Type returnType, LLVMValueRef llvmFunction, LLVMValueRef thisValue, Map<Variable, LLVMValueRef> variables,
Map<BreakableStatement, LLVMBasicBlockRef> breakBlocks, Map<BreakableStatement, LLVMBasicBlockRef> continueBlocks, Runnable returnVoidCallback)
{
if (statement instanceof AssignStatement)
{
AssignStatement assignStatement = (AssignStatement) statement;
Assignee[] assignees = assignStatement.getAssignees();
LLVMValueRef[] llvmAssigneePointers = new LLVMValueRef[assignees.length];
for (int i = 0; i < assignees.length; i++)
{
if (assignees[i] instanceof VariableAssignee)
{
Variable resolvedVariable = ((VariableAssignee) assignees[i]).getResolvedVariable();
if (resolvedVariable instanceof MemberVariable)
{
Field field = ((MemberVariable) resolvedVariable).getField();
LLVMValueRef[] indices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false),
LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), field.getMemberIndex(), false)};
llvmAssigneePointers[i] = LLVM.LLVMBuildGEP(builder, thisValue, C.toNativePointerArray(indices, false, true), indices.length, "");
}
else if (resolvedVariable instanceof GlobalVariable)
{
llvmAssigneePointers[i] = getGlobal((GlobalVariable) resolvedVariable);
}
else
{
llvmAssigneePointers[i] = variables.get(((VariableAssignee) assignees[i]).getResolvedVariable());
}
}
else if (assignees[i] instanceof ArrayElementAssignee)
{
ArrayElementAssignee arrayElementAssignee = (ArrayElementAssignee) assignees[i];
LLVMValueRef array = buildExpression(arrayElementAssignee.getArrayExpression(), llvmFunction, thisValue, variables);
LLVMValueRef dimension = buildExpression(arrayElementAssignee.getDimensionExpression(), llvmFunction, thisValue, variables);
LLVMValueRef convertedDimension = convertType(dimension, arrayElementAssignee.getDimensionExpression().getType(), ArrayLengthMember.ARRAY_LENGTH_TYPE, llvmFunction);
LLVMValueRef[] indices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false),
LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 1, false),
convertedDimension};
llvmAssigneePointers[i] = LLVM.LLVMBuildGEP(builder, array, C.toNativePointerArray(indices, false, true), indices.length, "");
}
else if (assignees[i] instanceof FieldAssignee)
{
FieldAssignee fieldAssignee = (FieldAssignee) assignees[i];
FieldAccessExpression fieldAccessExpression = fieldAssignee.getFieldAccessExpression();
if (fieldAccessExpression.getResolvedMember() instanceof Field)
{
Field field = (Field) fieldAccessExpression.getResolvedMember();
if (field.isStatic())
{
llvmAssigneePointers[i] = getGlobal(field.getGlobalVariable());
}
else
{
LLVMValueRef expressionValue = buildExpression(fieldAccessExpression.getBaseExpression(), llvmFunction, thisValue, variables);
LLVMValueRef[] indices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false),
LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), field.getMemberIndex(), false)};
llvmAssigneePointers[i] = LLVM.LLVMBuildGEP(builder, expressionValue, C.toNativePointerArray(indices, false, true), indices.length, "");
}
}
else
{
throw new IllegalArgumentException("Unknown member assigned to in a FieldAssignee: " + fieldAccessExpression.getResolvedMember());
}
}
else if (assignees[i] instanceof BlankAssignee)
{
// this assignee doesn't actually get assigned to
llvmAssigneePointers[i] = null;
}
else
{
throw new IllegalStateException("Unknown Assignee type: " + assignees[i]);
}
}
if (assignStatement.getExpression() != null)
{
LLVMValueRef value = buildExpression(assignStatement.getExpression(), llvmFunction, thisValue, variables);
if (llvmAssigneePointers.length == 1)
{
if (llvmAssigneePointers[0] != null)
{
LLVMValueRef convertedValue = convertType(value, assignStatement.getExpression().getType(), assignees[0].getResolvedType(), llvmFunction);
Type type = assignees[0].getResolvedType();
if (type instanceof NamedType) // TODO: when this does not cause a warning, add it: && ((NamedType) type).getResolvedDefinition() instanceof CompoundDefinition)
{
// for compound types, we need to load from the result of the expression and store a copy in the new pointer
convertedValue = LLVM.LLVMBuildLoad(builder, convertedValue, "");
}
LLVM.LLVMBuildStore(builder, convertedValue, llvmAssigneePointers[0]);
}
}
else
{
Type[] expressionSubTypes = ((TupleType) assignStatement.getExpression().getType()).getSubTypes();
for (int i = 0; i < llvmAssigneePointers.length; i++)
{
if (llvmAssigneePointers[i] != null)
{
LLVMValueRef extracted = LLVM.LLVMBuildExtractValue(builder, value, i, "");
LLVMValueRef convertedValue = convertType(extracted, expressionSubTypes[i], assignees[i].getResolvedType(), llvmFunction);
// since we are extracting from a tuple here, we do not need to treat compound types differently
LLVM.LLVMBuildStore(builder, convertedValue, llvmAssigneePointers[i]);
}
}
}
}
}
else if (statement instanceof Block)
{
for (Statement s : ((Block) statement).getStatements())
{
buildStatement(s, returnType, llvmFunction, thisValue, variables, breakBlocks, continueBlocks, returnVoidCallback);
}
}
else if (statement instanceof BreakStatement)
{
LLVMBasicBlockRef block = breakBlocks.get(((BreakStatement) statement).getResolvedBreakable());
if (block == null)
{
throw new IllegalStateException("Break statement leads to a null block during code generation: " + statement);
}
LLVM.LLVMBuildBr(builder, block);
}
else if (statement instanceof ContinueStatement)
{
LLVMBasicBlockRef block = continueBlocks.get(((ContinueStatement) statement).getResolvedBreakable());
if (block == null)
{
throw new IllegalStateException("Continue statement leads to a null block during code generation: " + statement);
}
LLVM.LLVMBuildBr(builder, block);
}
else if (statement instanceof ExpressionStatement)
{
buildExpression(((ExpressionStatement) statement).getExpression(), llvmFunction, thisValue, variables);
}
else if (statement instanceof ForStatement)
{
ForStatement forStatement = (ForStatement) statement;
Statement init = forStatement.getInitStatement();
if (init != null)
{
buildStatement(init, returnType, llvmFunction, thisValue, variables, breakBlocks, continueBlocks, returnVoidCallback);
}
Expression conditional = forStatement.getConditional();
Statement update = forStatement.getUpdateStatement();
LLVMBasicBlockRef loopCheck = conditional == null ? null : LLVM.LLVMAppendBasicBlock(llvmFunction, "forLoopCheck");
LLVMBasicBlockRef loopBody = LLVM.LLVMAppendBasicBlock(llvmFunction, "forLoopBody");
LLVMBasicBlockRef loopUpdate = update == null ? null : LLVM.LLVMAppendBasicBlock(llvmFunction, "forLoopUpdate");
// only generate a continuation block if there is a way to get out of the loop
LLVMBasicBlockRef continuationBlock = forStatement.stopsExecution() ? null : LLVM.LLVMAppendBasicBlock(llvmFunction, "afterForLoop");
if (conditional == null)
{
LLVM.LLVMBuildBr(builder, loopBody);
}
else
{
LLVM.LLVMBuildBr(builder, loopCheck);
LLVM.LLVMPositionBuilderAtEnd(builder, loopCheck);
LLVMValueRef conditionResult = buildExpression(conditional, llvmFunction, thisValue, variables);
LLVM.LLVMBuildCondBr(builder, conditionResult, loopBody, continuationBlock);
}
LLVM.LLVMPositionBuilderAtEnd(builder, loopBody);
if (continuationBlock != null)
{
breakBlocks.put(forStatement, continuationBlock);
}
continueBlocks.put(forStatement, loopUpdate == null ? (loopCheck == null ? loopBody : loopCheck) : loopUpdate);
buildStatement(forStatement.getBlock(), returnType, llvmFunction, thisValue, variables, breakBlocks, continueBlocks, returnVoidCallback);
if (!forStatement.getBlock().stopsExecution())
{
LLVM.LLVMBuildBr(builder, loopUpdate == null ? (loopCheck == null ? loopBody : loopCheck) : loopUpdate);
}
if (update != null)
{
LLVM.LLVMPositionBuilderAtEnd(builder, loopUpdate);
buildStatement(update, returnType, llvmFunction, thisValue, variables, breakBlocks, continueBlocks, returnVoidCallback);
if (update.stopsExecution())
{
throw new IllegalStateException("For loop update stops execution before the branch to the loop check: " + update);
}
LLVM.LLVMBuildBr(builder, loopCheck == null ? loopBody : loopCheck);
}
if (continuationBlock != null)
{
LLVM.LLVMPositionBuilderAtEnd(builder, continuationBlock);
}
}
else if (statement instanceof IfStatement)
{
IfStatement ifStatement = (IfStatement) statement;
LLVMValueRef conditional = buildExpression(ifStatement.getExpression(), llvmFunction, thisValue, variables);
LLVMBasicBlockRef thenClause = LLVM.LLVMAppendBasicBlock(llvmFunction, "then");
LLVMBasicBlockRef elseClause = null;
if (ifStatement.getElseClause() != null)
{
elseClause = LLVM.LLVMAppendBasicBlock(llvmFunction, "else");
}
LLVMBasicBlockRef continuation = null;
if (!ifStatement.stopsExecution())
{
continuation = LLVM.LLVMAppendBasicBlock(llvmFunction, "continuation");
}
// build the branch instruction
if (elseClause == null)
{
// if we have no else clause, then a continuation must have been created, since the if statement cannot stop execution
LLVM.LLVMBuildCondBr(builder, conditional, thenClause, continuation);
}
else
{
LLVM.LLVMBuildCondBr(builder, conditional, thenClause, elseClause);
// build the else clause
LLVM.LLVMPositionBuilderAtEnd(builder, elseClause);
buildStatement(ifStatement.getElseClause(), returnType, llvmFunction, thisValue, variables, breakBlocks, continueBlocks, returnVoidCallback);
if (!ifStatement.getElseClause().stopsExecution())
{
LLVM.LLVMBuildBr(builder, continuation);
}
}
// build the then clause
LLVM.LLVMPositionBuilderAtEnd(builder, thenClause);
buildStatement(ifStatement.getThenClause(), returnType, llvmFunction, thisValue, variables, breakBlocks, continueBlocks, returnVoidCallback);
if (!ifStatement.getThenClause().stopsExecution())
{
LLVM.LLVMBuildBr(builder, continuation);
}
if (continuation != null)
{
LLVM.LLVMPositionBuilderAtEnd(builder, continuation);
}
}
else if (statement instanceof PrefixIncDecStatement)
{
PrefixIncDecStatement prefixIncDecStatement = (PrefixIncDecStatement) statement;
Assignee assignee = prefixIncDecStatement.getAssignee();
LLVMValueRef pointer;
if (assignee instanceof VariableAssignee)
{
pointer = variables.get(((VariableAssignee) assignee).getResolvedVariable());
}
else if (assignee instanceof ArrayElementAssignee)
{
ArrayElementAssignee arrayElementAssignee = (ArrayElementAssignee) assignee;
LLVMValueRef array = buildExpression(arrayElementAssignee.getArrayExpression(), llvmFunction, thisValue, variables);
LLVMValueRef dimension = buildExpression(arrayElementAssignee.getDimensionExpression(), llvmFunction, thisValue, variables);
LLVMValueRef convertedDimension = convertType(dimension, arrayElementAssignee.getDimensionExpression().getType(), ArrayLengthMember.ARRAY_LENGTH_TYPE, llvmFunction);
LLVMValueRef[] indices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false),
LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 1, false),
convertedDimension};
pointer = LLVM.LLVMBuildGEP(builder, array, C.toNativePointerArray(indices, false, true), indices.length, "");
}
else
{
// ignore blank assignees, they shouldn't be able to get through variable resolution
throw new IllegalStateException("Unknown Assignee type: " + assignee);
}
LLVMValueRef loaded = LLVM.LLVMBuildLoad(builder, pointer, "");
PrimitiveType type = (PrimitiveType) assignee.getResolvedType();
LLVMValueRef result;
if (type.getPrimitiveTypeType().isFloating())
{
LLVMValueRef one = LLVM.LLVMConstReal(findNativeType(type), 1);
if (prefixIncDecStatement.isIncrement())
{
result = LLVM.LLVMBuildFAdd(builder, loaded, one, "");
}
else
{
result = LLVM.LLVMBuildFSub(builder, loaded, one, "");
}
}
else
{
LLVMValueRef one = LLVM.LLVMConstInt(findNativeType(type), 1, false);
if (prefixIncDecStatement.isIncrement())
{
result = LLVM.LLVMBuildAdd(builder, loaded, one, "");
}
else
{
result = LLVM.LLVMBuildSub(builder, loaded, one, "");
}
}
LLVM.LLVMBuildStore(builder, result, pointer);
}
else if (statement instanceof ReturnStatement)
{
Expression returnedExpression = ((ReturnStatement) statement).getExpression();
if (returnedExpression == null)
{
returnVoidCallback.run();
}
else
{
LLVMValueRef value = buildExpression(returnedExpression, llvmFunction, thisValue, variables);
LLVMValueRef convertedValue = convertType(value, returnedExpression.getType(), returnType, llvmFunction);
if (returnType instanceof NamedType) // TODO: when this does not cause a warning, add it: && ((NamedType) returnType).getResolvedDefinition() instanceof CompoundDefinition)
{
// for compound types, we need to load from the result of the expression and return that value
convertedValue = LLVM.LLVMBuildLoad(builder, convertedValue, "");
}
LLVM.LLVMBuildRet(builder, convertedValue);
}
}
else if (statement instanceof ShorthandAssignStatement)
{
ShorthandAssignStatement shorthandAssignStatement = (ShorthandAssignStatement) statement;
Assignee[] assignees = shorthandAssignStatement.getAssignees();
LLVMValueRef[] llvmAssigneePointers = new LLVMValueRef[assignees.length];
for (int i = 0; i < assignees.length; ++i)
{
if (assignees[i] instanceof VariableAssignee)
{
Variable resolvedVariable = ((VariableAssignee) assignees[i]).getResolvedVariable();
if (resolvedVariable instanceof MemberVariable)
{
Field field = ((MemberVariable) resolvedVariable).getField();
LLVMValueRef[] indices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false),
LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), field.getMemberIndex(), false)};
llvmAssigneePointers[i] = LLVM.LLVMBuildGEP(builder, thisValue, C.toNativePointerArray(indices, false, true), indices.length, "");
}
else if (resolvedVariable instanceof GlobalVariable)
{
llvmAssigneePointers[i] = getGlobal((GlobalVariable) resolvedVariable);
}
else
{
llvmAssigneePointers[i] = variables.get(((VariableAssignee) assignees[i]).getResolvedVariable());
}
}
else if (assignees[i] instanceof ArrayElementAssignee)
{
ArrayElementAssignee arrayElementAssignee = (ArrayElementAssignee) assignees[i];
LLVMValueRef array = buildExpression(arrayElementAssignee.getArrayExpression(), llvmFunction, thisValue, variables);
LLVMValueRef dimension = buildExpression(arrayElementAssignee.getDimensionExpression(), llvmFunction, thisValue, variables);
LLVMValueRef convertedDimension = convertType(dimension, arrayElementAssignee.getDimensionExpression().getType(), ArrayLengthMember.ARRAY_LENGTH_TYPE, llvmFunction);
LLVMValueRef[] indices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false),
LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 1, false),
convertedDimension};
llvmAssigneePointers[i] = LLVM.LLVMBuildGEP(builder, array, C.toNativePointerArray(indices, false, true), indices.length, "");
}
else if (assignees[i] instanceof FieldAssignee)
{
FieldAssignee fieldAssignee = (FieldAssignee) assignees[i];
FieldAccessExpression fieldAccessExpression = fieldAssignee.getFieldAccessExpression();
if (fieldAccessExpression.getResolvedMember() instanceof Field)
{
Field field = (Field) fieldAccessExpression.getResolvedMember();
if (field.isStatic())
{
llvmAssigneePointers[i] = getGlobal(field.getGlobalVariable());
}
else
{
LLVMValueRef expressionValue = buildExpression(fieldAccessExpression.getBaseExpression(), llvmFunction, thisValue, variables);
LLVMValueRef[] indices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false),
LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), field.getMemberIndex(), false)};
llvmAssigneePointers[i] = LLVM.LLVMBuildGEP(builder, expressionValue, C.toNativePointerArray(indices, false, true), indices.length, "");
}
}
else
{
throw new IllegalArgumentException("Unknown member assigned to in a FieldAssignee: " + fieldAccessExpression.getResolvedMember());
}
}
else if (assignees[i] instanceof BlankAssignee)
{
// this assignee doesn't actually get assigned to
llvmAssigneePointers[i] = null;
}
else
{
throw new IllegalStateException("Unknown Assignee type: " + assignees[i]);
}
}
LLVMValueRef result = buildExpression(shorthandAssignStatement.getExpression(), llvmFunction, thisValue, variables);
Type resultType = shorthandAssignStatement.getExpression().getType();
LLVMValueRef[] resultValues = new LLVMValueRef[assignees.length];
Type[] resultValueTypes = new Type[assignees.length];
if (resultType instanceof TupleType && ((TupleType) resultType).getSubTypes().length == assignees.length)
{
Type[] subTypes = ((TupleType) resultType).getSubTypes();
for (int i = 0; i < assignees.length; ++i)
{
if (assignees[i] instanceof BlankAssignee)
{
continue;
}
resultValues[i] = LLVM.LLVMBuildExtractValue(builder, result, i, "");
resultValueTypes[i] = subTypes[i];
}
}
else
{
for (int i = 0; i < assignees.length; ++i)
{
resultValues[i] = result;
resultValueTypes[i] = resultType;
}
}
for (int i = 0; i < assignees.length; ++i)
{
if (llvmAssigneePointers[i] == null)
{
// this is a blank assignee, so don't try to do anything for it
continue;
}
LLVMValueRef leftValue = LLVM.LLVMBuildLoad(builder, llvmAssigneePointers[i], "");
LLVMValueRef rightValue = convertType(resultValues[i], resultValueTypes[i], assignees[i].getResolvedType(), llvmFunction);
PrimitiveTypeType primitiveType = ((PrimitiveType) assignees[i].getResolvedType()).getPrimitiveTypeType();
boolean floating = primitiveType.isFloating();
boolean signed = primitiveType.isSigned();
LLVMValueRef assigneeResult;
switch (shorthandAssignStatement.getOperator())
{
case AND:
assigneeResult = LLVM.LLVMBuildAnd(builder, leftValue, rightValue, "");
break;
case OR:
assigneeResult = LLVM.LLVMBuildOr(builder, leftValue, rightValue, "");
break;
case XOR:
assigneeResult = LLVM.LLVMBuildXor(builder, leftValue, rightValue, "");
break;
case ADD:
assigneeResult = floating ? LLVM.LLVMBuildFAdd(builder, leftValue, rightValue, "") : LLVM.LLVMBuildAdd(builder, leftValue, rightValue, "");
break;
case SUBTRACT:
assigneeResult = floating ? LLVM.LLVMBuildFSub(builder, leftValue, rightValue, "") : LLVM.LLVMBuildSub(builder, leftValue, rightValue, "");
break;
case MULTIPLY:
assigneeResult = floating ? LLVM.LLVMBuildFMul(builder, leftValue, rightValue, "") : LLVM.LLVMBuildMul(builder, leftValue, rightValue, "");
break;
case DIVIDE:
assigneeResult = floating ? LLVM.LLVMBuildFDiv(builder, leftValue, rightValue, "") : signed ? LLVM.LLVMBuildSDiv(builder, leftValue, rightValue, "") : LLVM.LLVMBuildUDiv(builder, leftValue, rightValue, "");
break;
case REMAINDER:
assigneeResult = floating ? LLVM.LLVMBuildFRem(builder, leftValue, rightValue, "") : signed ? LLVM.LLVMBuildSRem(builder, leftValue, rightValue, "") : LLVM.LLVMBuildURem(builder, leftValue, rightValue, "");
break;
case MODULO:
if (floating)
{
LLVMValueRef rem = LLVM.LLVMBuildFRem(builder, leftValue, rightValue, "");
LLVMValueRef add = LLVM.LLVMBuildFAdd(builder, rem, rightValue, "");
assigneeResult = LLVM.LLVMBuildFRem(builder, add, rightValue, "");
}
else if (signed)
{
LLVMValueRef rem = LLVM.LLVMBuildSRem(builder, leftValue, rightValue, "");
LLVMValueRef add = LLVM.LLVMBuildAdd(builder, rem, rightValue, "");
assigneeResult = LLVM.LLVMBuildSRem(builder, add, rightValue, "");
}
else
{
// unsigned modulo is the same as unsigned remainder
assigneeResult = LLVM.LLVMBuildURem(builder, leftValue, rightValue, "");
}
break;
case LEFT_SHIFT:
assigneeResult = LLVM.LLVMBuildShl(builder, leftValue, rightValue, "");
break;
case RIGHT_SHIFT:
assigneeResult = signed ? LLVM.LLVMBuildAShr(builder, leftValue, rightValue, "") : LLVM.LLVMBuildLShr(builder, leftValue, rightValue, "");
break;
default:
throw new IllegalStateException("Unknown shorthand assignment operator: " + shorthandAssignStatement.getOperator());
}
LLVM.LLVMBuildStore(builder, assigneeResult, llvmAssigneePointers[i]);
}
}
else if (statement instanceof WhileStatement)
{
WhileStatement whileStatement = (WhileStatement) statement;
LLVMBasicBlockRef loopCheck = LLVM.LLVMAppendBasicBlock(llvmFunction, "whileLoopCheck");
LLVM.LLVMBuildBr(builder, loopCheck);
LLVM.LLVMPositionBuilderAtEnd(builder, loopCheck);
LLVMValueRef conditional = buildExpression(whileStatement.getExpression(), llvmFunction, thisValue, variables);
LLVMBasicBlockRef loopBodyBlock = LLVM.LLVMAppendBasicBlock(llvmFunction, "whileLoopBody");
LLVMBasicBlockRef afterLoopBlock = LLVM.LLVMAppendBasicBlock(llvmFunction, "afterWhileLoop");
LLVM.LLVMBuildCondBr(builder, conditional, loopBodyBlock, afterLoopBlock);
LLVM.LLVMPositionBuilderAtEnd(builder, loopBodyBlock);
// add the while statement's afterLoop block to the breakBlocks map before it's statement is built
breakBlocks.put(whileStatement, afterLoopBlock);
continueBlocks.put(whileStatement, loopCheck);
buildStatement(whileStatement.getStatement(), returnType, llvmFunction, thisValue, variables, breakBlocks, continueBlocks, returnVoidCallback);
if (!whileStatement.getStatement().stopsExecution())
{
LLVM.LLVMBuildBr(builder, loopCheck);
}
LLVM.LLVMPositionBuilderAtEnd(builder, afterLoopBlock);
}
}
private LLVMValueRef convertType(LLVMValueRef value, Type from, Type to, LLVMValueRef llvmFunction)
{
if (from.isEquivalent(to))
{
return value;
}
if (from instanceof PrimitiveType && to instanceof PrimitiveType)
{
return convertPrimitiveType(value, (PrimitiveType) from, (PrimitiveType) to);
}
if (from instanceof ArrayType && to instanceof ArrayType)
{
// array casts are illegal unless from and to types are the same, so they must have the same type
// nullability will be checked by the type checker, but has no effect on the native type, so we do not need to do anything special here
// if from and to are nullable and value is null, then the value we are returning here is undefined
// TODO: if from and to are nullable and value is null, throw an exception here instead of having undefined behaviour
return value;
}
if (from instanceof NamedType && to instanceof NamedType) // TODO: when it doesn't cause a warning, add: &&
//((NamedType) from).getResolvedDefinition() instanceof CompoundDefinition &&
//((NamedType) to).getResolvedDefinition() instanceof CompoundDefinition)
{
// compound type casts are illegal unless from and to types are the same, so they must have the same type
LLVMValueRef loadedValue = LLVM.LLVMBuildLoad(builder, value, "");
LLVMValueRef isNotNullValue = null;
LLVMValueRef namedValue = loadedValue;
if (from.isNullable())
{
isNotNullValue = LLVM.LLVMBuildExtractValue(builder, loadedValue, 0, "");
namedValue = LLVM.LLVMBuildExtractValue(builder, loadedValue, 1, "");
}
LLVMValueRef result;
if (to.isNullable())
{
result = LLVM.LLVMGetUndef(findNativeType(to));
if (from.isNullable())
{
result = LLVM.LLVMBuildInsertValue(builder, result, isNotNullValue, 0, "");
}
else
{
// set the flag to one to indicate that this value is not null
result = LLVM.LLVMBuildInsertValue(builder, result, LLVM.LLVMConstInt(LLVM.LLVMInt1Type(), 1, false), 0, "");
}
result = LLVM.LLVMBuildInsertValue(builder, result, namedValue, 1, "");
}
else
{
// return the primitive value directly, since the to type is not nullable
// if from is nullable and value is null, then the value we are returning here is undefined
// TODO: if from is nullable and value is null, throw an exception here instead of having undefined behaviour
result = namedValue;
}
// for compound types, we need to return a pointer to the value
// so build an alloca in the entry block
LLVMBasicBlockRef currentBlock = LLVM.LLVMGetInsertBlock(builder);
LLVM.LLVMPositionBuilderBefore(builder, LLVM.LLVMGetFirstInstruction(LLVM.LLVMGetEntryBasicBlock(llvmFunction)));
LLVMValueRef alloca = LLVM.LLVMBuildAlloca(builder, findNativeType(to), "");
LLVM.LLVMPositionBuilderAtEnd(builder, currentBlock);
LLVM.LLVMBuildStore(builder, result, alloca);
return alloca;
}
if (from instanceof TupleType && !(to instanceof TupleType))
{
TupleType fromTuple = (TupleType) from;
if (fromTuple.getSubTypes().length != 1)
{
throw new IllegalArgumentException("Cannot convert from a " + from + " to a " + to);
}
if (from.isNullable())
{
// extract the value of the tuple from the nullable structure
// if from is nullable and value is null, then the value we are using here is undefined
// TODO: if from is nullable and value is null, throw an exception here instead of having undefined behaviour
value = LLVM.LLVMBuildExtractValue(builder, value, 1, "");
}
return LLVM.LLVMBuildExtractValue(builder, value, 0, "");
}
if (!(from instanceof TupleType) && to instanceof TupleType)
{
TupleType toTuple = (TupleType) to;
if (toTuple.getSubTypes().length != 1)
{
throw new IllegalArgumentException("Cannot convert from a " + from + " to a " + to);
}
LLVMValueRef tupledValue = LLVM.LLVMGetUndef(findNativeType(new TupleType(false, toTuple.getSubTypes(), null)));
tupledValue = LLVM.LLVMBuildInsertValue(builder, tupledValue, value, 0, "");
if (to.isNullable())
{
LLVMValueRef result = LLVM.LLVMGetUndef(findNativeType(to));
result = LLVM.LLVMBuildInsertValue(builder, result, LLVM.LLVMConstInt(LLVM.LLVMInt1Type(), 1, false), 0, "");
return LLVM.LLVMBuildInsertValue(builder, result, tupledValue, 1, "");
}
return tupledValue;
}
if (from instanceof TupleType && to instanceof TupleType)
{
TupleType fromTuple = (TupleType) from;
TupleType toTuple = (TupleType) to;
if (fromTuple.isEquivalent(toTuple))
{
return value;
}
Type[] fromSubTypes = fromTuple.getSubTypes();
Type[] toSubTypes = toTuple.getSubTypes();
if (fromSubTypes.length != toSubTypes.length)
{
throw new IllegalArgumentException("Cannot convert from a " + from + " to a " + to);
}
boolean subTypesEquivalent = true;
for (int i = 0; i < fromSubTypes.length; ++i)
{
if (!fromSubTypes[i].isEquivalent(toSubTypes[i]))
{
subTypesEquivalent = false;
break;
}
}
if (subTypesEquivalent)
{
// just convert the nullability
if (from.isNullable() && !to.isNullable())
{
// extract the value of the tuple from the nullable structure
// if from is nullable and value is null, then the value we are using here is undefined
// TODO: if from is nullable and value is null, throw an exception here instead of having undefined behaviour
return LLVM.LLVMBuildExtractValue(builder, value, 1, "");
}
if (!from.isNullable() && to.isNullable())
{
LLVMValueRef result = LLVM.LLVMGetUndef(findNativeType(to));
// set the flag to one to indicate that this value is not null
result = LLVM.LLVMBuildInsertValue(builder, result, LLVM.LLVMConstInt(LLVM.LLVMInt1Type(), 1, false), 0, "");
return LLVM.LLVMBuildInsertValue(builder, result, value, 1, "");
}
throw new IllegalArgumentException("Unable to convert from a " + from + " to a " + to + " - their sub types and nullability are equivalent, but the types themselves are not");
}
LLVMValueRef isNotNullValue = null;
LLVMValueRef tupleValue = value;
if (from.isNullable())
{
isNotNullValue = LLVM.LLVMBuildExtractValue(builder, value, 0, "");
tupleValue = LLVM.LLVMBuildExtractValue(builder, value, 1, "");
}
LLVMValueRef currentValue = LLVM.LLVMGetUndef(findNativeType(toTuple));
for (int i = 0; i < fromTuple.getSubTypes().length; i++)
{
LLVMValueRef current = LLVM.LLVMBuildExtractValue(builder, tupleValue, i, "");
LLVMValueRef converted = convertType(current, fromSubTypes[i], toSubTypes[i], llvmFunction);
currentValue = LLVM.LLVMBuildInsertValue(builder, currentValue, converted, i, "");
}
if (to.isNullable())
{
LLVMValueRef result = LLVM.LLVMGetUndef(findNativeType(to));
if (from.isNullable())
{
result = LLVM.LLVMBuildInsertValue(builder, result, isNotNullValue, 0, "");
}
else
{
// set the flag to one to indicate that this value is not null
result = LLVM.LLVMBuildInsertValue(builder, result, LLVM.LLVMConstInt(LLVM.LLVMInt1Type(), 1, false), 0, "");
}
return LLVM.LLVMBuildInsertValue(builder, result, currentValue, 1, "");
}
// return the primitive value directly, since the to type is not nullable
// if from is nullable and value is null, then the value we are using here is undefined
// TODO: if from is nullable and value is null, throw an exception here instead of having undefined behaviour
return currentValue;
}
throw new IllegalArgumentException("Unknown type conversion, from '" + from + "' to '" + to + "'");
}
private LLVMValueRef convertPrimitiveType(LLVMValueRef value, PrimitiveType from, PrimitiveType to)
{
PrimitiveTypeType fromType = from.getPrimitiveTypeType();
PrimitiveTypeType toType = to.getPrimitiveTypeType();
if (fromType == toType && from.isNullable() == to.isNullable())
{
return value;
}
LLVMValueRef isNotNullValue = null;
LLVMValueRef primitiveValue = value;
if (from.isNullable())
{
isNotNullValue = LLVM.LLVMBuildExtractValue(builder, value, 0, "");
primitiveValue = LLVM.LLVMBuildExtractValue(builder, value, 1, "");
}
// perform the conversion
LLVMTypeRef toNativeType = findNativeType(new PrimitiveType(false, toType, null));
if (fromType == toType)
{
// do not alter primitiveValue, we only need to change the nullability
}
else if (fromType.isFloating() && toType.isFloating())
{
primitiveValue = LLVM.LLVMBuildFPCast(builder, primitiveValue, toNativeType, "");
}
else if (fromType.isFloating() && !toType.isFloating())
{
if (toType.isSigned())
{
primitiveValue = LLVM.LLVMBuildFPToSI(builder, primitiveValue, toNativeType, "");
}
else
{
primitiveValue = LLVM.LLVMBuildFPToUI(builder, primitiveValue, toNativeType, "");
}
}
else if (!fromType.isFloating() && toType.isFloating())
{
if (fromType.isSigned())
{
primitiveValue = LLVM.LLVMBuildSIToFP(builder, primitiveValue, toNativeType, "");
}
else
{
primitiveValue = LLVM.LLVMBuildUIToFP(builder, primitiveValue, toNativeType, "");
}
}
// both integer types, so perform a sign-extend, zero-extend, or truncation
else if (fromType.getBitCount() > toType.getBitCount())
{
primitiveValue = LLVM.LLVMBuildTrunc(builder, primitiveValue, toNativeType, "");
}
else if (fromType.getBitCount() == toType.getBitCount() && fromType.isSigned() != toType.isSigned())
{
primitiveValue = LLVM.LLVMBuildBitCast(builder, primitiveValue, toNativeType, "");
}
// the value needs extending, so decide whether to do a sign-extend or a zero-extend based on whether the from type is signed
else if (fromType.isSigned())
{
primitiveValue = LLVM.LLVMBuildSExt(builder, primitiveValue, toNativeType, "");
}
else
{
primitiveValue = LLVM.LLVMBuildZExt(builder, primitiveValue, toNativeType, "");
}
// pack up the result before returning it
if (to.isNullable())
{
LLVMValueRef result = LLVM.LLVMGetUndef(findNativeType(to));
if (from.isNullable())
{
result = LLVM.LLVMBuildInsertValue(builder, result, isNotNullValue, 0, "");
}
else
{
// set the flag to one to indicate that this value is not null
result = LLVM.LLVMBuildInsertValue(builder, result, LLVM.LLVMConstInt(LLVM.LLVMInt1Type(), 1, false), 0, "");
}
return LLVM.LLVMBuildInsertValue(builder, result, primitiveValue, 1, "");
}
// return the primitive value directly, since the to type is not nullable
// if from was null, then the value we are returning here is undefined
// TODO: if from was null, throw an exception here instead of having undefined behaviour
return primitiveValue;
}
private int getPredicate(ComparisonOperator operator, boolean floating, boolean signed)
{
if (floating)
{
switch (operator)
{
case EQUAL:
return LLVM.LLVMRealPredicate.LLVMRealOEQ;
case LESS_THAN:
return LLVM.LLVMRealPredicate.LLVMRealOLT;
case LESS_THAN_EQUAL:
return LLVM.LLVMRealPredicate.LLVMRealOLE;
case MORE_THAN:
return LLVM.LLVMRealPredicate.LLVMRealOGT;
case MORE_THAN_EQUAL:
return LLVM.LLVMRealPredicate.LLVMRealOGE;
case NOT_EQUAL:
return LLVM.LLVMRealPredicate.LLVMRealONE;
}
}
else
{
switch (operator)
{
case EQUAL:
return LLVM.LLVMIntPredicate.LLVMIntEQ;
case LESS_THAN:
return signed ? LLVM.LLVMIntPredicate.LLVMIntSLT : LLVM.LLVMIntPredicate.LLVMIntULT;
case LESS_THAN_EQUAL:
return signed ? LLVM.LLVMIntPredicate.LLVMIntSLE : LLVM.LLVMIntPredicate.LLVMIntULE;
case MORE_THAN:
return signed ? LLVM.LLVMIntPredicate.LLVMIntSGT : LLVM.LLVMIntPredicate.LLVMIntUGT;
case MORE_THAN_EQUAL:
return signed ? LLVM.LLVMIntPredicate.LLVMIntSGE : LLVM.LLVMIntPredicate.LLVMIntUGE;
case NOT_EQUAL:
return LLVM.LLVMIntPredicate.LLVMIntNE;
}
}
throw new IllegalArgumentException("Unknown predicate '" + operator + "'");
}
private LLVMValueRef buildArrayCreation(LLVMValueRef llvmFunction, LLVMValueRef[] llvmLengths, ArrayType type)
{
LLVMTypeRef llvmArrayType = findNativeType(type);
LLVMValueRef[] indices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false), // go into the pointer to the {i32, [0 x <type>]}
LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 1, false), // go into the structure to get the [0 x <type>]
llvmLengths[0]}; // go length elements along the array, to get the byte directly after the whole structure, which is also our size
LLVMValueRef llvmArraySize = LLVM.LLVMBuildGEP(builder, LLVM.LLVMConstNull(llvmArrayType), C.toNativePointerArray(indices, false, true), indices.length, "");
LLVMValueRef llvmSize = LLVM.LLVMBuildPtrToInt(builder, llvmArraySize, LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), "");
// call calloc to allocate the memory and initialise it to a string of zeros
LLVMValueRef[] arguments = new LLVMValueRef[] {llvmSize, LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 1, false)};
LLVMValueRef memoryPointer = LLVM.LLVMBuildCall(builder, callocFunction, C.toNativePointerArray(arguments, false, true), arguments.length, "");
LLVMValueRef allocatedPointer = LLVM.LLVMBuildBitCast(builder, memoryPointer, llvmArrayType, "");
LLVMValueRef[] sizeIndices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false),
LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false)};
LLVMValueRef sizeElementPointer = LLVM.LLVMBuildGEP(builder, allocatedPointer, C.toNativePointerArray(sizeIndices, false, true), sizeIndices.length, "");
LLVM.LLVMBuildStore(builder, llvmLengths[0], sizeElementPointer);
if (llvmLengths.length > 1)
{
// build a loop to create all of the elements of this array by recursively calling buildArrayCreation()
ArrayType subType = (ArrayType) type.getBaseType();
LLVMBasicBlockRef startBlock = LLVM.LLVMGetInsertBlock(builder);
LLVMBasicBlockRef loopCheckBlock = LLVM.LLVMAppendBasicBlock(llvmFunction, "arrayCreationCheck");
LLVMBasicBlockRef loopBlock = LLVM.LLVMAppendBasicBlock(llvmFunction, "arrayCreation");
LLVMBasicBlockRef exitBlock = LLVM.LLVMAppendBasicBlock(llvmFunction, "arrayCreationEnd");
LLVM.LLVMBuildBr(builder, loopCheckBlock);
LLVM.LLVMPositionBuilderAtEnd(builder, loopCheckBlock);
LLVMValueRef phiNode = LLVM.LLVMBuildPhi(builder, LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), "arrayCounter");
LLVMValueRef breakBoolean = LLVM.LLVMBuildICmp(builder, LLVM.LLVMIntPredicate.LLVMIntULT, phiNode, llvmLengths[0], "");
LLVM.LLVMBuildCondBr(builder, breakBoolean, loopBlock, exitBlock);
LLVM.LLVMPositionBuilderAtEnd(builder, loopBlock);
// recurse to create this element of the array
LLVMValueRef[] subLengths = new LLVMValueRef[llvmLengths.length - 1];
System.arraycopy(llvmLengths, 1, subLengths, 0, subLengths.length);
LLVMValueRef subArray = buildArrayCreation(llvmFunction, subLengths, subType);
// find the indices for the current location in the array
LLVMValueRef[] assignmentIndices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false),
LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 1, false),
phiNode};
LLVMValueRef elementPointer = LLVM.LLVMBuildGEP(builder, allocatedPointer, C.toNativePointerArray(assignmentIndices, false, true), assignmentIndices.length, "");
LLVM.LLVMBuildStore(builder, subArray, elementPointer);
// add the incoming values to the phi node
LLVMValueRef nextCounterValue = LLVM.LLVMBuildAdd(builder, phiNode, LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 1, false), "");
LLVMValueRef[] incomingValues = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false), nextCounterValue};
LLVMBasicBlockRef[] incomingBlocks = new LLVMBasicBlockRef[] {startBlock, LLVM.LLVMGetInsertBlock(builder)};
LLVM.LLVMAddIncoming(phiNode, C.toNativePointerArray(incomingValues, false, true), C.toNativePointerArray(incomingBlocks, false, true), 2);
LLVM.LLVMBuildBr(builder, loopCheckBlock);
LLVM.LLVMPositionBuilderAtEnd(builder, exitBlock);
}
return allocatedPointer;
}
private LLVMValueRef buildExpression(Expression expression, LLVMValueRef llvmFunction, LLVMValueRef thisValue, Map<Variable, LLVMValueRef> variables)
{
if (expression instanceof ArithmeticExpression)
{
ArithmeticExpression arithmeticExpression = (ArithmeticExpression) expression;
LLVMValueRef left = buildExpression(arithmeticExpression.getLeftSubExpression(), llvmFunction, thisValue, variables);
LLVMValueRef right = buildExpression(arithmeticExpression.getRightSubExpression(), llvmFunction, thisValue, variables);
PrimitiveType leftType = (PrimitiveType) arithmeticExpression.getLeftSubExpression().getType();
PrimitiveType rightType = (PrimitiveType) arithmeticExpression.getRightSubExpression().getType();
// cast if necessary
PrimitiveType resultType = (PrimitiveType) arithmeticExpression.getType();
left = convertPrimitiveType(left, leftType, resultType);
right = convertPrimitiveType(right, rightType, resultType);
boolean floating = resultType.getPrimitiveTypeType().isFloating();
boolean signed = resultType.getPrimitiveTypeType().isSigned();
switch (arithmeticExpression.getOperator())
{
case ADD:
return floating ? LLVM.LLVMBuildFAdd(builder, left, right, "") : LLVM.LLVMBuildAdd(builder, left, right, "");
case SUBTRACT:
return floating ? LLVM.LLVMBuildFSub(builder, left, right, "") : LLVM.LLVMBuildSub(builder, left, right, "");
case MULTIPLY:
return floating ? LLVM.LLVMBuildFMul(builder, left, right, "") : LLVM.LLVMBuildMul(builder, left, right, "");
case DIVIDE:
return floating ? LLVM.LLVMBuildFDiv(builder, left, right, "") : signed ? LLVM.LLVMBuildSDiv(builder, left, right, "") : LLVM.LLVMBuildUDiv(builder, left, right, "");
case REMAINDER:
return floating ? LLVM.LLVMBuildFRem(builder, left, right, "") : signed ? LLVM.LLVMBuildSRem(builder, left, right, "") : LLVM.LLVMBuildURem(builder, left, right, "");
case MODULO:
if (floating)
{
LLVMValueRef rem = LLVM.LLVMBuildFRem(builder, left, right, "");
LLVMValueRef add = LLVM.LLVMBuildFAdd(builder, rem, right, "");
return LLVM.LLVMBuildFRem(builder, add, right, "");
}
if (signed)
{
LLVMValueRef rem = LLVM.LLVMBuildSRem(builder, left, right, "");
LLVMValueRef add = LLVM.LLVMBuildAdd(builder, rem, right, "");
return LLVM.LLVMBuildSRem(builder, add, right, "");
}
// unsigned modulo is the same as unsigned remainder
return LLVM.LLVMBuildURem(builder, left, right, "");
}
throw new IllegalArgumentException("Unknown arithmetic operator: " + arithmeticExpression.getOperator());
}
if (expression instanceof ArrayAccessExpression)
{
ArrayAccessExpression arrayAccessExpression = (ArrayAccessExpression) expression;
LLVMValueRef arrayValue = buildExpression(arrayAccessExpression.getArrayExpression(), llvmFunction, thisValue, variables);
LLVMValueRef dimensionValue = buildExpression(arrayAccessExpression.getDimensionExpression(), llvmFunction, thisValue, variables);
LLVMValueRef convertedDimensionValue = convertType(dimensionValue, arrayAccessExpression.getDimensionExpression().getType(), ArrayLengthMember.ARRAY_LENGTH_TYPE, llvmFunction);
LLVMValueRef[] indices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false),
LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 1, false),
convertedDimensionValue};
LLVMValueRef elementPointer = LLVM.LLVMBuildGEP(builder, arrayValue, C.toNativePointerArray(indices, false, true), indices.length, "");
ArrayType arrayType = (ArrayType) arrayAccessExpression.getArrayExpression().getType();
if (arrayType.getBaseType() instanceof NamedType) // TODO (when it doesn't cause a warning): && ((NamedType) arrayAccessExpression.getType()).getResolvedDefinition() instanceof CompoundDefinition)
{
// for compound types, we do not need to load anything here
return convertType(elementPointer, arrayType.getBaseType(), arrayAccessExpression.getType(), llvmFunction);
}
LLVMValueRef value = LLVM.LLVMBuildLoad(builder, elementPointer, "");
return convertType(value, arrayType.getBaseType(), arrayAccessExpression.getType(), llvmFunction);
}
if (expression instanceof ArrayCreationExpression)
{
ArrayCreationExpression arrayCreationExpression = (ArrayCreationExpression) expression;
ArrayType type = arrayCreationExpression.getType();
Expression[] dimensionExpressions = arrayCreationExpression.getDimensionExpressions();
if (dimensionExpressions == null)
{
Expression[] valueExpressions = arrayCreationExpression.getValueExpressions();
LLVMValueRef llvmLength = LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), valueExpressions.length, false);
LLVMValueRef array = buildArrayCreation(llvmFunction, new LLVMValueRef[] {llvmLength}, type);
for (int i = 0; i < valueExpressions.length; i++)
{
LLVMValueRef expressionValue = buildExpression(valueExpressions[i], llvmFunction, thisValue, variables);
LLVMValueRef convertedValue = convertType(expressionValue, valueExpressions[i].getType(), type.getBaseType(), llvmFunction);
Type valueType = valueExpressions[i].getType();
if (valueType instanceof NamedType) // TODO: when it doesn't cause a warning, add: && ((NamedType) valueType).getResolvedDefinition() instanceof CompoundDefinition)
{
convertedValue = LLVM.LLVMBuildLoad(builder, convertedValue, "");
}
LLVMValueRef[] indices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false),
LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 1, false),
LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), i, false)};
LLVMValueRef elementPointer = LLVM.LLVMBuildGEP(builder, array, C.toNativePointerArray(indices, false, true), indices.length, "");
LLVM.LLVMBuildStore(builder, convertedValue, elementPointer);
}
return array;
}
LLVMValueRef[] llvmLengths = new LLVMValueRef[dimensionExpressions.length];
for (int i = 0; i < llvmLengths.length; i++)
{
LLVMValueRef expressionValue = buildExpression(dimensionExpressions[i], llvmFunction, thisValue, variables);
llvmLengths[i] = convertType(expressionValue, dimensionExpressions[i].getType(), ArrayLengthMember.ARRAY_LENGTH_TYPE, llvmFunction);
}
return buildArrayCreation(llvmFunction, llvmLengths, type);
}
if (expression instanceof BitwiseNotExpression)
{
LLVMValueRef value = buildExpression(((BitwiseNotExpression) expression).getExpression(), llvmFunction, thisValue, variables);
return LLVM.LLVMBuildNot(builder, value, "");
}
if (expression instanceof BooleanLiteralExpression)
{
return LLVM.LLVMConstInt(LLVM.LLVMInt1Type(), ((BooleanLiteralExpression) expression).getValue() ? 1 : 0, false);
}
if (expression instanceof BooleanNotExpression)
{
LLVMValueRef value = buildExpression(((BooleanNotExpression) expression).getExpression(), llvmFunction, thisValue, variables);
return LLVM.LLVMBuildNot(builder, value, "");
}
if (expression instanceof BracketedExpression)
{
return buildExpression(((BracketedExpression) expression).getExpression(), llvmFunction, thisValue, variables);
}
if (expression instanceof CastExpression)
{
CastExpression castExpression = (CastExpression) expression;
LLVMValueRef value = buildExpression(castExpression.getExpression(), llvmFunction, thisValue, variables);
return convertType(value, castExpression.getExpression().getType(), castExpression.getType(), llvmFunction);
}
if (expression instanceof ComparisonExpression)
{
ComparisonExpression comparisonExpression = (ComparisonExpression) expression;
LLVMValueRef left = buildExpression(comparisonExpression.getLeftSubExpression(), llvmFunction, thisValue, variables);
LLVMValueRef right = buildExpression(comparisonExpression.getRightSubExpression(), llvmFunction, thisValue, variables);
PrimitiveType leftType = (PrimitiveType) comparisonExpression.getLeftSubExpression().getType();
PrimitiveType rightType = (PrimitiveType) comparisonExpression.getRightSubExpression().getType();
// cast if necessary
PrimitiveType resultType = comparisonExpression.getComparisonType();
if (resultType == null)
{
PrimitiveTypeType leftTypeType = leftType.getPrimitiveTypeType();
PrimitiveTypeType rightTypeType = rightType.getPrimitiveTypeType();
if (!leftTypeType.isFloating() && !rightTypeType.isFloating() &&
leftTypeType.getBitCount() == rightTypeType.getBitCount() &&
leftTypeType.isSigned() != rightTypeType.isSigned())
{
// compare the signed and non-signed integers as (bitCount + 1) bit numbers, since they will not fit in bitCount bits
LLVMTypeRef comparisonType = LLVM.LLVMIntType(leftType.getPrimitiveTypeType().getBitCount() + 1);
if (leftTypeType.isSigned())
{
left = LLVM.LLVMBuildSExt(builder, left, comparisonType, "");
right = LLVM.LLVMBuildZExt(builder, right, comparisonType, "");
}
else
{
left = LLVM.LLVMBuildZExt(builder, left, comparisonType, "");
right = LLVM.LLVMBuildSExt(builder, right, comparisonType, "");
}
return LLVM.LLVMBuildICmp(builder, getPredicate(comparisonExpression.getOperator(), false, true), left, right, "");
}
throw new IllegalArgumentException("Unknown result type, unable to generate comparison expression: " + expression);
}
left = convertPrimitiveType(left, leftType, resultType);
right = convertPrimitiveType(right, rightType, resultType);
if (resultType.getPrimitiveTypeType().isFloating())
{
return LLVM.LLVMBuildFCmp(builder, getPredicate(comparisonExpression.getOperator(), true, true), left, right, "");
}
return LLVM.LLVMBuildICmp(builder, getPredicate(comparisonExpression.getOperator(), false, resultType.getPrimitiveTypeType().isSigned()), left, right, "");
}
if (expression instanceof FieldAccessExpression)
{
FieldAccessExpression fieldAccessExpression = (FieldAccessExpression) expression;
Member member = fieldAccessExpression.getResolvedMember();
if (member instanceof ArrayLengthMember)
{
LLVMValueRef array = buildExpression(fieldAccessExpression.getBaseExpression(), llvmFunction, thisValue, variables);
LLVMValueRef[] sizeIndices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false),
LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false)};
LLVMValueRef elementPointer = LLVM.LLVMBuildGEP(builder, array, C.toNativePointerArray(sizeIndices, false, true), sizeIndices.length, "");
return LLVM.LLVMBuildLoad(builder, elementPointer, "");
}
if (member instanceof Field)
{
Field field = (Field) member;
if (field.isStatic())
{
LLVMValueRef global = getGlobal(field.getGlobalVariable());
if (field.getType() instanceof NamedType) // TODO (when it doesn't cause a warning): && ((NamedType) field.getType()).getResolvedDefinition() instanceof CompoundDefinition)
{
// for compound types, we do not need to load anything here
return global;
}
return LLVM.LLVMBuildLoad(builder, global, "");
}
LLVMValueRef baseValue = buildExpression(fieldAccessExpression.getBaseExpression(), llvmFunction, thisValue, variables);
LLVMValueRef[] indices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false),
LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), field.getMemberIndex(), false)};
LLVMValueRef elementPointer = LLVM.LLVMBuildGEP(builder, baseValue, C.toNativePointerArray(indices, false, true), indices.length, "");
if (field.getType() instanceof NamedType) // TODO (when it doesn't cause a warning): && ((NamedType) field.getType()).getResolvedDefinition() instanceof CompoundDefinition)
{
// for compound types, we do not need to load anything here
return elementPointer;
}
return LLVM.LLVMBuildLoad(builder, elementPointer, "");
}
}
if (expression instanceof FloatingLiteralExpression)
{
double value = Double.parseDouble(((FloatingLiteralExpression) expression).getLiteral().toString());
return LLVM.LLVMConstReal(findNativeType(expression.getType()), value);
}
if (expression instanceof FunctionCallExpression)
{
FunctionCallExpression functionExpression = (FunctionCallExpression) expression;
Constructor resolvedConstructor = functionExpression.getResolvedConstructor();
Method resolvedMethod = functionExpression.getResolvedMethod();
Expression resolvedBaseExpression = functionExpression.getResolvedBaseExpression();
Type[] parameterTypes;
Type returnType;
LLVMValueRef llvmResolvedFunction;
if (resolvedConstructor != null)
{
Parameter[] params = resolvedConstructor.getParameters();
parameterTypes = new Type[params.length];
for (int i = 0; i < params.length; ++i)
{
parameterTypes[i] = params[i].getType();
}
returnType = new NamedType(false, resolvedConstructor.getContainingDefinition());
llvmResolvedFunction = getConstructorFunction(resolvedConstructor);
}
else if (resolvedMethod != null)
{
Parameter[] params = resolvedMethod.getParameters();
parameterTypes = new Type[params.length];
for (int i = 0; i < params.length; ++i)
{
parameterTypes[i] = params[i].getType();
}
returnType = resolvedMethod.getReturnType();
llvmResolvedFunction = getMethodFunction(resolvedMethod);
}
else if (resolvedBaseExpression != null)
{
FunctionType baseType = (FunctionType) resolvedBaseExpression.getType();
parameterTypes = baseType.getParameterTypes();
returnType = baseType.getReturnType();
llvmResolvedFunction = null;
}
else
{
throw new IllegalArgumentException("Unresolved function call expression: " + functionExpression);
}
LLVMValueRef callee = null;
if (resolvedBaseExpression != null)
{
callee = buildExpression(resolvedBaseExpression, llvmFunction, thisValue, variables);
}
Expression[] arguments = functionExpression.getArguments();
LLVMValueRef[] values = new LLVMValueRef[arguments.length];
for (int i = 0; i < arguments.length; i++)
{
LLVMValueRef arg = buildExpression(arguments[i], llvmFunction, thisValue, variables);
values[i] = convertType(arg, arguments[i].getType(), parameterTypes[i], llvmFunction);
if (parameterTypes[i] instanceof NamedType) // TODO: when it doesn't cause a warning, add: && ((NamedType) parameterTypes[i]).getResolvedDefinition() instanceof CompoundDefinition)
{
// for compound types, we need to pass the value itself, not the pointer to the value
values[i] = LLVM.LLVMBuildLoad(builder, values[i], "");
}
}
LLVMValueRef result;
if (resolvedConstructor != null)
{
result = LLVM.LLVMBuildCall(builder, llvmResolvedFunction, C.toNativePointerArray(values, false, true), values.length, "");
}
else if (resolvedMethod != null)
{
LLVMValueRef[] realArguments;
if (resolvedMethod.isStatic())
{
realArguments = values;
}
else
{
realArguments = new LLVMValueRef[values.length + 1];
realArguments[0] = callee;
if (callee == null)
{
realArguments[0] = thisValue;
}
System.arraycopy(values, 0, realArguments, 1, values.length);
}
result = LLVM.LLVMBuildCall(builder, llvmResolvedFunction, C.toNativePointerArray(realArguments, false, true), realArguments.length, "");
}
else if (resolvedBaseExpression != null)
{
// callee here is actually a tuple of an opaque pointer and a function type, where the first argument to the function is the opaque pointer
LLVMValueRef firstArgument = LLVM.LLVMBuildExtractValue(builder, callee, 0, "");
LLVMValueRef calleeFunction = LLVM.LLVMBuildExtractValue(builder, callee, 1, "");
LLVMValueRef[] realArguments = new LLVMValueRef[values.length + 1];
realArguments[0] = firstArgument;
System.arraycopy(values, 0, realArguments, 1, values.length);
result = LLVM.LLVMBuildCall(builder, calleeFunction, C.toNativePointerArray(realArguments, false, true), realArguments.length, "");
}
else
{
throw new IllegalArgumentException("Unresolved function call expression: " + functionExpression);
}
if (returnType instanceof NamedType) // TODO (when it doesn't cause a warning): && ((NamedType) returnType).getResolvedDefinition() instanceof CompoundDefinition)
{
// for compound types, we need to get a pointer from this returned value
// so build an alloca in the entry block
LLVMBasicBlockRef currentBlock = LLVM.LLVMGetInsertBlock(builder);
LLVM.LLVMPositionBuilderBefore(builder, LLVM.LLVMGetFirstInstruction(LLVM.LLVMGetEntryBasicBlock(llvmFunction)));
LLVMValueRef alloca = LLVM.LLVMBuildAlloca(builder, findNativeType(returnType), "");
LLVM.LLVMPositionBuilderAtEnd(builder, currentBlock);
LLVM.LLVMBuildStore(builder, result, alloca);
return alloca;
}
return result;
}
if (expression instanceof InlineIfExpression)
{
InlineIfExpression inlineIf = (InlineIfExpression) expression;
LLVMValueRef conditionValue = buildExpression(inlineIf.getCondition(), llvmFunction, thisValue, variables);
LLVMBasicBlockRef thenBlock = LLVM.LLVMAppendBasicBlock(llvmFunction, "inlineIfThen");
LLVMBasicBlockRef elseBlock = LLVM.LLVMAppendBasicBlock(llvmFunction, "inlineIfElse");
LLVMBasicBlockRef continuationBlock = LLVM.LLVMAppendBasicBlock(llvmFunction, "afterInlineIf");
LLVM.LLVMBuildCondBr(builder, conditionValue, thenBlock, elseBlock);
LLVM.LLVMPositionBuilderAtEnd(builder, thenBlock);
LLVMValueRef thenValue = buildExpression(inlineIf.getThenExpression(), llvmFunction, thisValue, variables);
LLVMValueRef convertedThenValue = convertType(thenValue, inlineIf.getThenExpression().getType(), inlineIf.getType(), llvmFunction);
LLVMBasicBlockRef thenBranchBlock = LLVM.LLVMGetInsertBlock(builder);
LLVM.LLVMBuildBr(builder, continuationBlock);
LLVM.LLVMPositionBuilderAtEnd(builder, elseBlock);
LLVMValueRef elseValue = buildExpression(inlineIf.getElseExpression(), llvmFunction, thisValue, variables);
LLVMValueRef convertedElseValue = convertType(elseValue, inlineIf.getElseExpression().getType(), inlineIf.getType(), llvmFunction);
LLVMBasicBlockRef elseBranchBlock = LLVM.LLVMGetInsertBlock(builder);
LLVM.LLVMBuildBr(builder, continuationBlock);
LLVM.LLVMPositionBuilderAtEnd(builder, continuationBlock);
LLVMValueRef result = LLVM.LLVMBuildPhi(builder, findNativeType(inlineIf.getType()), "");
LLVMValueRef[] incomingValues = new LLVMValueRef[] {convertedThenValue, convertedElseValue};
LLVMBasicBlockRef[] incomingBlocks = new LLVMBasicBlockRef[] {thenBranchBlock, elseBranchBlock};
LLVM.LLVMAddIncoming(result, C.toNativePointerArray(incomingValues, false, true), C.toNativePointerArray(incomingBlocks, false, true), 2);
return result;
}
if (expression instanceof IntegerLiteralExpression)
{
int n = ((IntegerLiteralExpression) expression).getLiteral().getValue().intValue();
return LLVM.LLVMConstInt(findNativeType(expression.getType()), n, false);
}
if (expression instanceof LogicalExpression)
{
LogicalExpression logicalExpression = (LogicalExpression) expression;
LLVMValueRef left = buildExpression(logicalExpression.getLeftSubExpression(), llvmFunction, thisValue, variables);
PrimitiveType leftType = (PrimitiveType) logicalExpression.getLeftSubExpression().getType();
PrimitiveType rightType = (PrimitiveType) logicalExpression.getRightSubExpression().getType();
// cast if necessary
PrimitiveType resultType = (PrimitiveType) logicalExpression.getType();
left = convertPrimitiveType(left, leftType, resultType);
LogicalOperator operator = logicalExpression.getOperator();
if (operator != LogicalOperator.SHORT_CIRCUIT_AND && operator != LogicalOperator.SHORT_CIRCUIT_OR)
{
LLVMValueRef right = buildExpression(logicalExpression.getRightSubExpression(), llvmFunction, thisValue, variables);
right = convertPrimitiveType(right, rightType, resultType);
switch (operator)
{
case AND:
return LLVM.LLVMBuildAnd(builder, left, right, "");
case OR:
return LLVM.LLVMBuildOr(builder, left, right, "");
case XOR:
return LLVM.LLVMBuildXor(builder, left, right, "");
default:
throw new IllegalStateException("Unexpected non-short-circuit operator: " + logicalExpression.getOperator());
}
}
LLVMBasicBlockRef currentBlock = LLVM.LLVMGetInsertBlock(builder);
LLVMBasicBlockRef rightCheckBlock = LLVM.LLVMAppendBasicBlock(llvmFunction, "shortCircuitCheck");
LLVMBasicBlockRef continuationBlock = LLVM.LLVMAppendBasicBlock(llvmFunction, "shortCircuitContinue");
// the only difference between short circuit AND and OR is whether they jump to the check block when the left hand side is true or false
LLVMBasicBlockRef trueDest = operator == LogicalOperator.SHORT_CIRCUIT_AND ? rightCheckBlock : continuationBlock;
LLVMBasicBlockRef falseDest = operator == LogicalOperator.SHORT_CIRCUIT_AND ? continuationBlock : rightCheckBlock;
LLVM.LLVMBuildCondBr(builder, left, trueDest, falseDest);
LLVM.LLVMPositionBuilderAtEnd(builder, rightCheckBlock);
LLVMValueRef right = buildExpression(logicalExpression.getRightSubExpression(), llvmFunction, thisValue, variables);
right = convertPrimitiveType(right, rightType, resultType);
LLVM.LLVMBuildBr(builder, continuationBlock);
LLVM.LLVMPositionBuilderAtEnd(builder, continuationBlock);
// create a phi node for the result, and return it
LLVMValueRef phi = LLVM.LLVMBuildPhi(builder, findNativeType(resultType), "");
LLVMValueRef[] incomingValues = new LLVMValueRef[] {left, right};
LLVMBasicBlockRef[] incomingBlocks = new LLVMBasicBlockRef[] {currentBlock, rightCheckBlock};
LLVM.LLVMAddIncoming(phi, C.toNativePointerArray(incomingValues, false, true), C.toNativePointerArray(incomingBlocks, false, true), 2);
return phi;
}
if (expression instanceof MinusExpression)
{
MinusExpression minusExpression = (MinusExpression) expression;
LLVMValueRef value = buildExpression(minusExpression.getExpression(), llvmFunction, thisValue, variables);
value = convertPrimitiveType(value, (PrimitiveType) minusExpression.getExpression().getType(), (PrimitiveType) minusExpression.getType());
PrimitiveTypeType primitiveTypeType = ((PrimitiveType) minusExpression.getType()).getPrimitiveTypeType();
if (primitiveTypeType.isFloating())
{
return LLVM.LLVMBuildFNeg(builder, value, "");
}
return LLVM.LLVMBuildNeg(builder, value, "");
}
if (expression instanceof NullLiteralExpression)
{
Type type = expression.getType();
LLVMValueRef value = LLVM.LLVMConstNull(findNativeType(type));
if (type instanceof NamedType) // TODO (when it doesn't cause a warning): && ((NamedType) type).getResolvedDefinition() instanceof CompoundDefinition)
{
// for compound types, we need to get a pointer from this null value
// so build an alloca in the entry block
LLVMBasicBlockRef currentBlock = LLVM.LLVMGetInsertBlock(builder);
LLVM.LLVMPositionBuilderBefore(builder, LLVM.LLVMGetFirstInstruction(LLVM.LLVMGetEntryBasicBlock(llvmFunction)));
LLVMValueRef alloca = LLVM.LLVMBuildAlloca(builder, findNativeType(type), "");
LLVM.LLVMPositionBuilderAtEnd(builder, currentBlock);
LLVM.LLVMBuildStore(builder, value, alloca);
return alloca;
}
return value;
}
if (expression instanceof ShiftExpression)
{
ShiftExpression shiftExpression = (ShiftExpression) expression;
LLVMValueRef leftValue = buildExpression(shiftExpression.getLeftExpression(), llvmFunction, thisValue, variables);
LLVMValueRef rightValue = buildExpression(shiftExpression.getRightExpression(), llvmFunction, thisValue, variables);
LLVMValueRef convertedLeft = convertType(leftValue, shiftExpression.getLeftExpression().getType(), shiftExpression.getType(), llvmFunction);
LLVMValueRef convertedRight = convertType(rightValue, shiftExpression.getRightExpression().getType(), shiftExpression.getType(), llvmFunction);
switch (shiftExpression.getOperator())
{
case RIGHT_SHIFT:
if (((PrimitiveType) shiftExpression.getType()).getPrimitiveTypeType().isSigned())
{
return LLVM.LLVMBuildAShr(builder, convertedLeft, convertedRight, "");
}
return LLVM.LLVMBuildLShr(builder, convertedLeft, convertedRight, "");
case LEFT_SHIFT:
return LLVM.LLVMBuildShl(builder, convertedLeft, convertedRight, "");
}
throw new IllegalArgumentException("Unknown shift operator: " + shiftExpression.getOperator());
}
if (expression instanceof ThisExpression)
{
return thisValue;
}
if (expression instanceof TupleExpression)
{
TupleExpression tupleExpression = (TupleExpression) expression;
Type[] tupleTypes = ((TupleType) tupleExpression.getType()).getSubTypes();
Expression[] subExpressions = tupleExpression.getSubExpressions();
LLVMValueRef currentValue = LLVM.LLVMGetUndef(findNativeType(tupleExpression.getType()));
for (int i = 0; i < subExpressions.length; i++)
{
LLVMValueRef value = buildExpression(subExpressions[i], llvmFunction, thisValue, variables);
Type type = tupleTypes[i];
value = convertType(value, subExpressions[i].getType(), type, llvmFunction);
if (type instanceof NamedType) // TODO: when this does not cause a warning, add it: && ((NamedType) type).getResolvedDefinition() instanceof CompoundDefinition)
{
// for compound types, we need to load from the result of the expression before storing the result in the tuple
value = LLVM.LLVMBuildLoad(builder, value, "");
}
currentValue = LLVM.LLVMBuildInsertValue(builder, currentValue, value, i, "");
}
return currentValue;
}
if (expression instanceof TupleIndexExpression)
{
TupleIndexExpression tupleIndexExpression = (TupleIndexExpression) expression;
TupleType tupleType = (TupleType) tupleIndexExpression.getExpression().getType();
LLVMValueRef result = buildExpression(tupleIndexExpression.getExpression(), llvmFunction, thisValue, variables);
// convert the 1-based indexing to 0-based before extracting the value
int index = tupleIndexExpression.getIndexLiteral().getValue().intValue() - 1;
LLVMValueRef value = LLVM.LLVMBuildExtractValue(builder, result, index, "");
LLVMValueRef convertedValue = convertType(value, tupleType.getSubTypes()[index], tupleIndexExpression.getType(), llvmFunction);
Type type = tupleIndexExpression.getType();
if (type instanceof NamedType) // TODO: when the doesn't cause a warning, add it: && ((NamedType) type).getResolvedDefinition() instanceof CompoundDefinition)
{
// for compound types, we need to get a pointer to the extracted value
// so build an alloca in the entry block
LLVMBasicBlockRef currentBlock = LLVM.LLVMGetInsertBlock(builder);
LLVM.LLVMPositionBuilderBefore(builder, LLVM.LLVMGetFirstInstruction(LLVM.LLVMGetEntryBasicBlock(llvmFunction)));
LLVMValueRef alloca = LLVM.LLVMBuildAlloca(builder, findNativeType(type), "");
LLVM.LLVMPositionBuilderAtEnd(builder, currentBlock);
LLVM.LLVMBuildStore(builder, convertedValue, alloca);
return alloca;
}
return convertedValue;
}
if (expression instanceof VariableExpression)
{
Variable variable = ((VariableExpression) expression).getResolvedVariable();
if (variable instanceof MemberVariable)
{
Field field = ((MemberVariable) variable).getField();
LLVMValueRef[] indices = new LLVMValueRef[] {LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), 0, false),
LLVM.LLVMConstInt(LLVM.LLVMIntType(PrimitiveTypeType.UINT.getBitCount()), field.getMemberIndex(), false)};
LLVMValueRef elementPointer = LLVM.LLVMBuildGEP(builder, thisValue, C.toNativePointerArray(indices, false, true), indices.length, "");
if (field.getType() instanceof NamedType) // TODO (when it doesn't cause a warning): && ((NamedType) field.getType()).getResolvedDefinition() instanceof CompoundDefinition)
{
// for compound types, we do not need to load anything here
return elementPointer;
}
return LLVM.LLVMBuildLoad(builder, elementPointer, "");
}
if (variable instanceof GlobalVariable)
{
LLVMValueRef global = getGlobal((GlobalVariable) variable);
if (expression.getType() instanceof NamedType) // TODO (when it doesn't cause a warning): && ((NamedType) field.getType()).getResolvedDefinition() instanceof CompoundDefinition)
{
// for compound types, we do not need to load anything here
return global;
}
return LLVM.LLVMBuildLoad(builder, global, "");
}
LLVMValueRef value = variables.get(variable);
if (value == null)
{
throw new IllegalStateException("Missing LLVMValueRef in variable Map: " + ((VariableExpression) expression).getName());
}
if (variable.getType() instanceof NamedType) // TODO (when it doesn't cause a warning): && ((NamedType) variable.getType()).getResolvedDefinition() instanceof CompoundDefinition)
{
// for compound types, we do not need to load anything here
return value;
}
return LLVM.LLVMBuildLoad(builder, value, "");
}
throw new IllegalArgumentException("Unknown Expression type: " + expression);
}
}
| Perform type conversions in BracketedExpressions
| src/eu/bryants/anthony/toylanguage/compiler/passes/CodeGenerator.java | Perform type conversions in BracketedExpressions | <ide><path>rc/eu/bryants/anthony/toylanguage/compiler/passes/CodeGenerator.java
<ide> }
<ide> if (expression instanceof BracketedExpression)
<ide> {
<del> return buildExpression(((BracketedExpression) expression).getExpression(), llvmFunction, thisValue, variables);
<add> BracketedExpression bracketedExpression = (BracketedExpression) expression;
<add> LLVMValueRef value = buildExpression(bracketedExpression.getExpression(), llvmFunction, thisValue, variables);
<add> return convertType(value, bracketedExpression.getExpression().getType(), expression.getType(), llvmFunction);
<ide> }
<ide> if (expression instanceof CastExpression)
<ide> { |
|
Java | apache-2.0 | 636a7aa45ce97df0eb8a53be230b4d02cec27c82 | 0 | codeaudit/OG-Platform,jerome79/OG-Platform,nssales/OG-Platform,jeorme/OG-Platform,DevStreet/FinanceAnalytics,DevStreet/FinanceAnalytics,ChinaQuants/OG-Platform,McLeodMoores/starling,ChinaQuants/OG-Platform,McLeodMoores/starling,ChinaQuants/OG-Platform,DevStreet/FinanceAnalytics,codeaudit/OG-Platform,ChinaQuants/OG-Platform,jeorme/OG-Platform,codeaudit/OG-Platform,jerome79/OG-Platform,nssales/OG-Platform,nssales/OG-Platform,jerome79/OG-Platform,codeaudit/OG-Platform,McLeodMoores/starling,jeorme/OG-Platform,jeorme/OG-Platform,McLeodMoores/starling,DevStreet/FinanceAnalytics,nssales/OG-Platform,jerome79/OG-Platform | /**
* Copyright (C) 2012 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.financial.analytics.model.curve.interestrate;
import it.unimi.dsi.fastutil.doubles.DoubleArrayList;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.time.calendar.ZonedDateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.Sets;
import com.opengamma.OpenGammaRuntimeException;
import com.opengamma.analytics.financial.forex.method.FXMatrix;
import com.opengamma.analytics.financial.interestrate.InstrumentDerivative;
import com.opengamma.analytics.financial.interestrate.MultipleYieldCurveFinderDataBundle;
import com.opengamma.analytics.financial.interestrate.MultipleYieldCurveFinderFunction;
import com.opengamma.analytics.financial.interestrate.MultipleYieldCurveFinderJacobian;
import com.opengamma.analytics.financial.interestrate.ParRateCalculator;
import com.opengamma.analytics.financial.interestrate.ParRateCurveSensitivityCalculator;
import com.opengamma.analytics.financial.interestrate.YieldCurveBundle;
import com.opengamma.analytics.financial.interestrate.payments.ForexForward;
import com.opengamma.analytics.financial.interestrate.payments.derivative.PaymentFixed;
import com.opengamma.analytics.financial.model.interestrate.curve.YieldAndDiscountCurve;
import com.opengamma.analytics.financial.model.interestrate.curve.YieldCurve;
import com.opengamma.analytics.math.curve.InterpolatedDoublesCurve;
import com.opengamma.analytics.math.function.Function1D;
import com.opengamma.analytics.math.interpolation.CombinedInterpolatorExtrapolator;
import com.opengamma.analytics.math.interpolation.CombinedInterpolatorExtrapolatorFactory;
import com.opengamma.analytics.math.interpolation.Interpolator1D;
import com.opengamma.analytics.math.linearalgebra.Decomposition;
import com.opengamma.analytics.math.linearalgebra.DecompositionFactory;
import com.opengamma.analytics.math.matrix.DoubleMatrix1D;
import com.opengamma.analytics.math.matrix.DoubleMatrix2D;
import com.opengamma.analytics.math.rootfinding.newton.BroydenVectorRootFinder;
import com.opengamma.analytics.math.rootfinding.newton.NewtonVectorRootFinder;
import com.opengamma.analytics.util.time.TimeCalculator;
import com.opengamma.core.config.ConfigSource;
import com.opengamma.engine.ComputationTarget;
import com.opengamma.engine.ComputationTargetSpecification;
import com.opengamma.engine.ComputationTargetType;
import com.opengamma.engine.function.AbstractFunction;
import com.opengamma.engine.function.FunctionCompilationContext;
import com.opengamma.engine.function.FunctionExecutionContext;
import com.opengamma.engine.function.FunctionInputs;
import com.opengamma.engine.value.ComputedValue;
import com.opengamma.engine.value.ValueProperties;
import com.opengamma.engine.value.ValuePropertyNames;
import com.opengamma.engine.value.ValueRequirement;
import com.opengamma.engine.value.ValueRequirementNames;
import com.opengamma.engine.value.ValueSpecification;
import com.opengamma.financial.OpenGammaCompilationContext;
import com.opengamma.financial.OpenGammaExecutionContext;
import com.opengamma.financial.analytics.fxforwardcurve.ConfigDBFXForwardCurveDefinitionSource;
import com.opengamma.financial.analytics.fxforwardcurve.ConfigDBFXForwardCurveSpecificationSource;
import com.opengamma.financial.analytics.fxforwardcurve.FXForwardCurveDefinition;
import com.opengamma.financial.analytics.fxforwardcurve.FXForwardCurveInstrumentProvider;
import com.opengamma.financial.analytics.fxforwardcurve.FXForwardCurveSpecification;
import com.opengamma.financial.analytics.ircurve.calcconfig.ConfigDBCurveCalculationConfigSource;
import com.opengamma.financial.analytics.ircurve.calcconfig.MultiCurveCalculationConfig;
import com.opengamma.financial.analytics.model.InterpolatedDataProperties;
import com.opengamma.financial.currency.ConfigDBCurrencyPairsSource;
import com.opengamma.financial.currency.CurrencyPairs;
import com.opengamma.id.ExternalId;
import com.opengamma.id.UniqueIdentifiable;
import com.opengamma.util.money.Currency;
import com.opengamma.util.money.UnorderedCurrencyPair;
import com.opengamma.util.time.Tenor;
/**
*
*/
public class FXImpliedYieldCurveFunction extends AbstractFunction.NonCompiledInvoker {
/** Property name for the calculation method */
public static final String FX_IMPLIED = "FXImplied";
private static final Logger s_logger = LoggerFactory.getLogger(FXImpliedYieldCurveFunction.class);
private static final ParRateCalculator PAR_RATE_CALCULATOR = ParRateCalculator.getInstance();
private static final ParRateCurveSensitivityCalculator PAR_RATE_SENSITIVITY_CALCULATOR = ParRateCurveSensitivityCalculator.getInstance();
@Override
public Set<ComputedValue> execute(final FunctionExecutionContext executionContext, final FunctionInputs inputs, final ComputationTarget target,
final Set<ValueRequirement> desiredValues) {
final ZonedDateTime now = executionContext.getValuationClock().zonedDateTime();
final ValueRequirement desiredValue = desiredValues.iterator().next();
String domesticCurveName = desiredValue.getConstraint(ValuePropertyNames.CURVE);
final Currency domesticCurrency = Currency.of(target.getUniqueId().getValue());
Object foreignCurveObject = null;
Currency foreignCurrency = null;
String foreignCurveName = null;
for (final ComputedValue values : inputs.getAllValues()) {
final ValueSpecification specification = values.getSpecification();
if (specification.getValueName().equals(ValueRequirementNames.YIELD_CURVE)) {
foreignCurveObject = values.getValue();
foreignCurrency = Currency.of(specification.getTargetSpecification().getUniqueId().getValue());
foreignCurveName = specification.getProperty(ValuePropertyNames.CURVE);
break;
}
}
if (foreignCurveObject == null) {
throw new OpenGammaRuntimeException("Could not get foreign yield curve");
}
final String curveCalculationConfigName = desiredValue.getConstraint(ValuePropertyNames.CURVE_CALCULATION_CONFIG);
final String absoluteToleranceName = desiredValue.getConstraint(MultiYieldCurvePropertiesAndDefaults.PROPERTY_ROOT_FINDER_ABSOLUTE_TOLERANCE);
final double absoluteTolerance = Double.parseDouble(absoluteToleranceName);
final String relativeToleranceName = desiredValue.getConstraint(MultiYieldCurvePropertiesAndDefaults.PROPERTY_ROOT_FINDER_RELATIVE_TOLERANCE);
final double relativeTolerance = Double.parseDouble(relativeToleranceName);
final String iterationsName = desiredValue.getConstraint(MultiYieldCurvePropertiesAndDefaults.PROPERTY_ROOT_FINDER_MAX_ITERATIONS);
final int iterations = Integer.parseInt(iterationsName);
final String decompositionName = desiredValue.getConstraint(MultiYieldCurvePropertiesAndDefaults.PROPERTY_DECOMPOSITION);
final String useFiniteDifferenceName = desiredValue.getConstraint(MultiYieldCurvePropertiesAndDefaults.PROPERTY_USE_FINITE_DIFFERENCE);
final boolean useFiniteDifference = Boolean.parseBoolean(useFiniteDifferenceName);
final Decomposition<?> decomposition = DecompositionFactory.getDecomposition(decompositionName);
final String interpolatorName = desiredValue.getConstraint(InterpolatedDataProperties.X_INTERPOLATOR_NAME);
final String leftExtrapolatorName = desiredValue.getConstraint(InterpolatedDataProperties.LEFT_X_EXTRAPOLATOR_NAME);
final String rightExtrapolatorName = desiredValue.getConstraint(InterpolatedDataProperties.RIGHT_X_EXTRAPOLATOR_NAME);
final ConfigSource configSource = OpenGammaExecutionContext.getConfigSource(executionContext);
final ConfigDBFXForwardCurveDefinitionSource fxCurveDefinitionSource = new ConfigDBFXForwardCurveDefinitionSource(configSource);
final ConfigDBFXForwardCurveSpecificationSource fxCurveSpecificationSource = new ConfigDBFXForwardCurveSpecificationSource(configSource);
final ConfigDBCurrencyPairsSource currencyPairsSource = new ConfigDBCurrencyPairsSource(OpenGammaExecutionContext.getConfigSource(executionContext));
final CurrencyPairs currencyPairs = currencyPairsSource.getCurrencyPairs(CurrencyPairs.DEFAULT_CURRENCY_PAIRS);
Currency baseCurrency = currencyPairs.getCurrencyPair(domesticCurrency, foreignCurrency).getBase();
boolean invertFXQuotes;
if (baseCurrency.equals(foreignCurrency)) {
invertFXQuotes = false;
} else {
invertFXQuotes = true;
}
if (domesticCurveName == null) {
final ConfigDBCurveCalculationConfigSource curveConfigSource = new ConfigDBCurveCalculationConfigSource(configSource);
final String[] curveNames = curveConfigSource.getConfig(curveCalculationConfigName).getYieldCurveNames();
if (curveNames.length != 1) {
throw new OpenGammaRuntimeException("Can only handle a single curve at the moment");
}
domesticCurveName = curveNames[0];
}
final UnorderedCurrencyPair currencyPair = UnorderedCurrencyPair.of(domesticCurrency, foreignCurrency);
final FXForwardCurveDefinition definition = fxCurveDefinitionSource.getDefinition(domesticCurveName, currencyPair.toString());
if (definition == null) {
throw new OpenGammaRuntimeException("Couldn't find FX forward curve definition called " + domesticCurveName + " for target " + currencyPair);
}
final FXForwardCurveSpecification specification = fxCurveSpecificationSource.getSpecification(domesticCurveName, currencyPair.toString());
if (specification == null) {
throw new OpenGammaRuntimeException("Couldn't find FX forward curve specification called " + domesticCurveName + " for target " + currencyPair);
}
final FXForwardCurveInstrumentProvider provider = specification.getCurveInstrumentProvider();
final ValueRequirement spotRequirement = new ValueRequirement(provider.getDataFieldName(), provider.getSpotInstrument());
if (inputs.getValue(spotRequirement) == null) {
throw new OpenGammaRuntimeException("Could not get value for spot; requirement was " + spotRequirement);
}
final double spotFX = invertFXQuotes ? 1 / (Double) inputs.getValue(spotRequirement) : (Double) inputs.getValue(spotRequirement);
final Object dataObject = inputs.getValue(ValueRequirementNames.FX_FORWARD_CURVE_MARKET_DATA);
if (dataObject == null) {
throw new OpenGammaRuntimeException("Could not get FX forward market data");
}
final YieldAndDiscountCurve foreignCurve = (YieldAndDiscountCurve) foreignCurveObject;
@SuppressWarnings("unchecked")
final Map<ExternalId, Double> fxForwardData = (Map<ExternalId, Double>) dataObject;
final DoubleArrayList marketValues = new DoubleArrayList();
final DoubleArrayList nodeTimes = new DoubleArrayList();
final DoubleArrayList initialRatesGuess = new DoubleArrayList();
final String fullDomesticCurveName = domesticCurveName + "_" + domesticCurrency.getCode();
final String fullForeignCurveName = foreignCurveName + "_" + foreignCurrency.getCode();
final List<InstrumentDerivative> derivatives = new ArrayList<InstrumentDerivative>();
for (final Tenor tenor : definition.getTenors()) {
final ExternalId identifier = provider.getInstrument(now.toLocalDate(), tenor);
if (fxForwardData.containsKey(identifier)) {
final double paymentTime = TimeCalculator.getTimeBetween(now, now.plus(tenor.getPeriod())); //TODO
final double forwardFX = invertFXQuotes ? 1 / fxForwardData.get(identifier) : fxForwardData.get(identifier);
derivatives.add(getFXForward(domesticCurrency, foreignCurrency, paymentTime, spotFX, forwardFX, fullDomesticCurveName, fullForeignCurveName));
marketValues.add(forwardFX);
nodeTimes.add(paymentTime); //TODO
initialRatesGuess.add(0.02);
}
}
final YieldCurveBundle knownCurve = new YieldCurveBundle(new String[] {fullForeignCurveName}, new YieldAndDiscountCurve[] {foreignCurve});
final LinkedHashMap<String, double[]> curveKnots = new LinkedHashMap<String, double[]>();
curveKnots.put(fullDomesticCurveName, nodeTimes.toDoubleArray());
final LinkedHashMap<String, double[]> curveNodes = new LinkedHashMap<String, double[]>();
final LinkedHashMap<String, Interpolator1D> interpolators = new LinkedHashMap<String, Interpolator1D>();
final CombinedInterpolatorExtrapolator interpolator = CombinedInterpolatorExtrapolatorFactory.getInterpolator(interpolatorName, leftExtrapolatorName,
rightExtrapolatorName);
curveNodes.put(fullDomesticCurveName, nodeTimes.toDoubleArray());
interpolators.put(fullDomesticCurveName, interpolator);
final FXMatrix fxMatrix = new FXMatrix();
fxMatrix.addCurrency(foreignCurrency, domesticCurrency, spotFX);
final MultipleYieldCurveFinderDataBundle data = new MultipleYieldCurveFinderDataBundle(derivatives, marketValues.toDoubleArray(), knownCurve, curveNodes,
interpolators, useFiniteDifference, fxMatrix);
final NewtonVectorRootFinder rootFinder = new BroydenVectorRootFinder(absoluteTolerance, relativeTolerance, iterations, decomposition);
final Function1D<DoubleMatrix1D, DoubleMatrix1D> curveCalculator = new MultipleYieldCurveFinderFunction(data, PAR_RATE_CALCULATOR);
final Function1D<DoubleMatrix1D, DoubleMatrix2D> jacobianCalculator = new MultipleYieldCurveFinderJacobian(data, PAR_RATE_SENSITIVITY_CALCULATOR);
final double[] fittedYields = rootFinder.getRoot(curveCalculator, jacobianCalculator, new DoubleMatrix1D(initialRatesGuess.toDoubleArray())).getData();
final DoubleMatrix2D jacobianMatrix = jacobianCalculator.evaluate(new DoubleMatrix1D(fittedYields));
final YieldCurve curve = YieldCurve.from(InterpolatedDoublesCurve.from(nodeTimes.toDoubleArray(), fittedYields, interpolator));
final Set<ComputedValue> result = Sets.newHashSetWithExpectedSize(2);
final ComputationTargetSpecification targetSpec = target.toSpecification();
final ValueProperties curveProperties = getCurveProperties(curveCalculationConfigName, domesticCurveName, absoluteToleranceName, relativeToleranceName,
iterationsName, decompositionName, useFiniteDifferenceName, interpolatorName, leftExtrapolatorName, rightExtrapolatorName);
final ValueProperties properties = getProperties(curveCalculationConfigName, absoluteToleranceName, relativeToleranceName, iterationsName, decompositionName,
useFiniteDifferenceName, interpolatorName, leftExtrapolatorName, rightExtrapolatorName);
result.add(new ComputedValue(new ValueSpecification(ValueRequirementNames.YIELD_CURVE_JACOBIAN, targetSpec, properties), jacobianMatrix.getData()));
result.add(new ComputedValue(new ValueSpecification(ValueRequirementNames.YIELD_CURVE, targetSpec, curveProperties), curve));
return result;
}
@Override
public ComputationTargetType getTargetType() {
return ComputationTargetType.PRIMITIVE;
}
@Override
public boolean canApplyTo(final FunctionCompilationContext context, final ComputationTarget target) {
if (target.getType() != ComputationTargetType.PRIMITIVE || target.getUniqueId() == null) {
return false;
}
return Currency.OBJECT_SCHEME.equals(target.getUniqueId().getScheme());
}
@Override
public Set<ValueSpecification> getResults(final FunctionCompilationContext context, final ComputationTarget target) {
final ValueProperties curveProperties = getCurveProperties();
final ValueProperties properties = getProperties();
final ValueSpecification curve = new ValueSpecification(ValueRequirementNames.YIELD_CURVE, target.toSpecification(), curveProperties);
final ValueSpecification jacobian = new ValueSpecification(ValueRequirementNames.YIELD_CURVE_JACOBIAN, target.toSpecification(), properties);
return Sets.newHashSet(curve, jacobian);
}
@Override
public Set<ValueRequirement> getRequirements(final FunctionCompilationContext context, final ComputationTarget target, final ValueRequirement desiredValue) {
final ValueProperties constraints = desiredValue.getConstraints();
final Set<String> curveCalculationConfigNames = constraints.getValues(ValuePropertyNames.CURVE_CALCULATION_CONFIG);
if (curveCalculationConfigNames == null || curveCalculationConfigNames.size() != 1) {
return null;
}
final Set<String> rootFinderAbsoluteTolerance = constraints.getValues(MultiYieldCurvePropertiesAndDefaults.PROPERTY_ROOT_FINDER_ABSOLUTE_TOLERANCE);
if (rootFinderAbsoluteTolerance == null || rootFinderAbsoluteTolerance.size() != 1) {
return null;
}
final Set<String> rootFinderRelativeTolerance = constraints.getValues(MultiYieldCurvePropertiesAndDefaults.PROPERTY_ROOT_FINDER_RELATIVE_TOLERANCE);
if (rootFinderRelativeTolerance == null || rootFinderRelativeTolerance.size() != 1) {
return null;
}
final Set<String> maxIterations = constraints.getValues(MultiYieldCurvePropertiesAndDefaults.PROPERTY_ROOT_FINDER_MAX_ITERATIONS);
if (maxIterations == null || maxIterations.size() != 1) {
return null;
}
final Set<String> decomposition = constraints.getValues(MultiYieldCurvePropertiesAndDefaults.PROPERTY_DECOMPOSITION);
if (decomposition == null || decomposition.size() != 1) {
return null;
}
final Set<String> useFiniteDifference = constraints.getValues(MultiYieldCurvePropertiesAndDefaults.PROPERTY_USE_FINITE_DIFFERENCE);
if (useFiniteDifference == null || useFiniteDifference.size() != 1) {
return null;
}
final Set<String> interpolatorName = constraints.getValues(InterpolatedDataProperties.X_INTERPOLATOR_NAME);
if (interpolatorName == null || interpolatorName.size() != 1) {
return null;
}
final Set<String> leftExtrapolatorName = constraints.getValues(InterpolatedDataProperties.LEFT_X_EXTRAPOLATOR_NAME);
if (leftExtrapolatorName == null || leftExtrapolatorName.size() != 1) {
return null;
}
final Set<String> rightExtrapolatorName = constraints.getValues(InterpolatedDataProperties.RIGHT_X_EXTRAPOLATOR_NAME);
if (rightExtrapolatorName == null || rightExtrapolatorName.size() != 1) {
return null;
}
final String domesticCurveCalculationConfigName = curveCalculationConfigNames.iterator().next();
final ConfigSource configSource = OpenGammaCompilationContext.getConfigSource(context);
final ConfigDBFXForwardCurveDefinitionSource fxCurveDefinitionSource = new ConfigDBFXForwardCurveDefinitionSource(configSource);
final ConfigDBFXForwardCurveSpecificationSource fxCurveSpecificationSource = new ConfigDBFXForwardCurveSpecificationSource(configSource);
final ConfigDBCurveCalculationConfigSource curveCalculationConfigSource = new ConfigDBCurveCalculationConfigSource(configSource);
final MultiCurveCalculationConfig domesticCurveCalculationConfig = curveCalculationConfigSource.getConfig(domesticCurveCalculationConfigName);
if (domesticCurveCalculationConfig == null) {
s_logger.error("Could not get domestic curve calculation config called {}", domesticCurveCalculationConfigName);
return null;
}
if (!domesticCurveCalculationConfig.getCalculationMethod().equals(FX_IMPLIED)) {
return null;
}
if (domesticCurveCalculationConfig.getExogenousConfigData() == null) {
s_logger.error("Need an externally-supplied curve to imply data; tried {}", domesticCurveCalculationConfigName);
return null;
}
if (domesticCurveCalculationConfig.getYieldCurveNames().length != 1) {
s_logger.error("Can only handle one curve at the moment");
return null;
}
final String domesticCurveName = domesticCurveCalculationConfig.getYieldCurveNames()[0];
final UniqueIdentifiable domesticId = domesticCurveCalculationConfig.getUniqueId();
if (!(domesticId instanceof Currency)) {
s_logger.error("Can only handle curves with currencies as ids at the moment");
return null;
}
final Currency domesticCurrency = (Currency) domesticId;
final Set<ValueRequirement> requirements = new HashSet<ValueRequirement>();
final Map<String, String[]> exogenousConfigs = domesticCurveCalculationConfig.getExogenousConfigData();
if (exogenousConfigs.size() != 1) {
s_logger.error("Can only handle curves with one foreign curve config");
return null;
}
final Map.Entry<String, String[]> entry = exogenousConfigs.entrySet().iterator().next();
final MultiCurveCalculationConfig foreignConfig = curveCalculationConfigSource.getConfig(entry.getKey());
if (foreignConfig == null) {
s_logger.error("Foreign config was null");
return null;
}
final UniqueIdentifiable foreignId = foreignConfig.getUniqueId();
if (!(foreignId instanceof Currency)) {
s_logger.error("Can only handle curves with currencies as ids at the moment");
return null;
}
final Currency foreignCurrency = (Currency) foreignId;
final UnorderedCurrencyPair currencyPair = UnorderedCurrencyPair.of(domesticCurrency, foreignCurrency);
final FXForwardCurveDefinition definition = fxCurveDefinitionSource.getDefinition(domesticCurveName, currencyPair.toString());
if (definition == null) {
s_logger.error("Couldn't find FX forward curve definition called " + domesticCurveName + " with target " + currencyPair);
return null;
}
final FXForwardCurveSpecification fxForwardCurveSpec = fxCurveSpecificationSource.getSpecification(domesticCurveName, currencyPair.toString());
if (fxForwardCurveSpec == null) {
s_logger.error("Couldn't find FX forward curve specification called " + domesticCurveName + " with target " + currencyPair);
return null;
}
final ValueProperties fxForwardCurveProperties = ValueProperties.builder().with(ValuePropertyNames.CURVE, domesticCurveName).get();
final String foreignCurveName = foreignConfig.getYieldCurveNames()[0];
final ValueProperties foreignCurveProperties = getForeignCurveProperties(foreignConfig, foreignCurveName);
final FXForwardCurveInstrumentProvider provider = fxForwardCurveSpec.getCurveInstrumentProvider();
requirements.add(new ValueRequirement(ValueRequirementNames.FX_FORWARD_CURVE_MARKET_DATA, new ComputationTargetSpecification(currencyPair), fxForwardCurveProperties));
requirements.add(new ValueRequirement(provider.getDataFieldName(), provider.getSpotInstrument()));
requirements.add(new ValueRequirement(ValueRequirementNames.YIELD_CURVE, new ComputationTargetSpecification(foreignCurrency), foreignCurveProperties));
return requirements;
}
private ValueProperties getForeignCurveProperties(final MultiCurveCalculationConfig foreignConfig, final String foreignCurveName) {
return ValueProperties.builder()
.with(ValuePropertyNames.CURVE, foreignCurveName)
.with(ValuePropertyNames.CURVE_CALCULATION_CONFIG, foreignConfig.getCalculationConfigName()).get();
}
private ValueProperties getCurveProperties() {
return createValueProperties()
.with(ValuePropertyNames.CURVE_CALCULATION_METHOD, FX_IMPLIED)
.withAny(ValuePropertyNames.CURVE)
.withAny(ValuePropertyNames.CURVE_CALCULATION_CONFIG)
.withAny(MultiYieldCurvePropertiesAndDefaults.PROPERTY_ROOT_FINDER_ABSOLUTE_TOLERANCE)
.withAny(MultiYieldCurvePropertiesAndDefaults.PROPERTY_ROOT_FINDER_RELATIVE_TOLERANCE)
.withAny(MultiYieldCurvePropertiesAndDefaults.PROPERTY_ROOT_FINDER_MAX_ITERATIONS)
.withAny(MultiYieldCurvePropertiesAndDefaults.PROPERTY_DECOMPOSITION)
.withAny(MultiYieldCurvePropertiesAndDefaults.PROPERTY_USE_FINITE_DIFFERENCE)
.withAny(InterpolatedDataProperties.X_INTERPOLATOR_NAME)
.withAny(InterpolatedDataProperties.LEFT_X_EXTRAPOLATOR_NAME)
.withAny(InterpolatedDataProperties.RIGHT_X_EXTRAPOLATOR_NAME).get();
}
private ValueProperties getProperties() {
return createValueProperties()
.with(ValuePropertyNames.CURVE_CALCULATION_METHOD, FX_IMPLIED)
.withAny(ValuePropertyNames.CURVE_CALCULATION_CONFIG)
.withAny(MultiYieldCurvePropertiesAndDefaults.PROPERTY_ROOT_FINDER_ABSOLUTE_TOLERANCE)
.withAny(MultiYieldCurvePropertiesAndDefaults.PROPERTY_ROOT_FINDER_RELATIVE_TOLERANCE)
.withAny(MultiYieldCurvePropertiesAndDefaults.PROPERTY_ROOT_FINDER_MAX_ITERATIONS)
.withAny(MultiYieldCurvePropertiesAndDefaults.PROPERTY_DECOMPOSITION)
.withAny(MultiYieldCurvePropertiesAndDefaults.PROPERTY_USE_FINITE_DIFFERENCE)
.withAny(InterpolatedDataProperties.X_INTERPOLATOR_NAME)
.withAny(InterpolatedDataProperties.LEFT_X_EXTRAPOLATOR_NAME)
.withAny(InterpolatedDataProperties.RIGHT_X_EXTRAPOLATOR_NAME).get();
}
private ValueProperties getCurveProperties(final String curveCalculationConfigName, final String curveName, final String absoluteTolerance,
final String relativeTolerance, final String maxIterations, final String decomposition, final String useFiniteDifference, final String interpolatorName,
final String leftExtrapolatorName, final String rightExtrapolatorName) {
return createValueProperties()
.with(ValuePropertyNames.CURVE_CALCULATION_METHOD, FX_IMPLIED)
.with(ValuePropertyNames.CURVE, curveName)
.with(ValuePropertyNames.CURVE_CALCULATION_CONFIG, curveCalculationConfigName)
.with(MultiYieldCurvePropertiesAndDefaults.PROPERTY_ROOT_FINDER_ABSOLUTE_TOLERANCE, absoluteTolerance)
.with(MultiYieldCurvePropertiesAndDefaults.PROPERTY_ROOT_FINDER_RELATIVE_TOLERANCE, relativeTolerance)
.with(MultiYieldCurvePropertiesAndDefaults.PROPERTY_ROOT_FINDER_MAX_ITERATIONS, maxIterations)
.with(MultiYieldCurvePropertiesAndDefaults.PROPERTY_DECOMPOSITION, decomposition)
.with(MultiYieldCurvePropertiesAndDefaults.PROPERTY_USE_FINITE_DIFFERENCE, useFiniteDifference)
.with(InterpolatedDataProperties.X_INTERPOLATOR_NAME, interpolatorName)
.with(InterpolatedDataProperties.LEFT_X_EXTRAPOLATOR_NAME, leftExtrapolatorName)
.with(InterpolatedDataProperties.RIGHT_X_EXTRAPOLATOR_NAME, rightExtrapolatorName).get();
}
private ValueProperties getProperties(final String curveCalculationConfigName, final String absoluteTolerance, final String relativeTolerance,
final String maxIterations, final String decomposition, final String useFiniteDifference, final String interpolatorName, final String leftExtrapolatorName,
final String rightExtrapolatorName) {
return createValueProperties()
.with(ValuePropertyNames.CURVE_CALCULATION_METHOD, FX_IMPLIED)
.with(ValuePropertyNames.CURVE_CALCULATION_CONFIG, curveCalculationConfigName)
.with(MultiYieldCurvePropertiesAndDefaults.PROPERTY_ROOT_FINDER_ABSOLUTE_TOLERANCE, absoluteTolerance)
.with(MultiYieldCurvePropertiesAndDefaults.PROPERTY_ROOT_FINDER_RELATIVE_TOLERANCE, relativeTolerance)
.with(MultiYieldCurvePropertiesAndDefaults.PROPERTY_ROOT_FINDER_MAX_ITERATIONS, maxIterations)
.with(MultiYieldCurvePropertiesAndDefaults.PROPERTY_DECOMPOSITION, decomposition)
.with(MultiYieldCurvePropertiesAndDefaults.PROPERTY_USE_FINITE_DIFFERENCE, useFiniteDifference)
.with(InterpolatedDataProperties.X_INTERPOLATOR_NAME, interpolatorName)
.with(InterpolatedDataProperties.LEFT_X_EXTRAPOLATOR_NAME, leftExtrapolatorName)
.with(InterpolatedDataProperties.RIGHT_X_EXTRAPOLATOR_NAME, rightExtrapolatorName).get();
}
//TODO determine domestic and notional from dominance data
private ForexForward getFXForward(final Currency ccy1, final Currency ccy2, final double paymentTime, final double spotFX, final double forwardFX, final String curveName1, final String curveName2) {
final PaymentFixed paymentCurrency1 = new PaymentFixed(ccy1, paymentTime, 1, curveName1);
final PaymentFixed paymentCurrency2 = new PaymentFixed(ccy2, paymentTime, -1. / forwardFX, curveName2);
return new ForexForward(paymentCurrency1, paymentCurrency2, spotFX);
}
}
| projects/OG-Financial/src/com/opengamma/financial/analytics/model/curve/interestrate/FXImpliedYieldCurveFunction.java | /**
* Copyright (C) 2012 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.financial.analytics.model.curve.interestrate;
import it.unimi.dsi.fastutil.doubles.DoubleArrayList;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.time.calendar.ZonedDateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.Sets;
import com.opengamma.OpenGammaRuntimeException;
import com.opengamma.analytics.financial.forex.method.FXMatrix;
import com.opengamma.analytics.financial.interestrate.InstrumentDerivative;
import com.opengamma.analytics.financial.interestrate.MultipleYieldCurveFinderDataBundle;
import com.opengamma.analytics.financial.interestrate.MultipleYieldCurveFinderFunction;
import com.opengamma.analytics.financial.interestrate.MultipleYieldCurveFinderJacobian;
import com.opengamma.analytics.financial.interestrate.ParRateCalculator;
import com.opengamma.analytics.financial.interestrate.ParRateCurveSensitivityCalculator;
import com.opengamma.analytics.financial.interestrate.YieldCurveBundle;
import com.opengamma.analytics.financial.interestrate.payments.ForexForward;
import com.opengamma.analytics.financial.interestrate.payments.derivative.PaymentFixed;
import com.opengamma.analytics.financial.model.interestrate.curve.YieldAndDiscountCurve;
import com.opengamma.analytics.financial.model.interestrate.curve.YieldCurve;
import com.opengamma.analytics.math.curve.InterpolatedDoublesCurve;
import com.opengamma.analytics.math.function.Function1D;
import com.opengamma.analytics.math.interpolation.CombinedInterpolatorExtrapolator;
import com.opengamma.analytics.math.interpolation.CombinedInterpolatorExtrapolatorFactory;
import com.opengamma.analytics.math.interpolation.Interpolator1D;
import com.opengamma.analytics.math.linearalgebra.Decomposition;
import com.opengamma.analytics.math.linearalgebra.DecompositionFactory;
import com.opengamma.analytics.math.matrix.DoubleMatrix1D;
import com.opengamma.analytics.math.matrix.DoubleMatrix2D;
import com.opengamma.analytics.math.rootfinding.newton.BroydenVectorRootFinder;
import com.opengamma.analytics.math.rootfinding.newton.NewtonVectorRootFinder;
import com.opengamma.analytics.util.time.TimeCalculator;
import com.opengamma.core.config.ConfigSource;
import com.opengamma.engine.ComputationTarget;
import com.opengamma.engine.ComputationTargetSpecification;
import com.opengamma.engine.ComputationTargetType;
import com.opengamma.engine.function.AbstractFunction;
import com.opengamma.engine.function.FunctionCompilationContext;
import com.opengamma.engine.function.FunctionExecutionContext;
import com.opengamma.engine.function.FunctionInputs;
import com.opengamma.engine.value.ComputedValue;
import com.opengamma.engine.value.ValueProperties;
import com.opengamma.engine.value.ValuePropertyNames;
import com.opengamma.engine.value.ValueRequirement;
import com.opengamma.engine.value.ValueRequirementNames;
import com.opengamma.engine.value.ValueSpecification;
import com.opengamma.financial.OpenGammaCompilationContext;
import com.opengamma.financial.OpenGammaExecutionContext;
import com.opengamma.financial.analytics.fxforwardcurve.ConfigDBFXForwardCurveDefinitionSource;
import com.opengamma.financial.analytics.fxforwardcurve.ConfigDBFXForwardCurveSpecificationSource;
import com.opengamma.financial.analytics.fxforwardcurve.FXForwardCurveDefinition;
import com.opengamma.financial.analytics.fxforwardcurve.FXForwardCurveInstrumentProvider;
import com.opengamma.financial.analytics.fxforwardcurve.FXForwardCurveSpecification;
import com.opengamma.financial.analytics.ircurve.calcconfig.ConfigDBCurveCalculationConfigSource;
import com.opengamma.financial.analytics.ircurve.calcconfig.MultiCurveCalculationConfig;
import com.opengamma.financial.analytics.model.InterpolatedDataProperties;
import com.opengamma.financial.currency.ConfigDBCurrencyPairsSource;
import com.opengamma.financial.currency.CurrencyPairs;
import com.opengamma.id.ExternalId;
import com.opengamma.id.UniqueIdentifiable;
import com.opengamma.util.money.Currency;
import com.opengamma.util.money.UnorderedCurrencyPair;
import com.opengamma.util.time.Tenor;
/**
*
*/
public class FXImpliedYieldCurveFunction extends AbstractFunction.NonCompiledInvoker {
/** Property name for the calculation method */
public static final String FX_IMPLIED = "FXImplied";
private static final Logger s_logger = LoggerFactory.getLogger(FXImpliedYieldCurveFunction.class);
private static final ParRateCalculator PAR_RATE_CALCULATOR = ParRateCalculator.getInstance();
private static final ParRateCurveSensitivityCalculator PAR_RATE_SENSITIVITY_CALCULATOR = ParRateCurveSensitivityCalculator.getInstance();
@Override
public Set<ComputedValue> execute(final FunctionExecutionContext executionContext, final FunctionInputs inputs, final ComputationTarget target,
final Set<ValueRequirement> desiredValues) {
final ZonedDateTime now = executionContext.getValuationClock().zonedDateTime();
final ValueRequirement desiredValue = desiredValues.iterator().next();
String domesticCurveName = desiredValue.getConstraint(ValuePropertyNames.CURVE);
final Currency domesticCurrency = Currency.of(target.getUniqueId().getValue());
Object foreignCurveObject = null;
Currency foreignCurrency = null;
String foreignCurveName = null;
for (final ComputedValue values : inputs.getAllValues()) {
final ValueSpecification specification = values.getSpecification();
if (specification.getValueName().equals(ValueRequirementNames.YIELD_CURVE)) {
foreignCurveObject = values.getValue();
foreignCurrency = Currency.of(specification.getTargetSpecification().getUniqueId().getValue());
foreignCurveName = specification.getProperty(ValuePropertyNames.CURVE);
break;
}
}
if (foreignCurveObject == null) {
throw new OpenGammaRuntimeException("Could not get foreign yield curve");
}
final String curveCalculationConfigName = desiredValue.getConstraint(ValuePropertyNames.CURVE_CALCULATION_CONFIG);
final String absoluteToleranceName = desiredValue.getConstraint(MultiYieldCurvePropertiesAndDefaults.PROPERTY_ROOT_FINDER_ABSOLUTE_TOLERANCE);
final double absoluteTolerance = Double.parseDouble(absoluteToleranceName);
final String relativeToleranceName = desiredValue.getConstraint(MultiYieldCurvePropertiesAndDefaults.PROPERTY_ROOT_FINDER_RELATIVE_TOLERANCE);
final double relativeTolerance = Double.parseDouble(relativeToleranceName);
final String iterationsName = desiredValue.getConstraint(MultiYieldCurvePropertiesAndDefaults.PROPERTY_ROOT_FINDER_MAX_ITERATIONS);
final int iterations = Integer.parseInt(iterationsName);
final String decompositionName = desiredValue.getConstraint(MultiYieldCurvePropertiesAndDefaults.PROPERTY_DECOMPOSITION);
final String useFiniteDifferenceName = desiredValue.getConstraint(MultiYieldCurvePropertiesAndDefaults.PROPERTY_USE_FINITE_DIFFERENCE);
final boolean useFiniteDifference = Boolean.parseBoolean(useFiniteDifferenceName);
final Decomposition<?> decomposition = DecompositionFactory.getDecomposition(decompositionName);
final String interpolatorName = desiredValue.getConstraint(InterpolatedDataProperties.X_INTERPOLATOR_NAME);
final String leftExtrapolatorName = desiredValue.getConstraint(InterpolatedDataProperties.LEFT_X_EXTRAPOLATOR_NAME);
final String rightExtrapolatorName = desiredValue.getConstraint(InterpolatedDataProperties.RIGHT_X_EXTRAPOLATOR_NAME);
final ConfigSource configSource = OpenGammaExecutionContext.getConfigSource(executionContext);
final ConfigDBFXForwardCurveDefinitionSource fxCurveDefinitionSource = new ConfigDBFXForwardCurveDefinitionSource(configSource);
final ConfigDBFXForwardCurveSpecificationSource fxCurveSpecificationSource = new ConfigDBFXForwardCurveSpecificationSource(configSource);
final ConfigDBCurrencyPairsSource currencyPairsSource = new ConfigDBCurrencyPairsSource(OpenGammaExecutionContext.getConfigSource(executionContext));
final CurrencyPairs currencyPairs = currencyPairsSource.getCurrencyPairs(CurrencyPairs.DEFAULT_CURRENCY_PAIRS);
Currency baseCurrency = currencyPairs.getCurrencyPair(domesticCurrency, foreignCurrency).getBase();
boolean invertFXQuotes;
if (baseCurrency.equals(foreignCurrency)) {
invertFXQuotes = false;
} else {
invertFXQuotes = true;
}
if (domesticCurveName == null) {
final ConfigDBCurveCalculationConfigSource curveConfigSource = new ConfigDBCurveCalculationConfigSource(configSource);
final String[] curveNames = curveConfigSource.getConfig(curveCalculationConfigName).getYieldCurveNames();
if (curveNames.length != 1) {
throw new OpenGammaRuntimeException("Can only handle a single curve at the moment");
}
domesticCurveName = curveNames[0];
}
final UnorderedCurrencyPair currencyPair = UnorderedCurrencyPair.of(domesticCurrency, foreignCurrency);
final FXForwardCurveDefinition definition = fxCurveDefinitionSource.getDefinition(domesticCurveName, currencyPair.toString());
if (definition == null) {
throw new OpenGammaRuntimeException("Couldn't find FX forward curve definition called " + domesticCurveName + " for target " + currencyPair);
}
final FXForwardCurveSpecification specification = fxCurveSpecificationSource.getSpecification(domesticCurveName, currencyPair.toString());
if (specification == null) {
throw new OpenGammaRuntimeException("Couldn't find FX forward curve specification called " + domesticCurveName + " for target " + currencyPair);
}
final FXForwardCurveInstrumentProvider provider = specification.getCurveInstrumentProvider();
final ValueRequirement spotRequirement = new ValueRequirement(provider.getDataFieldName(), provider.getSpotInstrument());
if (inputs.getValue(spotRequirement) == null) {
throw new OpenGammaRuntimeException("Could not get value for spot; requirement was " + spotRequirement);
}
final double spotFX = invertFXQuotes ? 1 / (Double) inputs.getValue(spotRequirement) : (Double) inputs.getValue(spotRequirement);
final Object dataObject = inputs.getValue(ValueRequirementNames.FX_FORWARD_CURVE_MARKET_DATA);
if (dataObject == null) {
throw new OpenGammaRuntimeException("Could not get FX forward market data");
}
final YieldAndDiscountCurve foreignCurve = (YieldAndDiscountCurve) foreignCurveObject;
@SuppressWarnings("unchecked")
final Map<ExternalId, Double> fxForwardData = (Map<ExternalId, Double>) dataObject;
final DoubleArrayList marketValues = new DoubleArrayList();
final DoubleArrayList nodeTimes = new DoubleArrayList();
final DoubleArrayList initialRatesGuess = new DoubleArrayList();
final String fullDomesticCurveName = domesticCurveName + "_" + domesticCurrency.getCode();
final String fullForeignCurveName = foreignCurveName + "_" + foreignCurrency.getCode();
final List<InstrumentDerivative> derivatives = new ArrayList<InstrumentDerivative>();
for (final Tenor tenor : definition.getTenors()) {
final ExternalId identifier = provider.getInstrument(now.toLocalDate(), tenor);
if (fxForwardData.containsKey(identifier)) {
final double paymentTime = TimeCalculator.getTimeBetween(now, now.plus(tenor.getPeriod())); //TODO
final double forwardFX = invertFXQuotes ? 1 / fxForwardData.get(identifier) : fxForwardData.get(identifier);
derivatives.add(getFXForward(domesticCurrency, foreignCurrency, paymentTime, spotFX, forwardFX, fullDomesticCurveName, fullForeignCurveName));
marketValues.add(forwardFX);
nodeTimes.add(paymentTime); //TODO
initialRatesGuess.add(0.02);
}
}
final YieldCurveBundle knownCurve = new YieldCurveBundle(new String[] {fullForeignCurveName}, new YieldAndDiscountCurve[] {foreignCurve});
final LinkedHashMap<String, double[]> curveKnots = new LinkedHashMap<String, double[]>();
curveKnots.put(fullDomesticCurveName, nodeTimes.toDoubleArray());
final LinkedHashMap<String, double[]> curveNodes = new LinkedHashMap<String, double[]>();
final LinkedHashMap<String, Interpolator1D> interpolators = new LinkedHashMap<String, Interpolator1D>();
final CombinedInterpolatorExtrapolator interpolator = CombinedInterpolatorExtrapolatorFactory.getInterpolator(interpolatorName, leftExtrapolatorName,
rightExtrapolatorName);
curveNodes.put(fullDomesticCurveName, nodeTimes.toDoubleArray());
interpolators.put(fullDomesticCurveName, interpolator);
final FXMatrix fxMatrix = new FXMatrix();
fxMatrix.addCurrency(foreignCurrency, domesticCurrency, spotFX);
final MultipleYieldCurveFinderDataBundle data = new MultipleYieldCurveFinderDataBundle(derivatives, marketValues.toDoubleArray(), knownCurve, curveNodes,
interpolators, useFiniteDifference, fxMatrix);
final NewtonVectorRootFinder rootFinder = new BroydenVectorRootFinder(absoluteTolerance, relativeTolerance, iterations, decomposition);
final Function1D<DoubleMatrix1D, DoubleMatrix1D> curveCalculator = new MultipleYieldCurveFinderFunction(data, PAR_RATE_CALCULATOR);
final Function1D<DoubleMatrix1D, DoubleMatrix2D> jacobianCalculator = new MultipleYieldCurveFinderJacobian(data, PAR_RATE_SENSITIVITY_CALCULATOR);
final double[] fittedYields = rootFinder.getRoot(curveCalculator, jacobianCalculator, new DoubleMatrix1D(initialRatesGuess.toDoubleArray())).getData();
final DoubleMatrix2D jacobianMatrix = jacobianCalculator.evaluate(new DoubleMatrix1D(fittedYields));
final YieldCurve curve = YieldCurve.from(InterpolatedDoublesCurve.from(nodeTimes.toDoubleArray(), fittedYields, interpolator));
final Set<ComputedValue> result = Sets.newHashSetWithExpectedSize(2);
final ComputationTargetSpecification targetSpec = target.toSpecification();
final ValueProperties curveProperties = getCurveProperties(curveCalculationConfigName, domesticCurveName, absoluteToleranceName, relativeToleranceName,
iterationsName, decompositionName, useFiniteDifferenceName, interpolatorName, leftExtrapolatorName, rightExtrapolatorName);
final ValueProperties properties = getProperties(curveCalculationConfigName, absoluteToleranceName, relativeToleranceName, iterationsName, decompositionName,
useFiniteDifferenceName, interpolatorName, leftExtrapolatorName, rightExtrapolatorName);
result.add(new ComputedValue(new ValueSpecification(ValueRequirementNames.YIELD_CURVE_JACOBIAN, targetSpec, properties), jacobianMatrix.getData()));
result.add(new ComputedValue(new ValueSpecification(ValueRequirementNames.YIELD_CURVE, targetSpec, curveProperties), curve));
return result;
}
@Override
public ComputationTargetType getTargetType() {
return ComputationTargetType.PRIMITIVE;
}
@Override
public boolean canApplyTo(final FunctionCompilationContext context, final ComputationTarget target) {
if (target.getType() != ComputationTargetType.PRIMITIVE || target.getUniqueId() == null) {
return false;
}
return Currency.OBJECT_SCHEME.equals(target.getUniqueId().getScheme());
}
@Override
public Set<ValueSpecification> getResults(final FunctionCompilationContext context, final ComputationTarget target) {
final ValueProperties curveProperties = getCurveProperties();
final ValueProperties properties = getProperties();
final ValueSpecification curve = new ValueSpecification(ValueRequirementNames.YIELD_CURVE, target.toSpecification(), curveProperties);
final ValueSpecification jacobian = new ValueSpecification(ValueRequirementNames.YIELD_CURVE_JACOBIAN, target.toSpecification(), properties);
return Sets.newHashSet(curve, jacobian);
}
@Override
public Set<ValueRequirement> getRequirements(final FunctionCompilationContext context, final ComputationTarget target, final ValueRequirement desiredValue) {
final ValueProperties constraints = desiredValue.getConstraints();
final Set<String> curveCalculationConfigNames = constraints.getValues(ValuePropertyNames.CURVE_CALCULATION_CONFIG);
if (curveCalculationConfigNames == null || curveCalculationConfigNames.size() != 1) {
return null;
}
final Set<String> rootFinderAbsoluteTolerance = constraints.getValues(MultiYieldCurvePropertiesAndDefaults.PROPERTY_ROOT_FINDER_ABSOLUTE_TOLERANCE);
if (rootFinderAbsoluteTolerance == null || rootFinderAbsoluteTolerance.size() != 1) {
return null;
}
final Set<String> rootFinderRelativeTolerance = constraints.getValues(MultiYieldCurvePropertiesAndDefaults.PROPERTY_ROOT_FINDER_RELATIVE_TOLERANCE);
if (rootFinderRelativeTolerance == null || rootFinderRelativeTolerance.size() != 1) {
return null;
}
final Set<String> maxIterations = constraints.getValues(MultiYieldCurvePropertiesAndDefaults.PROPERTY_ROOT_FINDER_MAX_ITERATIONS);
if (maxIterations == null || maxIterations.size() != 1) {
return null;
}
final Set<String> decomposition = constraints.getValues(MultiYieldCurvePropertiesAndDefaults.PROPERTY_DECOMPOSITION);
if (decomposition == null || decomposition.size() != 1) {
return null;
}
final Set<String> useFiniteDifference = constraints.getValues(MultiYieldCurvePropertiesAndDefaults.PROPERTY_USE_FINITE_DIFFERENCE);
if (useFiniteDifference == null || useFiniteDifference.size() != 1) {
return null;
}
final Set<String> interpolatorName = constraints.getValues(InterpolatedDataProperties.X_INTERPOLATOR_NAME);
if (interpolatorName == null || interpolatorName.size() != 1) {
return null;
}
final Set<String> leftExtrapolatorName = constraints.getValues(InterpolatedDataProperties.LEFT_X_EXTRAPOLATOR_NAME);
if (leftExtrapolatorName == null || leftExtrapolatorName.size() != 1) {
return null;
}
final Set<String> rightExtrapolatorName = constraints.getValues(InterpolatedDataProperties.RIGHT_X_EXTRAPOLATOR_NAME);
if (rightExtrapolatorName == null || rightExtrapolatorName.size() != 1) {
return null;
}
final String domesticCurveCalculationConfigName = curveCalculationConfigNames.iterator().next();
final ConfigSource configSource = OpenGammaCompilationContext.getConfigSource(context);
final ConfigDBFXForwardCurveDefinitionSource fxCurveDefinitionSource = new ConfigDBFXForwardCurveDefinitionSource(configSource);
final ConfigDBFXForwardCurveSpecificationSource fxCurveSpecificationSource = new ConfigDBFXForwardCurveSpecificationSource(configSource);
final ConfigDBCurveCalculationConfigSource curveCalculationConfigSource = new ConfigDBCurveCalculationConfigSource(configSource);
final MultiCurveCalculationConfig domesticCurveCalculationConfig = curveCalculationConfigSource.getConfig(domesticCurveCalculationConfigName);
if (domesticCurveCalculationConfig == null) {
s_logger.error("Could not get domestic curve calculation config called {}", domesticCurveCalculationConfigName);
return null;
}
if (!domesticCurveCalculationConfig.getCalculationMethod().equals(FX_IMPLIED)) {
return null;
}
if (domesticCurveCalculationConfig.getExogenousConfigData() == null) {
s_logger.error("Need an externally-supplied curve to imply data; tried {}", domesticCurveCalculationConfigName);
return null;
}
if (domesticCurveCalculationConfig.getYieldCurveNames().length != 1) {
s_logger.error("Can only handle one curve at the moment");
return null;
}
final String domesticCurveName = domesticCurveCalculationConfig.getYieldCurveNames()[0];
final UniqueIdentifiable domesticId = domesticCurveCalculationConfig.getUniqueId();
if (!(domesticId instanceof Currency)) {
s_logger.error("Can only handle curves with currencies as ids at the moment");
return null;
}
final Currency domesticCurrency = (Currency) domesticId;
final Set<ValueRequirement> requirements = new HashSet<ValueRequirement>();
final Map<String, String[]> exogenousConfigs = domesticCurveCalculationConfig.getExogenousConfigData();
if (exogenousConfigs.size() != 1) {
s_logger.error("Can only handle curves with one foreign curve config");
return null;
}
final Map.Entry<String, String[]> entry = exogenousConfigs.entrySet().iterator().next();
final MultiCurveCalculationConfig foreignConfig = curveCalculationConfigSource.getConfig(entry.getKey());
if (foreignConfig == null) {
s_logger.error("Foreign config was null");
return null;
}
final UniqueIdentifiable foreignId = foreignConfig.getUniqueId();
if (!(foreignId instanceof Currency)) {
s_logger.error("Can only handle curves with currencies as ids at the moment");
return null;
}
final Currency foreignCurrency = (Currency) foreignId;
final UnorderedCurrencyPair currencyPair = UnorderedCurrencyPair.of(domesticCurrency, foreignCurrency);
final FXForwardCurveDefinition definition = fxCurveDefinitionSource.getDefinition(domesticCurveName, currencyPair.toString());
if (definition == null) {
s_logger.error("Couldn't find FX forward curve definition called " + domesticCurveName + " with target " + currencyPair);
return null;
}
final FXForwardCurveSpecification fxForwardCurveSpec = fxCurveSpecificationSource.getSpecification(domesticCurveName, currencyPair.toString());
if (fxForwardCurveSpec == null) {
s_logger.error("Couldn't find FX forward curve specification called " + domesticCurveName + " with target " + currencyPair);
return null;
}
final ValueProperties fxForwardCurveProperties = ValueProperties.builder().with(ValuePropertyNames.CURVE, domesticCurveName).get();
final String foreignCurveName = foreignConfig.getYieldCurveNames()[0];
final ValueProperties foreignCurveProperties = getForeignCurveProperties(foreignConfig, foreignCurveName);
final FXForwardCurveInstrumentProvider provider = fxForwardCurveSpec.getCurveInstrumentProvider();
requirements.add(new ValueRequirement(ValueRequirementNames.FX_FORWARD_CURVE_MARKET_DATA, new ComputationTargetSpecification(currencyPair), fxForwardCurveProperties));
requirements.add(new ValueRequirement(provider.getDataFieldName(), provider.getSpotInstrument()));
requirements.add(new ValueRequirement(ValueRequirementNames.YIELD_CURVE, new ComputationTargetSpecification(foreignCurrency), foreignCurveProperties));
return requirements;
}
private ValueProperties getForeignCurveProperties(final MultiCurveCalculationConfig foreignConfig, final String foreignCurveName) {
return ValueProperties.builder()
.with(ValuePropertyNames.CURVE, foreignCurveName)
.with(ValuePropertyNames.CURVE_CALCULATION_CONFIG, foreignConfig.getCalculationConfigName()).get();
}
private ValueProperties getCurveProperties() {
return createValueProperties()
.with(ValuePropertyNames.CURVE_CALCULATION_METHOD, FX_IMPLIED)
.withAny(ValuePropertyNames.CURVE)
.withAny(ValuePropertyNames.CURVE_CALCULATION_CONFIG)
.withAny(MultiYieldCurvePropertiesAndDefaults.PROPERTY_ROOT_FINDER_ABSOLUTE_TOLERANCE)
.withAny(MultiYieldCurvePropertiesAndDefaults.PROPERTY_ROOT_FINDER_RELATIVE_TOLERANCE)
.withAny(MultiYieldCurvePropertiesAndDefaults.PROPERTY_ROOT_FINDER_MAX_ITERATIONS)
.withAny(MultiYieldCurvePropertiesAndDefaults.PROPERTY_DECOMPOSITION)
.withAny(MultiYieldCurvePropertiesAndDefaults.PROPERTY_USE_FINITE_DIFFERENCE)
.withAny(InterpolatedDataProperties.X_INTERPOLATOR_NAME)
.withAny(InterpolatedDataProperties.LEFT_X_EXTRAPOLATOR_NAME).withAny(InterpolatedDataProperties.RIGHT_X_EXTRAPOLATOR_NAME).get();
}
private ValueProperties getProperties() {
return createValueProperties()
.with(ValuePropertyNames.CURVE_CALCULATION_METHOD, FX_IMPLIED)
.withAny(ValuePropertyNames.CURVE_CALCULATION_CONFIG)
.withAny(MultiYieldCurvePropertiesAndDefaults.PROPERTY_ROOT_FINDER_ABSOLUTE_TOLERANCE)
.withAny(MultiYieldCurvePropertiesAndDefaults.PROPERTY_ROOT_FINDER_RELATIVE_TOLERANCE)
.withAny(MultiYieldCurvePropertiesAndDefaults.PROPERTY_ROOT_FINDER_MAX_ITERATIONS)
.withAny(MultiYieldCurvePropertiesAndDefaults.PROPERTY_DECOMPOSITION)
.withAny(MultiYieldCurvePropertiesAndDefaults.PROPERTY_USE_FINITE_DIFFERENCE)
.withAny(InterpolatedDataProperties.X_INTERPOLATOR_NAME)
.withAny(InterpolatedDataProperties.LEFT_X_EXTRAPOLATOR_NAME)
.withAny(InterpolatedDataProperties.RIGHT_X_EXTRAPOLATOR_NAME).get();
}
private ValueProperties getCurveProperties(final String curveCalculationConfigName, final String curveName, final String absoluteTolerance,
final String relativeTolerance, final String maxIterations, final String decomposition, final String useFiniteDifference, final String interpolatorName,
final String leftExtrapolatorName, final String rightExtrapolatorName) {
return createValueProperties()
.with(ValuePropertyNames.CURVE_CALCULATION_METHOD, FX_IMPLIED)
.with(ValuePropertyNames.CURVE, curveName)
.with(ValuePropertyNames.CURVE_CALCULATION_CONFIG, curveCalculationConfigName)
.with(MultiYieldCurvePropertiesAndDefaults.PROPERTY_ROOT_FINDER_ABSOLUTE_TOLERANCE, absoluteTolerance)
.with(MultiYieldCurvePropertiesAndDefaults.PROPERTY_ROOT_FINDER_RELATIVE_TOLERANCE, relativeTolerance)
.with(MultiYieldCurvePropertiesAndDefaults.PROPERTY_ROOT_FINDER_MAX_ITERATIONS, maxIterations)
.with(MultiYieldCurvePropertiesAndDefaults.PROPERTY_DECOMPOSITION, decomposition)
.with(MultiYieldCurvePropertiesAndDefaults.PROPERTY_USE_FINITE_DIFFERENCE, useFiniteDifference)
.with(InterpolatedDataProperties.X_INTERPOLATOR_NAME, interpolatorName)
.with(InterpolatedDataProperties.LEFT_X_EXTRAPOLATOR_NAME, leftExtrapolatorName)
.with(InterpolatedDataProperties.RIGHT_X_EXTRAPOLATOR_NAME, rightExtrapolatorName).get();
}
private ValueProperties getProperties(final String curveCalculationConfigName, final String absoluteTolerance, final String relativeTolerance,
final String maxIterations, final String decomposition, final String useFiniteDifference, final String interpolatorName, final String leftExtrapolatorName,
final String rightExtrapolatorName) {
return createValueProperties()
.with(ValuePropertyNames.CURVE_CALCULATION_METHOD, FX_IMPLIED)
.with(ValuePropertyNames.CURVE_CALCULATION_CONFIG, curveCalculationConfigName)
.with(MultiYieldCurvePropertiesAndDefaults.PROPERTY_ROOT_FINDER_ABSOLUTE_TOLERANCE, absoluteTolerance)
.with(MultiYieldCurvePropertiesAndDefaults.PROPERTY_ROOT_FINDER_RELATIVE_TOLERANCE, relativeTolerance)
.with(MultiYieldCurvePropertiesAndDefaults.PROPERTY_ROOT_FINDER_MAX_ITERATIONS, maxIterations)
.with(MultiYieldCurvePropertiesAndDefaults.PROPERTY_DECOMPOSITION, decomposition)
.with(MultiYieldCurvePropertiesAndDefaults.PROPERTY_USE_FINITE_DIFFERENCE, useFiniteDifference)
.with(InterpolatedDataProperties.X_INTERPOLATOR_NAME, interpolatorName)
.with(InterpolatedDataProperties.LEFT_X_EXTRAPOLATOR_NAME, leftExtrapolatorName)
.with(InterpolatedDataProperties.RIGHT_X_EXTRAPOLATOR_NAME, rightExtrapolatorName).get();
}
//TODO determine domestic and notional from dominance data
private ForexForward getFXForward(final Currency ccy1, final Currency ccy2, final double paymentTime, final double spotFX, final double forwardFX, final String curveName1, final String curveName2) {
final PaymentFixed paymentCurrency1 = new PaymentFixed(ccy1, paymentTime, 1, curveName1);
final PaymentFixed paymentCurrency2 = new PaymentFixed(ccy2, paymentTime, -1. / forwardFX, curveName2);
return new ForexForward(paymentCurrency1, paymentCurrency2, spotFX);
}
}
| Correcting formatting
| projects/OG-Financial/src/com/opengamma/financial/analytics/model/curve/interestrate/FXImpliedYieldCurveFunction.java | Correcting formatting | <ide><path>rojects/OG-Financial/src/com/opengamma/financial/analytics/model/curve/interestrate/FXImpliedYieldCurveFunction.java
<ide> .withAny(MultiYieldCurvePropertiesAndDefaults.PROPERTY_DECOMPOSITION)
<ide> .withAny(MultiYieldCurvePropertiesAndDefaults.PROPERTY_USE_FINITE_DIFFERENCE)
<ide> .withAny(InterpolatedDataProperties.X_INTERPOLATOR_NAME)
<del> .withAny(InterpolatedDataProperties.LEFT_X_EXTRAPOLATOR_NAME).withAny(InterpolatedDataProperties.RIGHT_X_EXTRAPOLATOR_NAME).get();
<add> .withAny(InterpolatedDataProperties.LEFT_X_EXTRAPOLATOR_NAME)
<add> .withAny(InterpolatedDataProperties.RIGHT_X_EXTRAPOLATOR_NAME).get();
<ide> }
<ide>
<ide> private ValueProperties getProperties() { |
|
JavaScript | apache-2.0 | 17ea8d5cc85fc362d3ad2b307acf20944f4ef5ef | 0 | Ideolys/carbone,Ideolys/carbone | var dateFormatter = require('../formatters/date');
var conditionFormatter = require('../formatters/condition');
var stringFormatter = require('../formatters/string');
var arrayFormatter = require('../formatters/array');
var numberFormatter = require('../formatters/number');
var helper = require('../lib/helper');
describe('formatter', function () {
describe('convDate', function () {
it('should accept use this.lang to set convert date', function () {
helper.assert(dateFormatter.convDate.call({lang : 'en'}, '20101201', 'YYYYMMDD', 'L'), '12/01/2010');
helper.assert(dateFormatter.convDate.call({lang : 'fr'}, '20101201', 'YYYYMMDD', 'L'), '01/12/2010');
});
it('should return null or undefined if value is null or undefined', function () {
helper.assert(dateFormatter.convDate.call({lang : 'en'}, undefined, 'YYYYMMDD', 'L'), undefined);
helper.assert(dateFormatter.convDate.call({lang : 'fr'}, null, 'YYYYMMDD', 'L'), null);
});
it('should convert unix timestamp', function () {
helper.assert(dateFormatter.convDate.call({lang : 'en'}, 1318781876, 'X', 'LLLL'), 'Sunday, October 16, 2011 6:17 PM');
helper.assert(dateFormatter.convDate.call({lang : 'fr'}, 1318781876, 'X', 'LLLL'), 'dimanche 16 octobre 2011 18:17');
});
});
describe('formatD', function () {
it('should accept use this.lang to set convert date', function () {
helper.assert(dateFormatter.formatD.call({lang : 'en'}, '20101201', 'L', 'YYYYMMDD'), '12/01/2010');
helper.assert(dateFormatter.formatD.call({lang : 'fr'}, '20101201', 'L', 'YYYYMMDD'), '01/12/2010');
});
it('should return null or undefined if value is null or undefined', function () {
helper.assert(dateFormatter.formatD.call({lang : 'en'}, undefined, 'L', 'YYYYMMDD'), undefined);
helper.assert(dateFormatter.formatD.call({lang : 'fr'}, null, 'L', 'YYYYMMDD'), null);
});
it('should convert unix timestamp', function () {
helper.assert(dateFormatter.formatD.call({lang : 'en'}, 1318781876, 'LLLL', 'X'), 'Sunday, October 16, 2011 6:17 PM');
helper.assert(dateFormatter.formatD.call({lang : 'fr'}, 1318781876, 'LLLL', 'X'), 'dimanche 16 octobre 2011 18:17');
});
it('should consider input format is ISO 8601 by default if not provided', function () {
helper.assert(dateFormatter.formatD.call({lang : 'en'}, '20101201', 'L'), '12/01/2010');
helper.assert(dateFormatter.formatD.call({lang : 'fr'}, '20101201', 'L'), '01/12/2010');
helper.assert(dateFormatter.formatD.call({lang : 'en'}, '2017-05-10T15:57:23.769561+03:00', 'LLLL'), 'Wednesday, May 10, 2017 2:57 PM');
helper.assert(dateFormatter.formatD.call({lang : 'en'}, '2017-05-10 15:57:23.769561+03:00', 'LLLL'), 'Wednesday, May 10, 2017 2:57 PM');
helper.assert(dateFormatter.formatD.call({lang : 'en'}, '1997-12-17 07:37:16-08', 'LLLL'), 'Wednesday, December 17, 1997 4:37 PM');
});
it('should accepts real locales', function () {
helper.assert(dateFormatter.formatD.call({lang : 'en-GB'}, '20101201', 'L'), '01/12/2010');
helper.assert(dateFormatter.formatD.call({lang : 'en-gb'}, '20101201', 'L'), '01/12/2010');
helper.assert(dateFormatter.formatD.call({lang : 'en-US'}, '20101201', 'L'), '12/01/2010');
helper.assert(dateFormatter.formatD.call({lang : 'fr-CA'}, '20101201', 'L'), '2010-12-01');
helper.assert(dateFormatter.formatD.call({lang : 'fr-FR'}, '20101201', 'L'), '01/12/2010');
});
});
describe('convCRLF', function () {
it('should convert LF and CR in odt', function () {
helper.assert(stringFormatter.convCRLF.call({extension : 'odt'}, 'qsdqsd \n sd \r\n qsd \n sq'), 'qsdqsd <text:line-break/> sd <text:line-break/> qsd <text:line-break/> sq');
});
it('should convert LF and CR in docx', function () {
helper.assert(stringFormatter.convCRLF.call({extension : 'docx'}, 'qsdqsd \n'), 'qsdqsd </w:t><w:br/><w:t>');
});
});
describe('ifEmpty', function () {
it('should show a message if data is empty. It should stop propagation to next formatter', function () {
var _context = {};
helper.assert(callWithContext(conditionFormatter.ifEmpty, _context, '' , 'msgIfEmpty'), 'msgIfEmpty');
helper.assert(_context.stopPropagation, true);
helper.assert(callWithContext(conditionFormatter.ifEmpty, _context, null , 'msgIfEmpty'), 'msgIfEmpty');
helper.assert(_context.stopPropagation, true);
helper.assert(callWithContext(conditionFormatter.ifEmpty, _context, undefined, 'msgIfEmpty'), 'msgIfEmpty');
helper.assert(_context.stopPropagation, true);
helper.assert(callWithContext(conditionFormatter.ifEmpty, _context, [] , 'msgIfEmpty'), 'msgIfEmpty');
helper.assert(_context.stopPropagation, true);
helper.assert(callWithContext(conditionFormatter.ifEmpty, _context, NaN , 'msgIfEmpty'), 'msgIfEmpty');
helper.assert(_context.stopPropagation, true);
helper.assert(callWithContext(conditionFormatter.ifEmpty, _context, {} , 'msgIfEmpty'), 'msgIfEmpty');
helper.assert(_context.stopPropagation, true);
helper.assert(callWithContext(conditionFormatter.ifEmpty, _context, {} , 'msgIfEmpty', 'true'), 'msgIfEmpty');
helper.assert(_context.stopPropagation, false);
helper.assert(callWithContext(conditionFormatter.ifEmpty, _context, {} , 'msgIfEmpty', true), 'msgIfEmpty');
helper.assert(_context.stopPropagation, false);
});
it('should return data if the message is not empty... and keep on propagation to next formatter', function () {
var _context = {};
helper.assert(callWithContext(conditionFormatter.ifEmpty, _context, 0 , 'msgIfEmpty'), 0);
helper.assert(_context.stopPropagation, false);
var _date = new Date();
helper.assert(callWithContext(conditionFormatter.ifEmpty, _context, _date , 'msgIfEmpty'), _date);
helper.assert(_context.stopPropagation, false);
helper.assert(callWithContext(conditionFormatter.ifEmpty, _context, 'sdsd' , 'msgIfEmpty'), 'sdsd');
helper.assert(_context.stopPropagation, false);
helper.assert(callWithContext(conditionFormatter.ifEmpty, _context, 12.33 , 'msgIfEmpty'), 12.33);
helper.assert(_context.stopPropagation, false);
helper.assert(callWithContext(conditionFormatter.ifEmpty, _context, true , 'msgIfEmpty'), true);
helper.assert(_context.stopPropagation, false);
helper.assert(callWithContext(conditionFormatter.ifEmpty, _context, [12, 23] , 'msgIfEmpty'), [12, 23]);
helper.assert(_context.stopPropagation, false);
helper.assert(callWithContext(conditionFormatter.ifEmpty, _context, {d : 'd'} , 'msgIfEmpty'), {d : 'd'});
helper.assert(_context.stopPropagation, false);
});
});
describe('ifEqual', function () {
it('should show a message if data is equal to a variable', function () {
var _context = {};
helper.assert(callWithContext(conditionFormatter.ifEqual, _context, 0, 0, 'msgIfTrue'), 'msgIfTrue');
helper.assert(_context.stopPropagation, true);
helper.assert(callWithContext(conditionFormatter.ifEqual, _context, 0, '0', 'msgIfTrue'), 'msgIfTrue');
helper.assert(_context.stopPropagation, true);
helper.assert(callWithContext(conditionFormatter.ifEqual, _context, true, true, 'msgIfTrue'), 'msgIfTrue');
helper.assert(_context.stopPropagation, true);
helper.assert(callWithContext(conditionFormatter.ifEqual, _context, 'true', 'true', 'msgIfTrue'), 'msgIfTrue');
helper.assert(_context.stopPropagation, true);
helper.assert(callWithContext(conditionFormatter.ifEqual, _context, true, 'true', 'msgIfTrue'), 'msgIfTrue');
helper.assert(_context.stopPropagation, true);
helper.assert(callWithContext(conditionFormatter.ifEqual, _context, false, 'false', 'msgIfTrue'), 'msgIfTrue');
helper.assert(_context.stopPropagation, true);
helper.assert(callWithContext(conditionFormatter.ifEqual, _context, 'false', 'false', 'msgIfTrue'), 'msgIfTrue');
helper.assert(_context.stopPropagation, true);
helper.assert(callWithContext(conditionFormatter.ifEqual, _context, false, false, 'msgIfTrue'), 'msgIfTrue');
helper.assert(_context.stopPropagation, true);
helper.assert(callWithContext(conditionFormatter.ifEqual, _context, false, 'false', 'msgIfTrue'), 'msgIfTrue');
helper.assert(_context.stopPropagation, true);
helper.assert(callWithContext(conditionFormatter.ifEqual, _context, 'titi', 'titi', 'msgIfTrue'), 'msgIfTrue');
helper.assert(_context.stopPropagation, true);
});
it('should propagate to next formatter if continueOnSuccess is true', function () {
var _context = {};
helper.assert(callWithContext(conditionFormatter.ifEqual, _context, 0, 0, 'msgIfTrue', 'true'), 'msgIfTrue');
helper.assert(_context.stopPropagation, false);
helper.assert(callWithContext(conditionFormatter.ifEqual, _context, 0, '0', 'msgIfTrue', 'true'), 'msgIfTrue');
helper.assert(_context.stopPropagation, false);
helper.assert(callWithContext(conditionFormatter.ifEqual, _context, true, true, 'msgIfTrue', 'true'), 'msgIfTrue');
helper.assert(_context.stopPropagation, false);
helper.assert(callWithContext(conditionFormatter.ifEqual, _context, false, false, 'msgIfTrue', 'true'), 'msgIfTrue');
helper.assert(_context.stopPropagation, false);
helper.assert(callWithContext(conditionFormatter.ifEqual, _context, 'titi', 'titi', 'msgIfTrue', 'true'), 'msgIfTrue');
helper.assert(_context.stopPropagation, false);
helper.assert(callWithContext(conditionFormatter.ifEqual, _context, 'titi', 'titi', 'msgIfTrue', true), 'msgIfTrue');
helper.assert(_context.stopPropagation, false);
});
it('should return data if data is not equal to a variable', function () {
var _context = {};
helper.assert(callWithContext(conditionFormatter.ifEqual, _context, 0, 3, 'msgIfTrue'), 0);
helper.assert(_context.stopPropagation, false);
helper.assert(callWithContext(conditionFormatter.ifEqual, _context, 0, '1', 'msgIfTrue'), 0);
helper.assert(_context.stopPropagation, false);
helper.assert(callWithContext(conditionFormatter.ifEqual, _context, true, false, 'msgIfTrue'), true);
helper.assert(_context.stopPropagation, false);
helper.assert(callWithContext(conditionFormatter.ifEqual, _context, 'true', false, 'msgIfTrue'), 'true');
helper.assert(_context.stopPropagation, false);
helper.assert(callWithContext(conditionFormatter.ifEqual, _context, 'false', 'true', 'msgIfTrue'), 'false');
helper.assert(_context.stopPropagation, false);
helper.assert(callWithContext(conditionFormatter.ifEqual, _context, false, true, 'msgIfTrue'), false);
helper.assert(_context.stopPropagation, false);
helper.assert(callWithContext(conditionFormatter.ifEqual, _context, 'titi', 'toto', 'msgIfTrue'), 'titi');
helper.assert(_context.stopPropagation, false);
});
});
describe('ifContains', function () {
it('should show a message if data contains a variable', function () {
var _context = {};
helper.assert(callWithContext(conditionFormatter.ifContain, _context, 'car is broken', 'is', 'msgIfTrue'), 'msgIfTrue');
helper.assert(_context.stopPropagation, true);
helper.assert(callWithContext(conditionFormatter.ifContain, _context, 'car is broken', 'car is', 'msgIfTrue'), 'msgIfTrue');
helper.assert(_context.stopPropagation, true);
helper.assert(callWithContext(conditionFormatter.ifContain, _context, [1, 2, 'toto'], 'toto', 'msgIfTrue'), 'msgIfTrue');
helper.assert(_context.stopPropagation, true);
helper.assert(callWithContext(conditionFormatter.ifContain, _context, [1, 2, 'toto'], 2, 'msgIfTrue'), 'msgIfTrue');
helper.assert(_context.stopPropagation, true);
});
it('should propagate to next formatter if continueOnSuccess is true', function () {
var _context = {};
helper.assert(callWithContext(conditionFormatter.ifContain, _context, 'car is broken', 'is', 'msgIfTrue', 'true'), 'msgIfTrue');
helper.assert(_context.stopPropagation, false);
helper.assert(callWithContext(conditionFormatter.ifContain, _context, 'car is broken', 'car is', 'msgIfTrue', 'true'), 'msgIfTrue');
helper.assert(_context.stopPropagation, false);
helper.assert(callWithContext(conditionFormatter.ifContain, _context, [1, 2, 'toto'], 'toto', 'msgIfTrue', 'true'), 'msgIfTrue');
helper.assert(_context.stopPropagation, false);
helper.assert(callWithContext(conditionFormatter.ifContain, _context, [1, 2, 'toto'], 2, 'msgIfTrue', 'true'), 'msgIfTrue');
helper.assert(_context.stopPropagation, false);
helper.assert(callWithContext(conditionFormatter.ifContain, _context, [1, 2, 'toto'], 2, 'msgIfTrue', true), 'msgIfTrue');
helper.assert(_context.stopPropagation, false);
});
it('should return data if data does not contain the variable', function () {
var _context = {};
helper.assert(callWithContext(conditionFormatter.ifContain, _context, 'car is broken', 'are', 'msgIfTrue'), 'car is broken');
helper.assert(_context.stopPropagation, false);
helper.assert(callWithContext(conditionFormatter.ifContain, _context, 'car is broken', 'caris', 'msgIfTrue'), 'car is broken');
helper.assert(_context.stopPropagation, false);
helper.assert(callWithContext(conditionFormatter.ifContain, _context, [1, 2, 'toto'], 'titi', 'msgIfTrue'), [1, 2, 'toto']);
helper.assert(_context.stopPropagation, false);
helper.assert(callWithContext(conditionFormatter.ifContain, _context, [], 3, 'msgIfTrue'), []);
helper.assert(_context.stopPropagation, false);
});
it('should not crash if data is not a String or an Array. It should transfer to next formatter', function () {
var _context = {};
helper.assert(callWithContext(conditionFormatter.ifContain, _context, null, 'is', 'msgIfTrue'), null);
helper.assert(_context.stopPropagation, false);
helper.assert(callWithContext(conditionFormatter.ifContain, _context, undefined, 'is', 'msgIfTrue'), undefined);
helper.assert(_context.stopPropagation, false);
helper.assert(callWithContext(conditionFormatter.ifContain, _context, 12, 'titi', 'msgIfTrue'), 12);
helper.assert(_context.stopPropagation, false);
helper.assert(callWithContext(conditionFormatter.ifContain, _context, {toto : 2 }, 3, 'msgIfTrue'), {toto : 2 });
helper.assert(_context.stopPropagation, false);
});
});
describe('ifEQ', function () {
it('should turn the `isConditionTrue` to True if a data is equal to a variable', function () {
const _dataSet = [
[0, 0],
[0, '0'],
[true, true],
['true', 'true'],
[true, 'true'],
['false', 'false'],
[false, 'false'],
[false, false],
['titi', 'titi'],
[undefined, undefined],
[null, null],
// object identiques, it is comparing "[object Object]" === "[object Object]"
[{value : 10, name : 'john', address : { name : '123 street'} }, {value : 10, name : 'john', address : { name : '123 street'}}],
[{ name : '85 street'}, {value : 10, name : 'wick', address : { name : '321 street'}}],
[[1, 2, 3, 4, 6, 7, 8, 9], [1, 2, 3, 4, 6, 7, 8, 9]]
];
var _context = {};
for (let i = 0, n = _dataSet.length; i < n; i++) {
const el = _dataSet[i];
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifEQ, _context, el[0], el[1]);
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
}
});
it('should turn the `isConditionTrue` to false if the data is not equal to a variable', function () {
var _context = {};
const _dataSet = [
[0, 3],
[0, '1'],
[true, false],
['true', false],
['false', 'true'],
[false, true],
['titi', 'toto'],
[undefined, 'titi'],
['titi', null],
[[1, 2, 3], [1, 3]],
];
for (let i = 0, n = _dataSet.length; i < n; i++) {
const el = _dataSet[i];
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifEQ, _context, el[0], el[1]);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
}
});
});
describe('ifNE', function () {
it('should turn the `isConditionTrue` to false if a data is equal to a variable', function () {
var _context = {};
const _dataSet = [
[0, 0],
[0, '0'],
[true, true],
['true', 'true'],
[true, 'true'],
[false, 'false'],
['false', 'false'],
[false, false],
[false, 'false'],
['titi', 'titi'],
[undefined, undefined],
[null, null],
// Objects appear as "[object Object]"
[{value : 10, name : 'john', address : { name : '123 street'} }, {value : 10, name : 'john', address : { name : '123 street'}}],
[{value : 20, name : 'Eric', address : { name : '85 street'} }, {value : 10, name : 'wick', address : { name : '321 street'}}],
[[1, 2, 3, 4, 6, 7, 8, 9], [1, 2, 3, 4, 6, 7, 8, 9]],
];
for (let i = 0, n = _dataSet.length; i < n; i++) {
const el = _dataSet[i];
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifNE, _context, el[0], el[1]);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
}
});
it('should turn the `isConditionTrue` to false if the data is not equal to a variable', function () {
var _context = {};
const _dataSet = [
[0, 3],
[0, '1'],
[true, false],
['true', false],
['false', 'true'],
[false, true],
['titi', 'toto'],
[undefined, 'titi'],
['titi', null],
[[1, 2, 3, 4, 6, 7, 8, 9], [1, 2, 3, 6, 7, 8, 9]],
];
for (let i = 0, n = _dataSet.length; i < n; i++) {
const el = _dataSet[i];
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifNE, _context, el[0], el[1]);
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
}
});
});
describe('ifGT', function () {
it('should matches values, string.length, array.length or object.length that are greater than a specified value', function () {
let _context = {isConditionTrue : false};
const _dataSet = [
[50, -29],
[1290, 768],
['1234', '1'],
['This is a long string', 'Hello'],
['Hello1234', '1'],
[[1, 2, 3, 4, 5], [1, 2, 3]],
[['apple', 'banana', 'jackfruit'], ['tomato', 'cabbage']],
[{id : 2, name : 'John', lastname : 'Wick', city : 'Paris'}, {id : 3, name : 'John'}],
];
for (let i = 0, n = _dataSet.length; i < n; i++) {
const el = _dataSet[i];
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifGT, _context, el[0], el[1]);
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
}
});
it('should matches values, string.length, array.length or object.length that are NOT greater than a specified value', function () {
let _context = {isConditionTrue : false};
const _dataSet = [
[-23, 19],
[1, 768],
[0, 0],
['1' , '1234'],
['Short sentence', 'Hello, this is a long sentence'],
[[1, 2], [1, 2, 3, 4, 5, 6]],
[[1, 2, 3, 4, 5], [1, 2, 3, 4, 6]],
[['apple', 'banana'], ['tomato', 'cabbage', 'jackfruit', 'berry']],
[{id : 2, name : 'John'}, {id : 3, name : 'John', lastname : 'Wick', city : 'Paris'}],
[{id : 2, name : 'John'}, null],
[null, 'Lion and giraffe'],
['Lion and giraffe', null],
[null, null],
[{id : 2, name : 'John'}, undefined],
[undefined, 'Lion and giraffe'],
['Lion and giraffe', undefined],
[undefined, undefined],
[{id : 2, name : 'John'}, {id : 3, name : 'Wick'}],
];
for (let i = 0, n = _dataSet.length; i < n; i++) {
const el = _dataSet[i];
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifGT, _context, el[0], el[1]);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
}
});
});
describe('ifGTE', function () {
it('Matches values, string.length, array.length or object.length that are greater than or equal to a specified value', function () {
let _context = {isConditionTrue : false};
let _dataSet = [
[50, -29],
[0, 0],
[1290, 768],
['1234', '1'],
['This is a long string', 'Hello'],
['ThisEqual', 'Hello1234'],
['Hello1234', '1'],
[[1, 2, 3, 4, 5], [1, 2, 3]],
[[1, 2, 3, 4, 5], [1, 2, 3, 4, 6]],
[['apple', 'banana', 'jackfruit'], ['tomato', 'cabbage']],
[['apple', 'banana'], ['tomato', 'cabbage']],
[{id : 2, name : 'John', lastname : 'Wick', city : 'Paris'}, {id : 3, name : 'John'}],
[{id : 2, name : 'John'}, {id : 3, name : 'Wick'}],
];
for (let i = 0, n = _dataSet.length; i < n; i++) {
const el = _dataSet[i];
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifGTE, _context, el[0], el[1]);
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
}
});
it('should matches values, string.length, array.length or object.length that are NOT greater than a specified value', function () {
let _context = {isConditionTrue : false};
const _dataSet = [
[-23, 19],
[1, 768],
['1' , '1234'],
['Short sentence', 'Hello, this is a long sentence'],
[[1, 2], [1, 2, 3, 4, 5, 6]],
[['apple', 'banana'], ['tomato', 'cabbage', 'jackfruit', 'berry']],
[{id : 2, name : 'John'}, {id : 3, name : 'John', lastname : 'Wick', city : 'Paris'}],
[{id : 2, name : 'John'}, null],
[null, 'Lion and giraffe'],
['Lion and giraffe', null],
[null, null],
[{id : 2, name : 'John'}, undefined],
[undefined, 'Lion and giraffe'],
['Lion and giraffe', undefined],
[undefined, undefined],
];
for (let i = 0, n = _dataSet.length; i < n; i++) {
const el = _dataSet[i];
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifGTE, _context, el[0], el[1]);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
}
});
});
describe('ifLT', function () {
it ('should matches values, string.length, array.length or object.length that are less than a specified value', function () {
let _context = {isConditionTrue : false};
const _dataSet = [
[-23, 19],
[1, 768],
['1' , '1234'],
['Short sentence', 'Hello, this is a long sentence'],
[[1, 2], [1, 2, 3, 4, 5, 6]],
[['apple', 'banana'], ['tomato', 'cabbage', 'jackfruit', 'berry']],
[{id : 2, name : 'John'}, {id : 3, name : 'John', lastname : 'Wick', city : 'Paris'}],
];
for (let i = 0, n = _dataSet.length; i < n; i++) {
const el = _dataSet[i];
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLT, _context, el[0], el[1]);
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
}
});
it('should matches values, string.length, array.length or object.length that are NOT less than a specified value', function () {
let _context = {isConditionTrue : false};
const _dataSet = [
[50, -29],
[0, 0],
[1290, 768],
['1234', '1'],
['This is a long string', 'Hello'],
['ThisEqual', 'Hello1234'],
['Hello1234', '1'],
[[1, 2, 3, 4, 5], [1, 2, 3]],
[[1, 2, 3, 4, 5], [1, 2, 3, 4, 6]],
[['apple', 'banana', 'jackfruit'], ['tomato', 'cabbage']],
[['apple', 'banana'], ['tomato', 'cabbage']],
[{id : 2, name : 'John', lastname : 'Wick', city : 'Paris'}, {id : 3, name : 'John'}],
[{id : 2, name : 'John'}, {id : 3, name : 'Wick'}],
[{id : 2, name : 'John'}, null],
[null, 'Lion and giraffe'],
['Lion and giraffe', null],
[null, null],
[{id : 2, name : 'John'}, undefined],
[undefined, 'Lion and giraffe'],
['Lion and giraffe', undefined],
[undefined, undefined],
];
for (let i = 0, n = _dataSet.length; i < n; i++) {
const el = _dataSet[i];
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLT, _context, el[0], el[1]);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
}
});
});
describe('ifLTE', function () {
it('should matches values, string.length, array.length or object.length that are less than or equal to a specified value', function () {
let _context = {isConditionTrue : false};
callWithContext(conditionFormatter.ifLTE, _context, -23, 19);
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLTE, _context, 1, 768);
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLTE, _context, 0, 0);
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLTE, _context, '1' , '1234');
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLTE, _context, 'Short sentence', 'Hello, this is a long sentence');
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLTE, _context, 'ThisEqual', 'Hello1234');
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLTE, _context, [1, 2], [1, 2, 3, 4, 5, 6]);
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLTE, _context, [1, 2, 3, 4, 5], [1, 2, 3, 4, 6]);
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLTE, _context, ['apple', 'banana'], ['tomato', 'cabbage', 'jackfruit', 'berry']);
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLTE, _context, ['apple', 'banana'], ['tomato', 'cabbage']);
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLTE, _context, {id : 2, name : 'John'}, {id : 3, name : 'John', lastname : 'Wick', city : 'Paris'});
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLTE, _context, {id : 2, name : 'John'}, {id : 3, name : 'Wick'});
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
});
it('should matches values, string.length, array.length or object.length that are NOT less than or equal to a specified value', function () {
let _context = {isConditionTrue : false};
callWithContext(conditionFormatter.ifLTE, _context, 50, -29);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLTE, _context, 1290, 768);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLTE, _context, '1234', '1');
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLTE, _context, 'This is a long string', 'Hello');
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLTE, _context, 'Hello1234', '1');
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLTE, _context, [1, 2, 3, 4, 5], [1, 2, 3]);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLTE, _context, ['apple', 'banana', 'jackfruit'], ['tomato', 'cabbage']);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLTE, _context, {id : 2, name : 'John', lastname : 'Wick', city : 'Paris'}, {id : 3, name : 'John'});
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLTE, _context, {id : 2, name : 'John'}, null);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLTE, _context, null, 'Lion and giraffe');
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLTE, _context, 'Lion and giraffe', null);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLTE, _context, null, null);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLTE, _context, {id : 2, name : 'John'}, undefined);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLTE, _context, undefined, 'Lion and giraffe');
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLTE, _context, 'Lion and giraffe', undefined);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLTE, _context, undefined, undefined);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
});
});
describe('ifIN', function () {
it('Matches any of the values specified in an array or string', function () {
var _context = {};
callWithContext(conditionFormatter.ifIN, _context, 'car is broken', 'is');
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
callWithContext(conditionFormatter.ifIN, _context, 'car is broken', 'car is');
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
callWithContext(conditionFormatter.ifIN, _context, [1, 2, 'toto'], 'toto');
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
callWithContext(conditionFormatter.ifIN, _context, [1, 2, 'toto'], 2);
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
});
it('Matches none of the values specified in an array or string', function () {
var _context = {};
callWithContext(conditionFormatter.ifIN, _context, 'car is broken', 'are');
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
callWithContext(conditionFormatter.ifIN, _context, 'car is broken', 'caris');
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
callWithContext(conditionFormatter.ifIN, _context, [1, 2, 'toto'], 'titi');
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
callWithContext(conditionFormatter.ifIN, _context, [], 3);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
callWithContext(conditionFormatter.ifIN, _context, null, 'titi');
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
callWithContext(conditionFormatter.ifIN, _context, 'titi', null);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
callWithContext(conditionFormatter.ifIN, _context, null, null);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
callWithContext(conditionFormatter.ifIN, _context, undefined, null);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
callWithContext(conditionFormatter.ifIN, _context, undefined, 'titi');
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
callWithContext(conditionFormatter.ifIN, _context, 'titi', undefined);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
callWithContext(conditionFormatter.ifIN, _context, undefined, undefined);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
callWithContext(conditionFormatter.ifIN, _context, 12, 'titi');
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
callWithContext(conditionFormatter.ifIN, _context, {toto : 2 }, 3);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
});
});
describe('ifNIN', function () {
it('should matches none of the values specified in an array or string', function () {
var _context = {};
callWithContext(conditionFormatter.ifNIN, _context, 'car is broken', 'are');
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
callWithContext(conditionFormatter.ifNIN, _context, 'car is broken', 'caris');
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
callWithContext(conditionFormatter.ifNIN, _context, [1, 2, 'toto'], 'titi');
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
callWithContext(conditionFormatter.ifNIN, _context, [], 3);
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
});
it('should matches any of the values specified in an array or string', function () {
var _context = {};
callWithContext(conditionFormatter.ifNIN, _context, 'car is broken', 'is');
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
callWithContext(conditionFormatter.ifNIN, _context, 'car is broken', 'car is');
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
callWithContext(conditionFormatter.ifNIN, _context, [1, 2, 'toto'], 'toto');
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
callWithContext(conditionFormatter.ifNIN, _context, [1, 2, 'toto'], 2);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
callWithContext(conditionFormatter.ifNIN, _context, null, 'titi');
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
callWithContext(conditionFormatter.ifNIN, _context, 'titi', null);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
callWithContext(conditionFormatter.ifNIN, _context, null, null);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
callWithContext(conditionFormatter.ifNIN, _context, undefined, null);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
callWithContext(conditionFormatter.ifNIN, _context, undefined, 'titi');
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
callWithContext(conditionFormatter.ifNIN, _context, 'titi', undefined);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
callWithContext(conditionFormatter.ifNIN, _context, undefined, undefined);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
callWithContext(conditionFormatter.ifNIN, _context, 12, 'titi');
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
callWithContext(conditionFormatter.ifNIN, _context, {toto : 2 }, 3);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
});
});
describe('ifEM', function () {
it ('should matches empty values, string, arrays or objects', function () {
let _context = {isConditionTrue : false};
callWithContext(conditionFormatter.ifEM, _context, '');
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifEM, _context, null);
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifEM, _context, undefined);
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifEM, _context, []);
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifEM, _context, NaN);
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifEM, _context, {});
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
});
it('should matches not empty values, string, arrays or objects', function () {
var _context = {};
callWithContext(conditionFormatter.ifEM, _context, 0);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifEM, _context, new Date());
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifEM, _context, 'sdsd');
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifEM, _context, 12.33);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifEM, _context, true);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifEM, _context, [12, 23]);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifEM, _context, {d : 'd'});
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
});
});
describe('ifNEM', function () {
it('should matches not empty values, string, arrays or objects', function () {
var _context = {};
callWithContext(conditionFormatter.ifNEM, _context, 0);
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifNEM, _context, new Date());
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifNEM, _context, 'sdsd');
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifNEM, _context, 12.33);
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifNEM, _context, true);
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifNEM, _context, [12, 23]);
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifNEM, _context, {d : 'd'});
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
});
it ('should matches empty values, string, arrays or objects', function () {
let _context = {isConditionTrue : false};
callWithContext(conditionFormatter.ifNEM, _context, '');
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifNEM, _context, null);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifNEM, _context, undefined);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifNEM, _context, []);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifNEM, _context, NaN);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifNEM, _context, {});
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
});
});
describe('Combined conditions', function () {
describe('AND', function () {
it('should be true | ifNE / ifEQ / ifGTE / ifGT / ifLT / ifLTE / ifIN / ifNIN / ifEM / ifNEM', function () {
let _context = {isConditionTrue : false};
callWithContext(conditionFormatter.ifNE, _context, 'delorean', 'tesla');
callWithContext(conditionFormatter.and, _context);
callWithContext(conditionFormatter.ifEQ, _context, 'dragon', 'dragon');
callWithContext(conditionFormatter.and, _context);
callWithContext(conditionFormatter.ifGT, _context, 20, 1);
callWithContext(conditionFormatter.and, _context);
callWithContext(conditionFormatter.ifGTE, _context, -100, -100);
callWithContext(conditionFormatter.and, _context);
callWithContext(conditionFormatter.ifLT, _context, -1000, 30);
callWithContext(conditionFormatter.and, _context);
callWithContext(conditionFormatter.ifLTE, _context, 13987, 13987);
callWithContext(conditionFormatter.and, _context);
callWithContext(conditionFormatter.ifIN, _context, ['potatoes', 'bananas', 'tomatoes'], 'tomatoes');
callWithContext(conditionFormatter.and, _context);
callWithContext(conditionFormatter.ifNIN, _context, ['potatoes', 'bananas', 'tomatoes'], 'grapes');
callWithContext(conditionFormatter.and, _context);
callWithContext(conditionFormatter.ifEM, _context, null);
callWithContext(conditionFormatter.and, _context);
callWithContext(conditionFormatter.ifNEM, _context, new Date());
callWithContext(conditionFormatter.and, _context);
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.isAndOperator, true);
});
it('should be false | ifNE / ifNIN', function () {
let _context = {isConditionTrue : false};
callWithContext(conditionFormatter.ifNE, _context, 'delorean', 'tesla');
callWithContext(conditionFormatter.and, _context);
callWithContext(conditionFormatter.ifNIN, _context, ['potatoes', 'bananas', 'tomatoes'], 'tomatoes');
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.isAndOperator, true);
});
it('should be false | ifEQ / ifEM / ifNEM', function () {
let _context = {isConditionTrue : false};
callWithContext(conditionFormatter.ifEQ, _context, 'delorean', 'delorean');
callWithContext(conditionFormatter.and, _context);
callWithContext(conditionFormatter.ifEM, _context, []);
callWithContext(conditionFormatter.and, _context);
callWithContext(conditionFormatter.ifEM, _context, {id : '1'});
callWithContext(conditionFormatter.and, _context);
callWithContext(conditionFormatter.ifNEM, _context, 'Hey');
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.isAndOperator, true);
});
});
describe('OR', function () {
it('should be true | ifNE / ifNIN', function () {
let _context = {isConditionTrue : false};
callWithContext(conditionFormatter.ifNE, _context, 'delorean', 'tesla');
callWithContext(conditionFormatter.or, _context);
callWithContext(conditionFormatter.ifNIN, _context, ['potatoes', 'bananas', 'tomatoes'], 'tomatoes');
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.isAndOperator, false);
});
it('should be true | ifEQ / ifNEM / ifEM', function () {
let _context = {isConditionTrue : false};
callWithContext(conditionFormatter.ifEQ, _context, 'delorean', 'tesla');
callWithContext(conditionFormatter.or, _context);
callWithContext(conditionFormatter.ifNEM, _context, [1, 2, 3, 4, 5]);
callWithContext(conditionFormatter.or, _context);
callWithContext(conditionFormatter.ifEM, _context, {});
callWithContext(conditionFormatter.or, _context);
callWithContext(conditionFormatter.ifNEM, _context, 'Hey');
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.isAndOperator, false);
});
});
describe('AND/OR/SHOW/ELSE SHOW', function () {
it('Should SHOW + or', function () {
let _context = {isConditionTrue : false};
callWithContext(conditionFormatter.ifGT, _context, 234, 2);
callWithContext(conditionFormatter.or, _context);
callWithContext(conditionFormatter.ifLTE, _context, 10, 2);
helper.assert(callWithContext(conditionFormatter.show, _context, null, 'space'), 'space');
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.isAndOperator, false);
helper.assert(_context.stopPropagation, true);
});
it('Should NOT SHOW + or', function () {
let _context = {isConditionTrue : false};
callWithContext(conditionFormatter.ifGTE, _context, 2, 20);
callWithContext(conditionFormatter.or, _context);
callWithContext(conditionFormatter.ifLT, _context, 10, 2);
callWithContext(conditionFormatter.show, _context);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.isAndOperator, false);
helper.assert(_context.stopPropagation, false);
});
it('Should ELSESHOW + or', function () {
let _context = {isConditionTrue : false};
callWithContext(conditionFormatter.ifGTE, _context, 2, 20);
callWithContext(conditionFormatter.or, _context);
callWithContext(conditionFormatter.ifLT, _context, 10, 2);
callWithContext(conditionFormatter.show, _context);
helper.assert(_context.stopPropagation, false);
helper.assert(callWithContext(conditionFormatter.elseShow, _context, null, 'space'), 'space');
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.isAndOperator, false);
helper.assert(_context.stopPropagation, true);
});
it('Should SHOW + and', function () {
let _context = {isConditionTrue : false};
callWithContext(conditionFormatter.ifIN, _context, [2, 30, 'apple', -1], 'apple');
callWithContext(conditionFormatter.and, _context);
callWithContext(conditionFormatter.ifLT, _context, -199, 21);
helper.assert(callWithContext(conditionFormatter.show, _context, null, 'space'), 'space');
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.isAndOperator, true);
helper.assert(_context.stopPropagation, true);
});
it('Should SHOW + multiple and', function () {
let _context = {isConditionTrue : false};
callWithContext(conditionFormatter.ifNIN, _context, 'This is a sentence 1234 hey', 'Hello');
callWithContext(conditionFormatter.and, _context);
callWithContext(conditionFormatter.ifLTE, _context, 200, 200);
callWithContext(conditionFormatter.and, _context);
callWithContext(conditionFormatter.ifLT, _context, 0, 1);
helper.assert(callWithContext(conditionFormatter.show, _context, null, 'space'), 'space');
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.isAndOperator, true);
helper.assert(_context.stopPropagation, true);
});
it('Should SHOW + multiple or', function () {
let _context = {isConditionTrue : false};
callWithContext(conditionFormatter.ifNIN, _context, 'This is a sentence 1234 hey', 'hey');
callWithContext(conditionFormatter.or, _context);
callWithContext(conditionFormatter.ifLTE, _context, 22333333, 2100);
callWithContext(conditionFormatter.or, _context);
callWithContext(conditionFormatter.ifEM, _context, null);
callWithContext(conditionFormatter.or, _context);
callWithContext(conditionFormatter.ifGTE, _context, -1, 0);
helper.assert(callWithContext(conditionFormatter.show, _context, null, 'space'), 'space');
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.isAndOperator, false);
helper.assert(_context.stopPropagation, true);
});
it('Should elseShow + multiple or', function () {
let _context = {isConditionTrue : false};
callWithContext(conditionFormatter.ifNIN, _context, 'This is a sentence 1234 hey', 'hey');
callWithContext(conditionFormatter.or, _context);
callWithContext(conditionFormatter.ifLTE, _context, 22222222, 2100);
callWithContext(conditionFormatter.or, _context);
callWithContext(conditionFormatter.ifEM, _context, 'no empty');
callWithContext(conditionFormatter.or, _context);
callWithContext(conditionFormatter.ifGTE, _context, -1, 0);
callWithContext(conditionFormatter.show, _context);
helper.assert(callWithContext(conditionFormatter.elseShow, _context, null, 'space'), 'space');
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.isAndOperator, false);
helper.assert(_context.stopPropagation, true);
});
});
});
describe('print', function () {
it('should print the message', function () {
var _context = {};
helper.assert(callWithContext(stringFormatter.print, _context, null, 'msg'), 'msg');
});
});
describe('convEnum', function () {
it('should convert enums to human readable values', function () {
var _context = {
enum : {
DAY : ['monday', 'tuesday', 'wednesday', 'thursday', 'friday'],
ORDER_STATUS : ['draft' , 'sent', 'received']
}
};
helper.assert(callWithContext(stringFormatter.convEnum, _context, 0, 'DAY'), 'monday');
helper.assert(callWithContext(stringFormatter.convEnum, _context, 2, 'DAY'), 'wednesday');
helper.assert(callWithContext(stringFormatter.convEnum, _context, 2, 'ORDER_STATUS'), 'received');
helper.assert(callWithContext(stringFormatter.convEnum, _context, '1', 'ORDER_STATUS'), 'sent');
});
it('should accept objects for enums', function () {
var _context = {
enum : {
DAY : {
mon : 'monday',
tue : 'tuesday',
wed : 'wednesday',
thu : 'thursday',
fri : 'friday'
}
}
};
helper.assert(callWithContext(stringFormatter.convEnum, _context, 'mon', 'DAY'), 'monday');
helper.assert(callWithContext(stringFormatter.convEnum, _context, 'wed', 'DAY'), 'wednesday');
});
it('should return value if enum translation is not possible', function () {
var _context = {
enum : {
DAY : ['monday', 'tuesday', 'wednesday', 'thursday', 'friday'],
ORDER_STATUS : ['draft' , 'sent', 'received']
}
};
helper.assert(callWithContext(stringFormatter.convEnum, _context, 6, 'DAY'), 6);
helper.assert(callWithContext(stringFormatter.convEnum, _context, 3, 'UNKNOWN_TYPE'), 3);
helper.assert(callWithContext(stringFormatter.convEnum, _context, null, 'UNKNOWN_TYPE'), null);
helper.assert(callWithContext(stringFormatter.convEnum, _context, undefined, 'UNKNOWN_TYPE'), undefined);
helper.assert(callWithContext(stringFormatter.convEnum, _context, [1, 2], 'UNKNOWN_TYPE'), [1, 2]);
helper.assert(callWithContext(stringFormatter.convEnum, _context, {data : 3}, 'UNKNOWN_TYPE'), {data : 3});
});
it('should not crash if enum is not defined. It should return the value', function () {
var _context = {};
helper.assert(callWithContext(stringFormatter.convEnum, _context, 6, 'DAY'), 6);
});
});
describe('lowerCase', function () {
it('should convert a string to lower case', function () {
helper.assert(stringFormatter.lowerCase('AZERTY'), 'azerty');
helper.assert(stringFormatter.lowerCase('qskhREqsLLK;d:sdRTH234'), 'qskhreqsllk;d:sdrth234');
});
it('should not crash if datas is null or undefined', function () {
helper.assert(stringFormatter.lowerCase(null), null);
helper.assert(stringFormatter.lowerCase(undefined), undefined);
helper.assert(stringFormatter.lowerCase(120), 120);
});
});
describe('upperCase', function () {
it('should convert a string to upper case', function () {
helper.assert(stringFormatter.upperCase('azerty'), 'AZERTY');
helper.assert(stringFormatter.upperCase('qskhreqsllk;d:sdrth234'), 'QSKHREQSLLK;D:SDRTH234');
});
it('should not crash if datas is null or undefined', function () {
helper.assert(stringFormatter.upperCase(null), null);
helper.assert(stringFormatter.upperCase(undefined), undefined);
helper.assert(stringFormatter.upperCase(120), 120);
});
});
describe('ucFirst', function () {
it('should upper case the first letter', function () {
helper.assert(stringFormatter.ucFirst('azerty ss'), 'Azerty ss');
helper.assert(stringFormatter.ucFirst(' azerty'), ' azerty');
helper.assert(stringFormatter.ucFirst('qskhreqsllk;d:sdrth234'), 'Qskhreqsllk;d:sdrth234');
});
it('should not crash if datas is null or undefined', function () {
helper.assert(stringFormatter.ucFirst(null), null);
helper.assert(stringFormatter.ucFirst(undefined), undefined);
helper.assert(stringFormatter.ucFirst(120), 120);
helper.assert(stringFormatter.ucFirst([]), []);
});
});
describe('ucWords', function () {
it('should upper case the first letter of each word', function () {
helper.assert(stringFormatter.ucWords('azerty ss zzzeZ'), 'Azerty Ss ZzzeZ');
helper.assert(stringFormatter.ucWords(' azerty'), ' Azerty');
helper.assert(stringFormatter.ucWords('qskhreqsllk; D:sdrt :h234'), 'Qskhreqsllk; D:sdrt :h234');
});
it('should not crash if datas is null or undefined', function () {
helper.assert(stringFormatter.ucWords(null), null);
helper.assert(stringFormatter.ucWords(undefined), undefined);
helper.assert(stringFormatter.ucWords(120), 120);
helper.assert(stringFormatter.ucWords([]), []);
});
});
describe('unaccent', function () {
it('should remove accent from string', function () {
helper.assert(stringFormatter.unaccent('crème brulée'), 'creme brulee');
helper.assert(stringFormatter.unaccent('CRÈME BRULÉE'), 'CREME BRULEE');
helper.assert(stringFormatter.unaccent('être'), 'etre');
helper.assert(stringFormatter.unaccent('éùïêèà'), 'euieea');
});
it('should not crash if datas is null or undefined', function () {
helper.assert(stringFormatter.unaccent(null), null);
helper.assert(stringFormatter.unaccent(undefined), undefined);
helper.assert(stringFormatter.unaccent(120), 120);
});
});
describe('substr', function () {
it('should keep only the selection', function () {
helper.assert(stringFormatter.substr('coucou', 0, 3), 'cou');
helper.assert(stringFormatter.substr('coucou', 0, 0), '');
helper.assert(stringFormatter.substr('coucou', 3, 4), 'c');
});
it('should not crash if data is null or undefined', function () {
helper.assert(stringFormatter.substr(null, 0, 3), null);
helper.assert(stringFormatter.substr(undefined, 0, 3), undefined);
});
});
describe('arrayMap', function () {
it('should flatten the each object of the array (only the first level, ignoring sub arrays, sub objects,...)', function () {
var _datas = [
{id : 2, name : 'car' , type : 'toy' , sub : {id : 3}, arr : [12, 23]},
{id : 3, name : 'plane', type : 'concept', sub : {id : 3}, arr : [12, 23]}
];
helper.assert(arrayFormatter.arrayMap(_datas), '2:car:toy, 3:plane:concept');
});
it('should accept array of strings', function () {
var _datas = ['car', 'plane', 'toy', 42];
helper.assert(arrayFormatter.arrayMap(_datas), 'car, plane, toy, 42');
});
it('should change object and attribute separators', function () {
var _datas = [
{id : 2, name : 'car' , type : 'toy' , sub : {id : 3}},
{id : 3, name : 'plane', type : 'concept', sub : {id : 3}}
];
helper.assert(arrayFormatter.arrayMap(_datas, ' | ', ' ; '), '2 ; car ; toy | 3 ; plane ; concept');
helper.assert(arrayFormatter.arrayMap(_datas, '', ''), '2cartoy3planeconcept');
});
it('should print only given attribute', function () {
var _datas = [
{id : 2, name : 'car' , type : 'toy' , sub : {id : 3}},
{id : 3, name : 'plane', type : 'concept', sub : {id : 3}}
];
helper.assert(arrayFormatter.arrayMap(_datas, ' | ', ' ; ', 'name'), 'car | plane');
});
it('should print a list of given attribute in the same order', function () {
var _datas = [
{id : 2, name : 'car' , type : 'toy' , sub : {id : 3}},
{id : 3, name : 'plane', type : 'concept', sub : {id : 3}}
];
helper.assert(arrayFormatter.arrayMap(_datas, ', ', ':', 'name', 'id', 'type'), 'car:2:toy, plane:3:concept');
});
it('should not crash if datas is null or undefined', function () {
helper.assert(arrayFormatter.arrayMap(null), null);
helper.assert(arrayFormatter.arrayMap(undefined), undefined);
helper.assert(arrayFormatter.arrayMap(120), 120);
helper.assert(arrayFormatter.arrayMap([]), '');
helper.assert(arrayFormatter.arrayMap({}), {});
});
});
describe('arrayJoin', function () {
it('should flatten the array of string', function () {
var _datas = ['1', '2', 'hey!'];
helper.assert(arrayFormatter.arrayJoin(_datas), '1, 2, hey!');
});
it('should change separator', function () {
var _datas = ['1', '2', 'hey!'];
helper.assert(arrayFormatter.arrayJoin(_datas, ''), '12hey!');
helper.assert(arrayFormatter.arrayJoin(_datas, ' | '), '1 | 2 | hey!');
});
it('should not crash if datas is null or undefined', function () {
helper.assert(arrayFormatter.arrayMap(null), null);
helper.assert(arrayFormatter.arrayMap(undefined), undefined);
helper.assert(arrayFormatter.arrayMap(120), 120);
helper.assert(arrayFormatter.arrayMap([]), '');
helper.assert(arrayFormatter.arrayMap({}), {});
});
});
describe('convCurr', function () {
it('should return the same value if the currency source is the same as the currency target', function () {
var _this = {currency : { source : 'EUR', target : 'EUR', rates : {EUR : 1, USD : 1.14, GBP : 0.89} }};
helper.assert(numberFormatter.convCurr.call(_this, 10.1), 10.1);
});
it('should not crash if value or rate is null or undefined', function () {
var _rates = {EUR : 1, USD : 1.14, GBP : 0.8};
var _this = {currency : { source : 'EUR', target : 'USD', rates : _rates }};
helper.assert(numberFormatter.convCurr.call(_this, null), 0);
_this = {currency : { source : null, target : null, rates : _rates }};
helper.assert(numberFormatter.convCurr.call(_this, 10), 10);
});
it('should convert currency', function () {
var _rates = {EUR : 1, USD : 1.14, GBP : 0.8};
var _this = {currency : { source : 'EUR', target : 'USD', rates : _rates }};
helper.assert(numberFormatter.convCurr.call(_this, 10.1), 11.514);
_this = {currency : { source : 'USD', target : 'EUR', rates : _rates }};
helper.assert(numberFormatter.convCurr.call(_this, 11.514), 10.1);
_this = {currency : { source : 'GBP', target : 'EUR', rates : _rates }};
helper.assert(numberFormatter.convCurr.call(_this, 100.4), 125.5);
_this = {currency : { source : 'EUR', target : 'USD', rates : _rates }};
helper.assert(numberFormatter.convCurr.call(_this, 125.5), 143.07);
_this = {currency : { source : 'GBP', target : 'USD', rates : _rates }};
helper.assert(numberFormatter.convCurr.call(_this, 100.4), 143.07);
});
it('should accept to change target in the formatter', function () {
var _rates = {EUR : 1, USD : 1.14, GBP : 0.8};
var _this = {currency : { source : 'EUR', target : 'USD', rates : _rates }};
helper.assert(numberFormatter.convCurr.call(_this, 10.1, 'GBP'), 8.08);
});
it('should accept to change source in the formatter', function () {
var _rates = {EUR : 1, USD : 1.14, GBP : 0.8};
var _this = {currency : { source : 'EUR', target : 'USD', rates : _rates }};
helper.assert(numberFormatter.convCurr.call(_this, 100.4, 'EUR', 'GBP'), 125.5);
});
});
describe('formatN', function () {
it('should format number according to the locale a percentage', function () {
var _this = {lang : 'fr'};
helper.assert(numberFormatter.formatN.call(_this, 10000.1, 1), '10 000,1');
helper.assert(numberFormatter.formatN.call(_this, 10000.1, '1'), '10 000,1');
helper.assert(numberFormatter.formatN.call(_this, 10000.1), '10 000,100');
helper.assert(numberFormatter.formatN.call(_this, null, 1), null);
helper.assert(numberFormatter.formatN.call(_this, undefined, 1), undefined);
helper.assert(numberFormatter.formatN.call(_this, 10000.30202, 5), '10 000,30202');
helper.assert(numberFormatter.formatN.call(_this, -10000.30202, 5), '-10 000,30202');
helper.assert(numberFormatter.formatN.call(_this, -10000.30202, '5'), '-10 000,30202');
helper.assert(numberFormatter.formatN.call(_this, '-10000.30202', '5'), '-10 000,30202');
_this = {lang : 'en-gb'};
helper.assert(numberFormatter.formatN.call(_this, 10000.1, 1), '10,000.1');
helper.assert(numberFormatter.formatN.call(_this, '10000000.1', 1), '10,000,000.1');
});
it.skip('should keep maximal precision if precision is not defined', function () {
var _this = {lang : 'fr'};
helper.assert(numberFormatter.formatN.call(_this, 10000.12345566789), '10 000,12345566789');
});
it('should round number', function () {
var _this = {lang : 'fr'};
helper.assert(numberFormatter.formatN.call(_this, 222.1512, 2), '222,15');
helper.assert(numberFormatter.formatN.call(_this, 222.1552, 2), '222,16');
helper.assert(numberFormatter.formatN.call(_this, 1.005, 2), '1,01');
helper.assert(numberFormatter.formatN.call(_this, 1.005, 3), '1,005');
helper.assert(numberFormatter.formatN.call(_this, -1.005, 3), '-1,005');
helper.assert(numberFormatter.formatN.call(_this, -1.006, 2), '-1,01');
});
});
describe('round', function () {
it('should round number', function () {
var _this = {lang : 'fr'};
helper.assert(numberFormatter.round.call(_this, 222.1512, 2), 222.15);
helper.assert(numberFormatter.round.call(_this, 222.1552, 2), 222.16);
helper.assert(numberFormatter.round.call(_this, 1.005, 2), 1.01);
helper.assert(numberFormatter.round.call(_this, 1.005, 3), 1.005);
helper.assert(numberFormatter.round.call(_this, -1.005, 3), -1.005);
helper.assert(numberFormatter.round.call(_this, -1.006, 2), -1.01);
helper.assert(numberFormatter.round.call(_this, -1.005, 2), -1);
});
});
describe('formatC', function () {
it('should format number according to the locale, currencyTarget, and set automatically the precision', function () {
var _rates = {EUR : 1, USD : 1, GBP : 1};
var _this = {lang : 'en-us', currency : { source : 'EUR', target : 'USD', rates : _rates }};
helper.assert(numberFormatter.formatC.call(_this, 10000.1), '$10,000.10');
_this.currency.target = 'EUR';
helper.assert(numberFormatter.formatC.call(_this, 10000.155), '€10,000.16');
_this.lang = 'fr-fr';
helper.assert(numberFormatter.formatC.call(_this, 10000.1), '10 000,10 €');
helper.assert(numberFormatter.formatC.call(_this, -10000.1), '-10 000,10 €');
helper.assert(numberFormatter.formatC.call(_this, 10000.1, 'M'), 'euros');
helper.assert(numberFormatter.formatC.call(_this, null, 1), null);
helper.assert(numberFormatter.formatC.call(_this, undefined, 1), undefined);
});
it('should change currency output format', function () {
var _rates = {EUR : 1, USD : 1, GBP : 1};
var _this = {lang : 'en-us', currency : { source : 'EUR', target : 'USD', rates : _rates }};
helper.assert(numberFormatter.formatC.call(_this, 10000.1, 'M'), 'dollars');
helper.assert(numberFormatter.formatC.call(_this, 1, 'M'), 'dollar');
helper.assert(numberFormatter.formatC.call(_this, 10.15678, 5), '$10.15678');
helper.assert(numberFormatter.formatC.call(_this, 10.15678, 'LL'), '10.16 dollars');
_this.currency.target = 'EUR';
_this.lang = 'fr-fr';
helper.assert(numberFormatter.formatC.call(_this, 10000.1, 'M'), 'euros');
helper.assert(numberFormatter.formatC.call(_this, 10000.1, 'L'), '10 000,10 €');
helper.assert(numberFormatter.formatC.call(_this, 10000.1, 'LL'), '10 000,10 euros');
helper.assert(numberFormatter.formatC.call(_this, 1, 'LL'), '1,00 euro');
});
it('should convert currency automatically if target != source using rates', function () {
var _rates = {EUR : 1, USD : 2, GBP : 10};
var _this = {lang : 'en-us', currency : { source : 'EUR', target : 'USD', rates : _rates }};
helper.assert(numberFormatter.formatC.call(_this, 10000.1), '$20,000.20');
_this.currency.target = 'GBP';
helper.assert(numberFormatter.formatC.call(_this, 10000.1), '£100,001.00');
});
it('should convert to crypto-currencies/USD by using rates (USD to BTC/ETH AND BTC/ETH to USD)', function () {
var _rates = {USD : 1, BTC : 0.000102618, ETH : 0.003695354, XMR : 0.01218769 };
/** USD to BTC */
var _this = {lang : 'en-us', currency : { source : 'USD', target : 'BTC', rates : _rates }};
helper.assert(numberFormatter.formatC.call(_this, 1255), '₿0.12878559');
/** USD to ETH */
_this.currency.target = 'ETH';
helper.assert(numberFormatter.formatC.call(_this, 32.41), 'Ξ0.119766423');
/** USD to XMR */
_this.currency.target = 'XMR';
helper.assert(numberFormatter.formatC.call(_this, 383991.32), 'XMR4,679.96717085');
/** BTC to USD */
_rates = {USD : 9736.03, BTC : 1};
_this = {lang : 'en-us', currency : { source : 'BTC', target : 'USD', rates : _rates }};
helper.assert(numberFormatter.formatC.call(_this, 2.3155321), '$22,544.09');
/** ETH to USD */
_this.currency.source = 'ETH';
_this.currency.rates = { USD : 247.37, ETH : 1 };
helper.assert(numberFormatter.formatC.call(_this, 0.54212345), '$134.11');
});
it('should accept custom format', function () {
var _rates = {EUR : 1, USD : 1, GBP : 1};
var _this = {lang : 'fr-fr', currency : { source : 'EUR', target : 'EUR', rates : _rates }};
helper.assert(numberFormatter.formatC.call(_this, 10000.1, 'M'), 'euros');
helper.assert(numberFormatter.formatC.call(_this, 1, 'M'), 'euro');
});
it('should be fast', function () {
var _rates = {EUR : 1, USD : 2, GBP : 10};
var _this = {lang : 'en-us', currency : { source : 'EUR', target : 'USD', rates : _rates }};
var _loops = 10000;
var _res = [];
var _start = process.hrtime();
for (var i = 0; i < _loops; i++) {
_res.push(numberFormatter.formatC.call(_this, 10000.1));
}
var _diff = process.hrtime(_start);
var _elapsed = ((_diff[0] * 1e9 + _diff[1]) / 1e6);
console.log('\n formatC number speed : ' + _elapsed + ' ms (around 30ms for 10k) \n');
helper.assert(_elapsed > 50, false, 'formatC is too slow');
});
});
describe('Number operations', function () {
it('should add number', function () {
helper.assert(numberFormatter.add('120', '67'), 187);
});
it('should substract number', function () {
helper.assert(numberFormatter.sub('120', '67'), 53);
});
it('should multiply number', function () {
helper.assert(numberFormatter.mul('120', '67'), 8040);
});
it('should divide number', function () {
helper.assert(numberFormatter.div('120', '80'), 1.5);
});
});
});
/**
* Call a formatter, passing `context` object as `this`
* @param {Function} func formatter to call
* @param {Object} context object
* @return {Mixed} [description]
*/
function callWithContext (func, context) {
context.stopPropagation = false; // reset propagation
var _args = Array.prototype.slice.call(arguments);
return func.apply(context, _args.slice(2));
}
| test/test.formatter.js | var dateFormatter = require('../formatters/date');
var conditionFormatter = require('../formatters/condition');
var stringFormatter = require('../formatters/string');
var arrayFormatter = require('../formatters/array');
var numberFormatter = require('../formatters/number');
var helper = require('../lib/helper');
describe('formatter', function () {
describe('convDate', function () {
it('should accept use this.lang to set convert date', function () {
helper.assert(dateFormatter.convDate.call({lang : 'en'}, '20101201', 'YYYYMMDD', 'L'), '12/01/2010');
helper.assert(dateFormatter.convDate.call({lang : 'fr'}, '20101201', 'YYYYMMDD', 'L'), '01/12/2010');
});
it('should return null or undefined if value is null or undefined', function () {
helper.assert(dateFormatter.convDate.call({lang : 'en'}, undefined, 'YYYYMMDD', 'L'), undefined);
helper.assert(dateFormatter.convDate.call({lang : 'fr'}, null, 'YYYYMMDD', 'L'), null);
});
it('should convert unix timestamp', function () {
helper.assert(dateFormatter.convDate.call({lang : 'en'}, 1318781876, 'X', 'LLLL'), 'Sunday, October 16, 2011 6:17 PM');
helper.assert(dateFormatter.convDate.call({lang : 'fr'}, 1318781876, 'X', 'LLLL'), 'dimanche 16 octobre 2011 18:17');
});
});
describe('formatD', function () {
it('should accept use this.lang to set convert date', function () {
helper.assert(dateFormatter.formatD.call({lang : 'en'}, '20101201', 'L', 'YYYYMMDD'), '12/01/2010');
helper.assert(dateFormatter.formatD.call({lang : 'fr'}, '20101201', 'L', 'YYYYMMDD'), '01/12/2010');
});
it('should return null or undefined if value is null or undefined', function () {
helper.assert(dateFormatter.formatD.call({lang : 'en'}, undefined, 'L', 'YYYYMMDD'), undefined);
helper.assert(dateFormatter.formatD.call({lang : 'fr'}, null, 'L', 'YYYYMMDD'), null);
});
it('should convert unix timestamp', function () {
helper.assert(dateFormatter.formatD.call({lang : 'en'}, 1318781876, 'LLLL', 'X'), 'Sunday, October 16, 2011 6:17 PM');
helper.assert(dateFormatter.formatD.call({lang : 'fr'}, 1318781876, 'LLLL', 'X'), 'dimanche 16 octobre 2011 18:17');
});
it('should consider input format is ISO 8601 by default if not provided', function () {
helper.assert(dateFormatter.formatD.call({lang : 'en'}, '20101201', 'L'), '12/01/2010');
helper.assert(dateFormatter.formatD.call({lang : 'fr'}, '20101201', 'L'), '01/12/2010');
helper.assert(dateFormatter.formatD.call({lang : 'en'}, '2017-05-10T15:57:23.769561+03:00', 'LLLL'), 'Wednesday, May 10, 2017 2:57 PM');
helper.assert(dateFormatter.formatD.call({lang : 'en'}, '2017-05-10 15:57:23.769561+03:00', 'LLLL'), 'Wednesday, May 10, 2017 2:57 PM');
helper.assert(dateFormatter.formatD.call({lang : 'en'}, '1997-12-17 07:37:16-08', 'LLLL'), 'Wednesday, December 17, 1997 4:37 PM');
});
it('should accepts real locales', function () {
helper.assert(dateFormatter.formatD.call({lang : 'en-GB'}, '20101201', 'L'), '01/12/2010');
helper.assert(dateFormatter.formatD.call({lang : 'en-gb'}, '20101201', 'L'), '01/12/2010');
helper.assert(dateFormatter.formatD.call({lang : 'en-US'}, '20101201', 'L'), '12/01/2010');
helper.assert(dateFormatter.formatD.call({lang : 'fr-CA'}, '20101201', 'L'), '2010-12-01');
helper.assert(dateFormatter.formatD.call({lang : 'fr-FR'}, '20101201', 'L'), '01/12/2010');
});
});
describe('convCRLF', function () {
it('should convert LF and CR in odt', function () {
helper.assert(stringFormatter.convCRLF.call({extension : 'odt'}, 'qsdqsd \n sd \r\n qsd \n sq'), 'qsdqsd <text:line-break/> sd <text:line-break/> qsd <text:line-break/> sq');
});
it('should convert LF and CR in docx', function () {
helper.assert(stringFormatter.convCRLF.call({extension : 'docx'}, 'qsdqsd \n'), 'qsdqsd </w:t><w:br/><w:t>');
});
});
describe('ifEmpty', function () {
it('should show a message if data is empty. It should stop propagation to next formatter', function () {
var _context = {};
helper.assert(callWithContext(conditionFormatter.ifEmpty, _context, '' , 'msgIfEmpty'), 'msgIfEmpty');
helper.assert(_context.stopPropagation, true);
helper.assert(callWithContext(conditionFormatter.ifEmpty, _context, null , 'msgIfEmpty'), 'msgIfEmpty');
helper.assert(_context.stopPropagation, true);
helper.assert(callWithContext(conditionFormatter.ifEmpty, _context, undefined, 'msgIfEmpty'), 'msgIfEmpty');
helper.assert(_context.stopPropagation, true);
helper.assert(callWithContext(conditionFormatter.ifEmpty, _context, [] , 'msgIfEmpty'), 'msgIfEmpty');
helper.assert(_context.stopPropagation, true);
helper.assert(callWithContext(conditionFormatter.ifEmpty, _context, NaN , 'msgIfEmpty'), 'msgIfEmpty');
helper.assert(_context.stopPropagation, true);
helper.assert(callWithContext(conditionFormatter.ifEmpty, _context, {} , 'msgIfEmpty'), 'msgIfEmpty');
helper.assert(_context.stopPropagation, true);
helper.assert(callWithContext(conditionFormatter.ifEmpty, _context, {} , 'msgIfEmpty', 'true'), 'msgIfEmpty');
helper.assert(_context.stopPropagation, false);
helper.assert(callWithContext(conditionFormatter.ifEmpty, _context, {} , 'msgIfEmpty', true), 'msgIfEmpty');
helper.assert(_context.stopPropagation, false);
});
it('should return data if the message is not empty... and keep on propagation to next formatter', function () {
var _context = {};
helper.assert(callWithContext(conditionFormatter.ifEmpty, _context, 0 , 'msgIfEmpty'), 0);
helper.assert(_context.stopPropagation, false);
var _date = new Date();
helper.assert(callWithContext(conditionFormatter.ifEmpty, _context, _date , 'msgIfEmpty'), _date);
helper.assert(_context.stopPropagation, false);
helper.assert(callWithContext(conditionFormatter.ifEmpty, _context, 'sdsd' , 'msgIfEmpty'), 'sdsd');
helper.assert(_context.stopPropagation, false);
helper.assert(callWithContext(conditionFormatter.ifEmpty, _context, 12.33 , 'msgIfEmpty'), 12.33);
helper.assert(_context.stopPropagation, false);
helper.assert(callWithContext(conditionFormatter.ifEmpty, _context, true , 'msgIfEmpty'), true);
helper.assert(_context.stopPropagation, false);
helper.assert(callWithContext(conditionFormatter.ifEmpty, _context, [12, 23] , 'msgIfEmpty'), [12, 23]);
helper.assert(_context.stopPropagation, false);
helper.assert(callWithContext(conditionFormatter.ifEmpty, _context, {d : 'd'} , 'msgIfEmpty'), {d : 'd'});
helper.assert(_context.stopPropagation, false);
});
});
describe('ifEqual', function () {
it('should show a message if data is equal to a variable', function () {
var _context = {};
helper.assert(callWithContext(conditionFormatter.ifEqual, _context, 0, 0, 'msgIfTrue'), 'msgIfTrue');
helper.assert(_context.stopPropagation, true);
helper.assert(callWithContext(conditionFormatter.ifEqual, _context, 0, '0', 'msgIfTrue'), 'msgIfTrue');
helper.assert(_context.stopPropagation, true);
helper.assert(callWithContext(conditionFormatter.ifEqual, _context, true, true, 'msgIfTrue'), 'msgIfTrue');
helper.assert(_context.stopPropagation, true);
helper.assert(callWithContext(conditionFormatter.ifEqual, _context, 'true', 'true', 'msgIfTrue'), 'msgIfTrue');
helper.assert(_context.stopPropagation, true);
helper.assert(callWithContext(conditionFormatter.ifEqual, _context, true, 'true', 'msgIfTrue'), 'msgIfTrue');
helper.assert(_context.stopPropagation, true);
helper.assert(callWithContext(conditionFormatter.ifEqual, _context, false, 'false', 'msgIfTrue'), 'msgIfTrue');
helper.assert(_context.stopPropagation, true);
helper.assert(callWithContext(conditionFormatter.ifEqual, _context, 'false', 'false', 'msgIfTrue'), 'msgIfTrue');
helper.assert(_context.stopPropagation, true);
helper.assert(callWithContext(conditionFormatter.ifEqual, _context, false, false, 'msgIfTrue'), 'msgIfTrue');
helper.assert(_context.stopPropagation, true);
helper.assert(callWithContext(conditionFormatter.ifEqual, _context, false, 'false', 'msgIfTrue'), 'msgIfTrue');
helper.assert(_context.stopPropagation, true);
helper.assert(callWithContext(conditionFormatter.ifEqual, _context, 'titi', 'titi', 'msgIfTrue'), 'msgIfTrue');
helper.assert(_context.stopPropagation, true);
});
it('should propagate to next formatter if continueOnSuccess is true', function () {
var _context = {};
helper.assert(callWithContext(conditionFormatter.ifEqual, _context, 0, 0, 'msgIfTrue', 'true'), 'msgIfTrue');
helper.assert(_context.stopPropagation, false);
helper.assert(callWithContext(conditionFormatter.ifEqual, _context, 0, '0', 'msgIfTrue', 'true'), 'msgIfTrue');
helper.assert(_context.stopPropagation, false);
helper.assert(callWithContext(conditionFormatter.ifEqual, _context, true, true, 'msgIfTrue', 'true'), 'msgIfTrue');
helper.assert(_context.stopPropagation, false);
helper.assert(callWithContext(conditionFormatter.ifEqual, _context, false, false, 'msgIfTrue', 'true'), 'msgIfTrue');
helper.assert(_context.stopPropagation, false);
helper.assert(callWithContext(conditionFormatter.ifEqual, _context, 'titi', 'titi', 'msgIfTrue', 'true'), 'msgIfTrue');
helper.assert(_context.stopPropagation, false);
helper.assert(callWithContext(conditionFormatter.ifEqual, _context, 'titi', 'titi', 'msgIfTrue', true), 'msgIfTrue');
helper.assert(_context.stopPropagation, false);
});
it('should return data if data is not equal to a variable', function () {
var _context = {};
helper.assert(callWithContext(conditionFormatter.ifEqual, _context, 0, 3, 'msgIfTrue'), 0);
helper.assert(_context.stopPropagation, false);
helper.assert(callWithContext(conditionFormatter.ifEqual, _context, 0, '1', 'msgIfTrue'), 0);
helper.assert(_context.stopPropagation, false);
helper.assert(callWithContext(conditionFormatter.ifEqual, _context, true, false, 'msgIfTrue'), true);
helper.assert(_context.stopPropagation, false);
helper.assert(callWithContext(conditionFormatter.ifEqual, _context, 'true', false, 'msgIfTrue'), 'true');
helper.assert(_context.stopPropagation, false);
helper.assert(callWithContext(conditionFormatter.ifEqual, _context, 'false', 'true', 'msgIfTrue'), 'false');
helper.assert(_context.stopPropagation, false);
helper.assert(callWithContext(conditionFormatter.ifEqual, _context, false, true, 'msgIfTrue'), false);
helper.assert(_context.stopPropagation, false);
helper.assert(callWithContext(conditionFormatter.ifEqual, _context, 'titi', 'toto', 'msgIfTrue'), 'titi');
helper.assert(_context.stopPropagation, false);
});
});
describe('ifContains', function () {
it('should show a message if data contains a variable', function () {
var _context = {};
helper.assert(callWithContext(conditionFormatter.ifContain, _context, 'car is broken', 'is', 'msgIfTrue'), 'msgIfTrue');
helper.assert(_context.stopPropagation, true);
helper.assert(callWithContext(conditionFormatter.ifContain, _context, 'car is broken', 'car is', 'msgIfTrue'), 'msgIfTrue');
helper.assert(_context.stopPropagation, true);
helper.assert(callWithContext(conditionFormatter.ifContain, _context, [1, 2, 'toto'], 'toto', 'msgIfTrue'), 'msgIfTrue');
helper.assert(_context.stopPropagation, true);
helper.assert(callWithContext(conditionFormatter.ifContain, _context, [1, 2, 'toto'], 2, 'msgIfTrue'), 'msgIfTrue');
helper.assert(_context.stopPropagation, true);
});
it('should propagate to next formatter if continueOnSuccess is true', function () {
var _context = {};
helper.assert(callWithContext(conditionFormatter.ifContain, _context, 'car is broken', 'is', 'msgIfTrue', 'true'), 'msgIfTrue');
helper.assert(_context.stopPropagation, false);
helper.assert(callWithContext(conditionFormatter.ifContain, _context, 'car is broken', 'car is', 'msgIfTrue', 'true'), 'msgIfTrue');
helper.assert(_context.stopPropagation, false);
helper.assert(callWithContext(conditionFormatter.ifContain, _context, [1, 2, 'toto'], 'toto', 'msgIfTrue', 'true'), 'msgIfTrue');
helper.assert(_context.stopPropagation, false);
helper.assert(callWithContext(conditionFormatter.ifContain, _context, [1, 2, 'toto'], 2, 'msgIfTrue', 'true'), 'msgIfTrue');
helper.assert(_context.stopPropagation, false);
helper.assert(callWithContext(conditionFormatter.ifContain, _context, [1, 2, 'toto'], 2, 'msgIfTrue', true), 'msgIfTrue');
helper.assert(_context.stopPropagation, false);
});
it('should return data if data does not contain the variable', function () {
var _context = {};
helper.assert(callWithContext(conditionFormatter.ifContain, _context, 'car is broken', 'are', 'msgIfTrue'), 'car is broken');
helper.assert(_context.stopPropagation, false);
helper.assert(callWithContext(conditionFormatter.ifContain, _context, 'car is broken', 'caris', 'msgIfTrue'), 'car is broken');
helper.assert(_context.stopPropagation, false);
helper.assert(callWithContext(conditionFormatter.ifContain, _context, [1, 2, 'toto'], 'titi', 'msgIfTrue'), [1, 2, 'toto']);
helper.assert(_context.stopPropagation, false);
helper.assert(callWithContext(conditionFormatter.ifContain, _context, [], 3, 'msgIfTrue'), []);
helper.assert(_context.stopPropagation, false);
});
it('should not crash if data is not a String or an Array. It should transfer to next formatter', function () {
var _context = {};
helper.assert(callWithContext(conditionFormatter.ifContain, _context, null, 'is', 'msgIfTrue'), null);
helper.assert(_context.stopPropagation, false);
helper.assert(callWithContext(conditionFormatter.ifContain, _context, undefined, 'is', 'msgIfTrue'), undefined);
helper.assert(_context.stopPropagation, false);
helper.assert(callWithContext(conditionFormatter.ifContain, _context, 12, 'titi', 'msgIfTrue'), 12);
helper.assert(_context.stopPropagation, false);
helper.assert(callWithContext(conditionFormatter.ifContain, _context, {toto : 2 }, 3, 'msgIfTrue'), {toto : 2 });
helper.assert(_context.stopPropagation, false);
});
});
describe('ifEQ', function () {
it('should turn the `isConditionTrue` to True if a data is equal to a variable', function () {
const _dataSet = [
[0, 0],
[0, '0'],
[true, true],
['true', 'true'],
[true, 'true'],
['false', 'false'],
[false, 'false'],
[false, false],
['titi', 'titi'],
[undefined, undefined],
[null, null],
// object identiques, it is comparing "[object Object]" === "[object Object]"
[{value : 10, name : 'john', address : { name : '123 street'} }, {value : 10, name : 'john', address : { name : '123 street'}}],
[{ name : '85 street'}, {value : 10, name : 'wick', address : { name : '321 street'}}],
[[1, 2, 3, 4, 6, 7, 8, 9], [1, 2, 3, 4, 6, 7, 8, 9]]
];
var _context = {};
for (let i = 0, n = _dataSet.length; i < n; i++) {
const el = _dataSet[i];
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifEQ, _context, el[0], el[1]);
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
}
});
it('should turn the `isConditionTrue` to false if the data is not equal to a variable', function () {
var _context = {};
const _dataSet = [
[0, 3],
[0, '1'],
[true, false],
['true', false],
['false', 'true'],
[false, true],
['titi', 'toto'],
[undefined, 'titi'],
['titi', null],
[[1, 2, 3], [1, 3]],
];
for (let i = 0, n = _dataSet.length; i < n; i++) {
const el = _dataSet[i];
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifEQ, _context, el[0], el[1]);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
}
});
});
describe('ifNE', function () {
it('should turn the `isConditionTrue` to false if a data is equal to a variable', function () {
var _context = {};
const _dataSet = [
[0, 0],
[0, '0'],
[true, true],
['true', 'true'],
[true, 'true'],
[false, 'false'],
['false', 'false'],
[false, false],
[false, 'false'],
['titi', 'titi'],
[undefined, undefined],
[null, null],
// Objects appear as "[object Object]"
[{value : 10, name : 'john', address : { name : '123 street'} }, {value : 10, name : 'john', address : { name : '123 street'}}],
[{value : 20, name : 'Eric', address : { name : '85 street'} }, {value : 10, name : 'wick', address : { name : '321 street'}}],
[[1, 2, 3, 4, 6, 7, 8, 9], [1, 2, 3, 4, 6, 7, 8, 9]],
];
for (let i = 0, n = _dataSet.length; i < n; i++) {
const el = _dataSet[i];
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifNE, _context, el[0], el[1]);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
}
});
it('should turn the `isConditionTrue` to false if the data is not equal to a variable', function () {
var _context = {};
const _dataSet = [
[0, 3],
[0, '1'],
[true, false],
['true', false],
['false', 'true'],
[false, true],
['titi', 'toto'],
[undefined, 'titi'],
['titi', null],
[[1, 2, 3, 4, 6, 7, 8, 9], [1, 2, 3, 6, 7, 8, 9]],
];
for (let i = 0, n = _dataSet.length; i < n; i++) {
const el = _dataSet[i];
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifNE, _context, el[0], el[1]);
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
}
});
});
describe('ifGT', function () {
it('should matches values, string.length, array.length or object.length that are greater than a specified value', function () {
let _context = {isConditionTrue : false};
const _dataSet = [
[50, -29],
[1290, 768],
['1234', '1'],
['This is a long string', 'Hello'],
['Hello1234', '1'],
[[1, 2, 3, 4, 5], [1, 2, 3]],
[['apple', 'banana', 'jackfruit'], ['tomato', 'cabbage']],
[{id : 2, name : 'John', lastname : 'Wick', city : 'Paris'}, {id : 3, name : 'John'}],
];
for (let i = 0, n = _dataSet.length; i < n; i++) {
const el = _dataSet[i];
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifGT, _context, el[0], el[1]);
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
}
});
it('should matches values, string.length, array.length or object.length that are NOT greater than a specified value', function () {
let _context = {isConditionTrue : false};
const _dataSet = [
[-23, 19],
[1, 768],
[0, 0],
['1' , '1234'],
['Short sentence', 'Hello, this is a long sentence'],
[[1, 2], [1, 2, 3, 4, 5, 6]],
[[1, 2, 3, 4, 5], [1, 2, 3, 4, 6]],
[['apple', 'banana'], ['tomato', 'cabbage', 'jackfruit', 'berry']],
[{id : 2, name : 'John'}, {id : 3, name : 'John', lastname : 'Wick', city : 'Paris'}],
[{id : 2, name : 'John'}, null],
[null, 'Lion and giraffe'],
['Lion and giraffe', null],
[null, null],
[{id : 2, name : 'John'}, undefined],
[undefined, 'Lion and giraffe'],
['Lion and giraffe', undefined],
[undefined, undefined],
[{id : 2, name : 'John'}, {id : 3, name : 'Wick'}],
];
for (let i = 0, n = _dataSet.length; i < n; i++) {
const el = _dataSet[i];
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifGT, _context, el[0], el[1]);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
}
});
});
describe('ifGTE', function () {
it('Matches values, string.length, array.length or object.length that are greater than or equal to a specified value', function () {
let _context = {isConditionTrue : false};
let _dataSet = [
[50, -29],
[0, 0],
[1290, 768],
['1234', '1'],
['This is a long string', 'Hello'],
['ThisEqual', 'Hello1234'],
['Hello1234', '1'],
[[1, 2, 3, 4, 5], [1, 2, 3]],
[[1, 2, 3, 4, 5], [1, 2, 3, 4, 6]],
[['apple', 'banana', 'jackfruit'], ['tomato', 'cabbage']],
[['apple', 'banana'], ['tomato', 'cabbage']],
[{id : 2, name : 'John', lastname : 'Wick', city : 'Paris'}, {id : 3, name : 'John'}],
[{id : 2, name : 'John'}, {id : 3, name : 'Wick'}],
];
for (let i = 0, n = _dataSet.length; i < n; i++) {
const el = _dataSet[i];
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifGTE, _context, el[0], el[1]);
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
}
});
it('should matches values, string.length, array.length or object.length that are NOT greater than a specified value', function () {
let _context = {isConditionTrue : false};
const _dataSet = [
[-23, 19],
[1, 768],
['1' , '1234'],
['Short sentence', 'Hello, this is a long sentence'],
[[1, 2], [1, 2, 3, 4, 5, 6]],
[['apple', 'banana'], ['tomato', 'cabbage', 'jackfruit', 'berry']],
[{id : 2, name : 'John'}, {id : 3, name : 'John', lastname : 'Wick', city : 'Paris'}],
[{id : 2, name : 'John'}, null],
[null, 'Lion and giraffe'],
['Lion and giraffe', null],
[null, null],
[{id : 2, name : 'John'}, undefined],
[undefined, 'Lion and giraffe'],
['Lion and giraffe', undefined],
[undefined, undefined],
];
for (let i = 0, n = _dataSet.length; i < n; i++) {
const el = _dataSet[i];
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifGTE, _context, el[0], el[1]);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
}
});
});
describe('ifLT', function () {
it ('should matches values, string.length, array.length or object.length that are less than a specified value', function () {
let _context = {isConditionTrue : false};
callWithContext(conditionFormatter.ifLT, _context, -23, 19);
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLT, _context, 1, 768);
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLT, _context, '1' , '1234');
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLT, _context, 'Short sentence', 'Hello, this is a long sentence');
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLT, _context, [1, 2], [1, 2, 3, 4, 5, 6]);
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLT, _context, ['apple', 'banana'], ['tomato', 'cabbage', 'jackfruit', 'berry']);
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLT, _context, {id : 2, name : 'John'}, {id : 3, name : 'John', lastname : 'Wick', city : 'Paris'});
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
});
it ('should matches values, string.length, array.length or object.length that are NOT less than a specified value', function () {
let _context = {isConditionTrue : false};
callWithContext(conditionFormatter.ifLT, _context, 50, -29);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLT, _context, 0, 0);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLT, _context, 1290, 768);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLT, _context, '1234', '1');
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLT, _context, 'This is a long string', 'Hello');
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLT, _context, 'ThisEqual', 'Hello1234');
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLT, _context, 'Hello1234', '1');
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLT, _context, [1, 2, 3, 4, 5], [1, 2, 3]);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLT, _context, [1, 2, 3, 4, 5], [1, 2, 3, 4, 6]);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLT, _context, ['apple', 'banana', 'jackfruit'], ['tomato', 'cabbage']);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLT, _context, ['apple', 'banana'], ['tomato', 'cabbage']);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLT, _context, {id : 2, name : 'John', lastname : 'Wick', city : 'Paris'}, {id : 3, name : 'John'});
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLT, _context, {id : 2, name : 'John'}, {id : 3, name : 'Wick'});
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLT, _context, {id : 2, name : 'John'}, null);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLT, _context, null, 'Lion and giraffe');
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLT, _context, 'Lion and giraffe', null);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLT, _context, null, null);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLT, _context, {id : 2, name : 'John'}, undefined);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLT, _context, undefined, 'Lion and giraffe');
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLT, _context, 'Lion and giraffe', undefined);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLT, _context, undefined, undefined);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
});
});
describe('ifLTE', function () {
it('should matches values, string.length, array.length or object.length that are less than or equal to a specified value', function () {
let _context = {isConditionTrue : false};
callWithContext(conditionFormatter.ifLTE, _context, -23, 19);
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLTE, _context, 1, 768);
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLTE, _context, 0, 0);
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLTE, _context, '1' , '1234');
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLTE, _context, 'Short sentence', 'Hello, this is a long sentence');
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLTE, _context, 'ThisEqual', 'Hello1234');
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLTE, _context, [1, 2], [1, 2, 3, 4, 5, 6]);
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLTE, _context, [1, 2, 3, 4, 5], [1, 2, 3, 4, 6]);
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLTE, _context, ['apple', 'banana'], ['tomato', 'cabbage', 'jackfruit', 'berry']);
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLTE, _context, ['apple', 'banana'], ['tomato', 'cabbage']);
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLTE, _context, {id : 2, name : 'John'}, {id : 3, name : 'John', lastname : 'Wick', city : 'Paris'});
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLTE, _context, {id : 2, name : 'John'}, {id : 3, name : 'Wick'});
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
});
it('should matches values, string.length, array.length or object.length that are NOT less than or equal to a specified value', function () {
let _context = {isConditionTrue : false};
callWithContext(conditionFormatter.ifLTE, _context, 50, -29);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLTE, _context, 1290, 768);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLTE, _context, '1234', '1');
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLTE, _context, 'This is a long string', 'Hello');
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLTE, _context, 'Hello1234', '1');
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLTE, _context, [1, 2, 3, 4, 5], [1, 2, 3]);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLTE, _context, ['apple', 'banana', 'jackfruit'], ['tomato', 'cabbage']);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLTE, _context, {id : 2, name : 'John', lastname : 'Wick', city : 'Paris'}, {id : 3, name : 'John'});
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLTE, _context, {id : 2, name : 'John'}, null);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLTE, _context, null, 'Lion and giraffe');
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLTE, _context, 'Lion and giraffe', null);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLTE, _context, null, null);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLTE, _context, {id : 2, name : 'John'}, undefined);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLTE, _context, undefined, 'Lion and giraffe');
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLTE, _context, 'Lion and giraffe', undefined);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifLTE, _context, undefined, undefined);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
});
});
describe('ifIN', function () {
it('Matches any of the values specified in an array or string', function () {
var _context = {};
callWithContext(conditionFormatter.ifIN, _context, 'car is broken', 'is');
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
callWithContext(conditionFormatter.ifIN, _context, 'car is broken', 'car is');
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
callWithContext(conditionFormatter.ifIN, _context, [1, 2, 'toto'], 'toto');
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
callWithContext(conditionFormatter.ifIN, _context, [1, 2, 'toto'], 2);
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
});
it('Matches none of the values specified in an array or string', function () {
var _context = {};
callWithContext(conditionFormatter.ifIN, _context, 'car is broken', 'are');
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
callWithContext(conditionFormatter.ifIN, _context, 'car is broken', 'caris');
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
callWithContext(conditionFormatter.ifIN, _context, [1, 2, 'toto'], 'titi');
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
callWithContext(conditionFormatter.ifIN, _context, [], 3);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
callWithContext(conditionFormatter.ifIN, _context, null, 'titi');
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
callWithContext(conditionFormatter.ifIN, _context, 'titi', null);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
callWithContext(conditionFormatter.ifIN, _context, null, null);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
callWithContext(conditionFormatter.ifIN, _context, undefined, null);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
callWithContext(conditionFormatter.ifIN, _context, undefined, 'titi');
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
callWithContext(conditionFormatter.ifIN, _context, 'titi', undefined);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
callWithContext(conditionFormatter.ifIN, _context, undefined, undefined);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
callWithContext(conditionFormatter.ifIN, _context, 12, 'titi');
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
callWithContext(conditionFormatter.ifIN, _context, {toto : 2 }, 3);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
});
});
describe('ifNIN', function () {
it('should matches none of the values specified in an array or string', function () {
var _context = {};
callWithContext(conditionFormatter.ifNIN, _context, 'car is broken', 'are');
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
callWithContext(conditionFormatter.ifNIN, _context, 'car is broken', 'caris');
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
callWithContext(conditionFormatter.ifNIN, _context, [1, 2, 'toto'], 'titi');
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
callWithContext(conditionFormatter.ifNIN, _context, [], 3);
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
});
it('should matches any of the values specified in an array or string', function () {
var _context = {};
callWithContext(conditionFormatter.ifNIN, _context, 'car is broken', 'is');
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
callWithContext(conditionFormatter.ifNIN, _context, 'car is broken', 'car is');
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
callWithContext(conditionFormatter.ifNIN, _context, [1, 2, 'toto'], 'toto');
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
callWithContext(conditionFormatter.ifNIN, _context, [1, 2, 'toto'], 2);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
callWithContext(conditionFormatter.ifNIN, _context, null, 'titi');
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
callWithContext(conditionFormatter.ifNIN, _context, 'titi', null);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
callWithContext(conditionFormatter.ifNIN, _context, null, null);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
callWithContext(conditionFormatter.ifNIN, _context, undefined, null);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
callWithContext(conditionFormatter.ifNIN, _context, undefined, 'titi');
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
callWithContext(conditionFormatter.ifNIN, _context, 'titi', undefined);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
callWithContext(conditionFormatter.ifNIN, _context, undefined, undefined);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
callWithContext(conditionFormatter.ifNIN, _context, 12, 'titi');
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
callWithContext(conditionFormatter.ifNIN, _context, {toto : 2 }, 3);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
});
});
describe('ifEM', function () {
it ('should matches empty values, string, arrays or objects', function () {
let _context = {isConditionTrue : false};
callWithContext(conditionFormatter.ifEM, _context, '');
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifEM, _context, null);
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifEM, _context, undefined);
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifEM, _context, []);
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifEM, _context, NaN);
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifEM, _context, {});
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
});
it('should matches not empty values, string, arrays or objects', function () {
var _context = {};
callWithContext(conditionFormatter.ifEM, _context, 0);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifEM, _context, new Date());
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifEM, _context, 'sdsd');
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifEM, _context, 12.33);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifEM, _context, true);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifEM, _context, [12, 23]);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifEM, _context, {d : 'd'});
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
});
});
describe('ifNEM', function () {
it('should matches not empty values, string, arrays or objects', function () {
var _context = {};
callWithContext(conditionFormatter.ifNEM, _context, 0);
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifNEM, _context, new Date());
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifNEM, _context, 'sdsd');
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifNEM, _context, 12.33);
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifNEM, _context, true);
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifNEM, _context, [12, 23]);
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifNEM, _context, {d : 'd'});
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.stopPropagation, false);
});
it ('should matches empty values, string, arrays or objects', function () {
let _context = {isConditionTrue : false};
callWithContext(conditionFormatter.ifNEM, _context, '');
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifNEM, _context, null);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifNEM, _context, undefined);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifNEM, _context, []);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifNEM, _context, NaN);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
_context.isConditionTrue = false;
callWithContext(conditionFormatter.ifNEM, _context, {});
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.stopPropagation, false);
});
});
describe('Combined conditions', function () {
describe('AND', function () {
it('should be true | ifNE / ifEQ / ifGTE / ifGT / ifLT / ifLTE / ifIN / ifNIN / ifEM / ifNEM', function () {
let _context = {isConditionTrue : false};
callWithContext(conditionFormatter.ifNE, _context, 'delorean', 'tesla');
callWithContext(conditionFormatter.and, _context);
callWithContext(conditionFormatter.ifEQ, _context, 'dragon', 'dragon');
callWithContext(conditionFormatter.and, _context);
callWithContext(conditionFormatter.ifGT, _context, 20, 1);
callWithContext(conditionFormatter.and, _context);
callWithContext(conditionFormatter.ifGTE, _context, -100, -100);
callWithContext(conditionFormatter.and, _context);
callWithContext(conditionFormatter.ifLT, _context, -1000, 30);
callWithContext(conditionFormatter.and, _context);
callWithContext(conditionFormatter.ifLTE, _context, 13987, 13987);
callWithContext(conditionFormatter.and, _context);
callWithContext(conditionFormatter.ifIN, _context, ['potatoes', 'bananas', 'tomatoes'], 'tomatoes');
callWithContext(conditionFormatter.and, _context);
callWithContext(conditionFormatter.ifNIN, _context, ['potatoes', 'bananas', 'tomatoes'], 'grapes');
callWithContext(conditionFormatter.and, _context);
callWithContext(conditionFormatter.ifEM, _context, null);
callWithContext(conditionFormatter.and, _context);
callWithContext(conditionFormatter.ifNEM, _context, new Date());
callWithContext(conditionFormatter.and, _context);
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.isAndOperator, true);
});
it('should be false | ifNE / ifNIN', function () {
let _context = {isConditionTrue : false};
callWithContext(conditionFormatter.ifNE, _context, 'delorean', 'tesla');
callWithContext(conditionFormatter.and, _context);
callWithContext(conditionFormatter.ifNIN, _context, ['potatoes', 'bananas', 'tomatoes'], 'tomatoes');
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.isAndOperator, true);
});
it('should be false | ifEQ / ifEM / ifNEM', function () {
let _context = {isConditionTrue : false};
callWithContext(conditionFormatter.ifEQ, _context, 'delorean', 'delorean');
callWithContext(conditionFormatter.and, _context);
callWithContext(conditionFormatter.ifEM, _context, []);
callWithContext(conditionFormatter.and, _context);
callWithContext(conditionFormatter.ifEM, _context, {id : '1'});
callWithContext(conditionFormatter.and, _context);
callWithContext(conditionFormatter.ifNEM, _context, 'Hey');
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.isAndOperator, true);
});
});
describe('OR', function () {
it('should be true | ifNE / ifNIN', function () {
let _context = {isConditionTrue : false};
callWithContext(conditionFormatter.ifNE, _context, 'delorean', 'tesla');
callWithContext(conditionFormatter.or, _context);
callWithContext(conditionFormatter.ifNIN, _context, ['potatoes', 'bananas', 'tomatoes'], 'tomatoes');
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.isAndOperator, false);
});
it('should be true | ifEQ / ifNEM / ifEM', function () {
let _context = {isConditionTrue : false};
callWithContext(conditionFormatter.ifEQ, _context, 'delorean', 'tesla');
callWithContext(conditionFormatter.or, _context);
callWithContext(conditionFormatter.ifNEM, _context, [1, 2, 3, 4, 5]);
callWithContext(conditionFormatter.or, _context);
callWithContext(conditionFormatter.ifEM, _context, {});
callWithContext(conditionFormatter.or, _context);
callWithContext(conditionFormatter.ifNEM, _context, 'Hey');
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.isAndOperator, false);
});
});
describe('AND/OR/SHOW/ELSE SHOW', function () {
it('Should SHOW + or', function () {
let _context = {isConditionTrue : false};
callWithContext(conditionFormatter.ifGT, _context, 234, 2);
callWithContext(conditionFormatter.or, _context);
callWithContext(conditionFormatter.ifLTE, _context, 10, 2);
helper.assert(callWithContext(conditionFormatter.show, _context, null, 'space'), 'space');
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.isAndOperator, false);
helper.assert(_context.stopPropagation, true);
});
it('Should NOT SHOW + or', function () {
let _context = {isConditionTrue : false};
callWithContext(conditionFormatter.ifGTE, _context, 2, 20);
callWithContext(conditionFormatter.or, _context);
callWithContext(conditionFormatter.ifLT, _context, 10, 2);
callWithContext(conditionFormatter.show, _context);
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.isAndOperator, false);
helper.assert(_context.stopPropagation, false);
});
it('Should ELSESHOW + or', function () {
let _context = {isConditionTrue : false};
callWithContext(conditionFormatter.ifGTE, _context, 2, 20);
callWithContext(conditionFormatter.or, _context);
callWithContext(conditionFormatter.ifLT, _context, 10, 2);
callWithContext(conditionFormatter.show, _context);
helper.assert(_context.stopPropagation, false);
helper.assert(callWithContext(conditionFormatter.elseShow, _context, null, 'space'), 'space');
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.isAndOperator, false);
helper.assert(_context.stopPropagation, true);
});
it('Should SHOW + and', function () {
let _context = {isConditionTrue : false};
callWithContext(conditionFormatter.ifIN, _context, [2, 30, 'apple', -1], 'apple');
callWithContext(conditionFormatter.and, _context);
callWithContext(conditionFormatter.ifLT, _context, -199, 21);
helper.assert(callWithContext(conditionFormatter.show, _context, null, 'space'), 'space');
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.isAndOperator, true);
helper.assert(_context.stopPropagation, true);
});
it('Should SHOW + multiple and', function () {
let _context = {isConditionTrue : false};
callWithContext(conditionFormatter.ifNIN, _context, 'This is a sentence 1234 hey', 'Hello');
callWithContext(conditionFormatter.and, _context);
callWithContext(conditionFormatter.ifLTE, _context, 200, 200);
callWithContext(conditionFormatter.and, _context);
callWithContext(conditionFormatter.ifLT, _context, 0, 1);
helper.assert(callWithContext(conditionFormatter.show, _context, null, 'space'), 'space');
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.isAndOperator, true);
helper.assert(_context.stopPropagation, true);
});
it('Should SHOW + multiple or', function () {
let _context = {isConditionTrue : false};
callWithContext(conditionFormatter.ifNIN, _context, 'This is a sentence 1234 hey', 'hey');
callWithContext(conditionFormatter.or, _context);
callWithContext(conditionFormatter.ifLTE, _context, 22333333, 2100);
callWithContext(conditionFormatter.or, _context);
callWithContext(conditionFormatter.ifEM, _context, null);
callWithContext(conditionFormatter.or, _context);
callWithContext(conditionFormatter.ifGTE, _context, -1, 0);
helper.assert(callWithContext(conditionFormatter.show, _context, null, 'space'), 'space');
helper.assert(_context.isConditionTrue, true);
helper.assert(_context.isAndOperator, false);
helper.assert(_context.stopPropagation, true);
});
it('Should elseShow + multiple or', function () {
let _context = {isConditionTrue : false};
callWithContext(conditionFormatter.ifNIN, _context, 'This is a sentence 1234 hey', 'hey');
callWithContext(conditionFormatter.or, _context);
callWithContext(conditionFormatter.ifLTE, _context, 22222222, 2100);
callWithContext(conditionFormatter.or, _context);
callWithContext(conditionFormatter.ifEM, _context, 'no empty');
callWithContext(conditionFormatter.or, _context);
callWithContext(conditionFormatter.ifGTE, _context, -1, 0);
callWithContext(conditionFormatter.show, _context);
helper.assert(callWithContext(conditionFormatter.elseShow, _context, null, 'space'), 'space');
helper.assert(_context.isConditionTrue, false);
helper.assert(_context.isAndOperator, false);
helper.assert(_context.stopPropagation, true);
});
});
});
describe('print', function () {
it('should print the message', function () {
var _context = {};
helper.assert(callWithContext(stringFormatter.print, _context, null, 'msg'), 'msg');
});
});
describe('convEnum', function () {
it('should convert enums to human readable values', function () {
var _context = {
enum : {
DAY : ['monday', 'tuesday', 'wednesday', 'thursday', 'friday'],
ORDER_STATUS : ['draft' , 'sent', 'received']
}
};
helper.assert(callWithContext(stringFormatter.convEnum, _context, 0, 'DAY'), 'monday');
helper.assert(callWithContext(stringFormatter.convEnum, _context, 2, 'DAY'), 'wednesday');
helper.assert(callWithContext(stringFormatter.convEnum, _context, 2, 'ORDER_STATUS'), 'received');
helper.assert(callWithContext(stringFormatter.convEnum, _context, '1', 'ORDER_STATUS'), 'sent');
});
it('should accept objects for enums', function () {
var _context = {
enum : {
DAY : {
mon : 'monday',
tue : 'tuesday',
wed : 'wednesday',
thu : 'thursday',
fri : 'friday'
}
}
};
helper.assert(callWithContext(stringFormatter.convEnum, _context, 'mon', 'DAY'), 'monday');
helper.assert(callWithContext(stringFormatter.convEnum, _context, 'wed', 'DAY'), 'wednesday');
});
it('should return value if enum translation is not possible', function () {
var _context = {
enum : {
DAY : ['monday', 'tuesday', 'wednesday', 'thursday', 'friday'],
ORDER_STATUS : ['draft' , 'sent', 'received']
}
};
helper.assert(callWithContext(stringFormatter.convEnum, _context, 6, 'DAY'), 6);
helper.assert(callWithContext(stringFormatter.convEnum, _context, 3, 'UNKNOWN_TYPE'), 3);
helper.assert(callWithContext(stringFormatter.convEnum, _context, null, 'UNKNOWN_TYPE'), null);
helper.assert(callWithContext(stringFormatter.convEnum, _context, undefined, 'UNKNOWN_TYPE'), undefined);
helper.assert(callWithContext(stringFormatter.convEnum, _context, [1, 2], 'UNKNOWN_TYPE'), [1, 2]);
helper.assert(callWithContext(stringFormatter.convEnum, _context, {data : 3}, 'UNKNOWN_TYPE'), {data : 3});
});
it('should not crash if enum is not defined. It should return the value', function () {
var _context = {};
helper.assert(callWithContext(stringFormatter.convEnum, _context, 6, 'DAY'), 6);
});
});
describe('lowerCase', function () {
it('should convert a string to lower case', function () {
helper.assert(stringFormatter.lowerCase('AZERTY'), 'azerty');
helper.assert(stringFormatter.lowerCase('qskhREqsLLK;d:sdRTH234'), 'qskhreqsllk;d:sdrth234');
});
it('should not crash if datas is null or undefined', function () {
helper.assert(stringFormatter.lowerCase(null), null);
helper.assert(stringFormatter.lowerCase(undefined), undefined);
helper.assert(stringFormatter.lowerCase(120), 120);
});
});
describe('upperCase', function () {
it('should convert a string to upper case', function () {
helper.assert(stringFormatter.upperCase('azerty'), 'AZERTY');
helper.assert(stringFormatter.upperCase('qskhreqsllk;d:sdrth234'), 'QSKHREQSLLK;D:SDRTH234');
});
it('should not crash if datas is null or undefined', function () {
helper.assert(stringFormatter.upperCase(null), null);
helper.assert(stringFormatter.upperCase(undefined), undefined);
helper.assert(stringFormatter.upperCase(120), 120);
});
});
describe('ucFirst', function () {
it('should upper case the first letter', function () {
helper.assert(stringFormatter.ucFirst('azerty ss'), 'Azerty ss');
helper.assert(stringFormatter.ucFirst(' azerty'), ' azerty');
helper.assert(stringFormatter.ucFirst('qskhreqsllk;d:sdrth234'), 'Qskhreqsllk;d:sdrth234');
});
it('should not crash if datas is null or undefined', function () {
helper.assert(stringFormatter.ucFirst(null), null);
helper.assert(stringFormatter.ucFirst(undefined), undefined);
helper.assert(stringFormatter.ucFirst(120), 120);
helper.assert(stringFormatter.ucFirst([]), []);
});
});
describe('ucWords', function () {
it('should upper case the first letter of each word', function () {
helper.assert(stringFormatter.ucWords('azerty ss zzzeZ'), 'Azerty Ss ZzzeZ');
helper.assert(stringFormatter.ucWords(' azerty'), ' Azerty');
helper.assert(stringFormatter.ucWords('qskhreqsllk; D:sdrt :h234'), 'Qskhreqsllk; D:sdrt :h234');
});
it('should not crash if datas is null or undefined', function () {
helper.assert(stringFormatter.ucWords(null), null);
helper.assert(stringFormatter.ucWords(undefined), undefined);
helper.assert(stringFormatter.ucWords(120), 120);
helper.assert(stringFormatter.ucWords([]), []);
});
});
describe('unaccent', function () {
it('should remove accent from string', function () {
helper.assert(stringFormatter.unaccent('crème brulée'), 'creme brulee');
helper.assert(stringFormatter.unaccent('CRÈME BRULÉE'), 'CREME BRULEE');
helper.assert(stringFormatter.unaccent('être'), 'etre');
helper.assert(stringFormatter.unaccent('éùïêèà'), 'euieea');
});
it('should not crash if datas is null or undefined', function () {
helper.assert(stringFormatter.unaccent(null), null);
helper.assert(stringFormatter.unaccent(undefined), undefined);
helper.assert(stringFormatter.unaccent(120), 120);
});
});
describe('substr', function () {
it('should keep only the selection', function () {
helper.assert(stringFormatter.substr('coucou', 0, 3), 'cou');
helper.assert(stringFormatter.substr('coucou', 0, 0), '');
helper.assert(stringFormatter.substr('coucou', 3, 4), 'c');
});
it('should not crash if data is null or undefined', function () {
helper.assert(stringFormatter.substr(null, 0, 3), null);
helper.assert(stringFormatter.substr(undefined, 0, 3), undefined);
});
});
describe('arrayMap', function () {
it('should flatten the each object of the array (only the first level, ignoring sub arrays, sub objects,...)', function () {
var _datas = [
{id : 2, name : 'car' , type : 'toy' , sub : {id : 3}, arr : [12, 23]},
{id : 3, name : 'plane', type : 'concept', sub : {id : 3}, arr : [12, 23]}
];
helper.assert(arrayFormatter.arrayMap(_datas), '2:car:toy, 3:plane:concept');
});
it('should accept array of strings', function () {
var _datas = ['car', 'plane', 'toy', 42];
helper.assert(arrayFormatter.arrayMap(_datas), 'car, plane, toy, 42');
});
it('should change object and attribute separators', function () {
var _datas = [
{id : 2, name : 'car' , type : 'toy' , sub : {id : 3}},
{id : 3, name : 'plane', type : 'concept', sub : {id : 3}}
];
helper.assert(arrayFormatter.arrayMap(_datas, ' | ', ' ; '), '2 ; car ; toy | 3 ; plane ; concept');
helper.assert(arrayFormatter.arrayMap(_datas, '', ''), '2cartoy3planeconcept');
});
it('should print only given attribute', function () {
var _datas = [
{id : 2, name : 'car' , type : 'toy' , sub : {id : 3}},
{id : 3, name : 'plane', type : 'concept', sub : {id : 3}}
];
helper.assert(arrayFormatter.arrayMap(_datas, ' | ', ' ; ', 'name'), 'car | plane');
});
it('should print a list of given attribute in the same order', function () {
var _datas = [
{id : 2, name : 'car' , type : 'toy' , sub : {id : 3}},
{id : 3, name : 'plane', type : 'concept', sub : {id : 3}}
];
helper.assert(arrayFormatter.arrayMap(_datas, ', ', ':', 'name', 'id', 'type'), 'car:2:toy, plane:3:concept');
});
it('should not crash if datas is null or undefined', function () {
helper.assert(arrayFormatter.arrayMap(null), null);
helper.assert(arrayFormatter.arrayMap(undefined), undefined);
helper.assert(arrayFormatter.arrayMap(120), 120);
helper.assert(arrayFormatter.arrayMap([]), '');
helper.assert(arrayFormatter.arrayMap({}), {});
});
});
describe('arrayJoin', function () {
it('should flatten the array of string', function () {
var _datas = ['1', '2', 'hey!'];
helper.assert(arrayFormatter.arrayJoin(_datas), '1, 2, hey!');
});
it('should change separator', function () {
var _datas = ['1', '2', 'hey!'];
helper.assert(arrayFormatter.arrayJoin(_datas, ''), '12hey!');
helper.assert(arrayFormatter.arrayJoin(_datas, ' | '), '1 | 2 | hey!');
});
it('should not crash if datas is null or undefined', function () {
helper.assert(arrayFormatter.arrayMap(null), null);
helper.assert(arrayFormatter.arrayMap(undefined), undefined);
helper.assert(arrayFormatter.arrayMap(120), 120);
helper.assert(arrayFormatter.arrayMap([]), '');
helper.assert(arrayFormatter.arrayMap({}), {});
});
});
describe('convCurr', function () {
it('should return the same value if the currency source is the same as the currency target', function () {
var _this = {currency : { source : 'EUR', target : 'EUR', rates : {EUR : 1, USD : 1.14, GBP : 0.89} }};
helper.assert(numberFormatter.convCurr.call(_this, 10.1), 10.1);
});
it('should not crash if value or rate is null or undefined', function () {
var _rates = {EUR : 1, USD : 1.14, GBP : 0.8};
var _this = {currency : { source : 'EUR', target : 'USD', rates : _rates }};
helper.assert(numberFormatter.convCurr.call(_this, null), 0);
_this = {currency : { source : null, target : null, rates : _rates }};
helper.assert(numberFormatter.convCurr.call(_this, 10), 10);
});
it('should convert currency', function () {
var _rates = {EUR : 1, USD : 1.14, GBP : 0.8};
var _this = {currency : { source : 'EUR', target : 'USD', rates : _rates }};
helper.assert(numberFormatter.convCurr.call(_this, 10.1), 11.514);
_this = {currency : { source : 'USD', target : 'EUR', rates : _rates }};
helper.assert(numberFormatter.convCurr.call(_this, 11.514), 10.1);
_this = {currency : { source : 'GBP', target : 'EUR', rates : _rates }};
helper.assert(numberFormatter.convCurr.call(_this, 100.4), 125.5);
_this = {currency : { source : 'EUR', target : 'USD', rates : _rates }};
helper.assert(numberFormatter.convCurr.call(_this, 125.5), 143.07);
_this = {currency : { source : 'GBP', target : 'USD', rates : _rates }};
helper.assert(numberFormatter.convCurr.call(_this, 100.4), 143.07);
});
it('should accept to change target in the formatter', function () {
var _rates = {EUR : 1, USD : 1.14, GBP : 0.8};
var _this = {currency : { source : 'EUR', target : 'USD', rates : _rates }};
helper.assert(numberFormatter.convCurr.call(_this, 10.1, 'GBP'), 8.08);
});
it('should accept to change source in the formatter', function () {
var _rates = {EUR : 1, USD : 1.14, GBP : 0.8};
var _this = {currency : { source : 'EUR', target : 'USD', rates : _rates }};
helper.assert(numberFormatter.convCurr.call(_this, 100.4, 'EUR', 'GBP'), 125.5);
});
});
describe('formatN', function () {
it('should format number according to the locale a percentage', function () {
var _this = {lang : 'fr'};
helper.assert(numberFormatter.formatN.call(_this, 10000.1, 1), '10 000,1');
helper.assert(numberFormatter.formatN.call(_this, 10000.1, '1'), '10 000,1');
helper.assert(numberFormatter.formatN.call(_this, 10000.1), '10 000,100');
helper.assert(numberFormatter.formatN.call(_this, null, 1), null);
helper.assert(numberFormatter.formatN.call(_this, undefined, 1), undefined);
helper.assert(numberFormatter.formatN.call(_this, 10000.30202, 5), '10 000,30202');
helper.assert(numberFormatter.formatN.call(_this, -10000.30202, 5), '-10 000,30202');
helper.assert(numberFormatter.formatN.call(_this, -10000.30202, '5'), '-10 000,30202');
helper.assert(numberFormatter.formatN.call(_this, '-10000.30202', '5'), '-10 000,30202');
_this = {lang : 'en-gb'};
helper.assert(numberFormatter.formatN.call(_this, 10000.1, 1), '10,000.1');
helper.assert(numberFormatter.formatN.call(_this, '10000000.1', 1), '10,000,000.1');
});
it.skip('should keep maximal precision if precision is not defined', function () {
var _this = {lang : 'fr'};
helper.assert(numberFormatter.formatN.call(_this, 10000.12345566789), '10 000,12345566789');
});
it('should round number', function () {
var _this = {lang : 'fr'};
helper.assert(numberFormatter.formatN.call(_this, 222.1512, 2), '222,15');
helper.assert(numberFormatter.formatN.call(_this, 222.1552, 2), '222,16');
helper.assert(numberFormatter.formatN.call(_this, 1.005, 2), '1,01');
helper.assert(numberFormatter.formatN.call(_this, 1.005, 3), '1,005');
helper.assert(numberFormatter.formatN.call(_this, -1.005, 3), '-1,005');
helper.assert(numberFormatter.formatN.call(_this, -1.006, 2), '-1,01');
});
});
describe('round', function () {
it('should round number', function () {
var _this = {lang : 'fr'};
helper.assert(numberFormatter.round.call(_this, 222.1512, 2), 222.15);
helper.assert(numberFormatter.round.call(_this, 222.1552, 2), 222.16);
helper.assert(numberFormatter.round.call(_this, 1.005, 2), 1.01);
helper.assert(numberFormatter.round.call(_this, 1.005, 3), 1.005);
helper.assert(numberFormatter.round.call(_this, -1.005, 3), -1.005);
helper.assert(numberFormatter.round.call(_this, -1.006, 2), -1.01);
helper.assert(numberFormatter.round.call(_this, -1.005, 2), -1);
});
});
describe('formatC', function () {
it('should format number according to the locale, currencyTarget, and set automatically the precision', function () {
var _rates = {EUR : 1, USD : 1, GBP : 1};
var _this = {lang : 'en-us', currency : { source : 'EUR', target : 'USD', rates : _rates }};
helper.assert(numberFormatter.formatC.call(_this, 10000.1), '$10,000.10');
_this.currency.target = 'EUR';
helper.assert(numberFormatter.formatC.call(_this, 10000.155), '€10,000.16');
_this.lang = 'fr-fr';
helper.assert(numberFormatter.formatC.call(_this, 10000.1), '10 000,10 €');
helper.assert(numberFormatter.formatC.call(_this, -10000.1), '-10 000,10 €');
helper.assert(numberFormatter.formatC.call(_this, 10000.1, 'M'), 'euros');
helper.assert(numberFormatter.formatC.call(_this, null, 1), null);
helper.assert(numberFormatter.formatC.call(_this, undefined, 1), undefined);
});
it('should change currency output format', function () {
var _rates = {EUR : 1, USD : 1, GBP : 1};
var _this = {lang : 'en-us', currency : { source : 'EUR', target : 'USD', rates : _rates }};
helper.assert(numberFormatter.formatC.call(_this, 10000.1, 'M'), 'dollars');
helper.assert(numberFormatter.formatC.call(_this, 1, 'M'), 'dollar');
helper.assert(numberFormatter.formatC.call(_this, 10.15678, 5), '$10.15678');
helper.assert(numberFormatter.formatC.call(_this, 10.15678, 'LL'), '10.16 dollars');
_this.currency.target = 'EUR';
_this.lang = 'fr-fr';
helper.assert(numberFormatter.formatC.call(_this, 10000.1, 'M'), 'euros');
helper.assert(numberFormatter.formatC.call(_this, 10000.1, 'L'), '10 000,10 €');
helper.assert(numberFormatter.formatC.call(_this, 10000.1, 'LL'), '10 000,10 euros');
helper.assert(numberFormatter.formatC.call(_this, 1, 'LL'), '1,00 euro');
});
it('should convert currency automatically if target != source using rates', function () {
var _rates = {EUR : 1, USD : 2, GBP : 10};
var _this = {lang : 'en-us', currency : { source : 'EUR', target : 'USD', rates : _rates }};
helper.assert(numberFormatter.formatC.call(_this, 10000.1), '$20,000.20');
_this.currency.target = 'GBP';
helper.assert(numberFormatter.formatC.call(_this, 10000.1), '£100,001.00');
});
it('should convert to crypto-currencies/USD by using rates (USD to BTC/ETH AND BTC/ETH to USD)', function () {
var _rates = {USD : 1, BTC : 0.000102618, ETH : 0.003695354, XMR : 0.01218769 };
/** USD to BTC */
var _this = {lang : 'en-us', currency : { source : 'USD', target : 'BTC', rates : _rates }};
helper.assert(numberFormatter.formatC.call(_this, 1255), '₿0.12878559');
/** USD to ETH */
_this.currency.target = 'ETH';
helper.assert(numberFormatter.formatC.call(_this, 32.41), 'Ξ0.119766423');
/** USD to XMR */
_this.currency.target = 'XMR';
helper.assert(numberFormatter.formatC.call(_this, 383991.32), 'XMR4,679.96717085');
/** BTC to USD */
_rates = {USD : 9736.03, BTC : 1};
_this = {lang : 'en-us', currency : { source : 'BTC', target : 'USD', rates : _rates }};
helper.assert(numberFormatter.formatC.call(_this, 2.3155321), '$22,544.09');
/** ETH to USD */
_this.currency.source = 'ETH';
_this.currency.rates = { USD : 247.37, ETH : 1 };
helper.assert(numberFormatter.formatC.call(_this, 0.54212345), '$134.11');
});
it('should accept custom format', function () {
var _rates = {EUR : 1, USD : 1, GBP : 1};
var _this = {lang : 'fr-fr', currency : { source : 'EUR', target : 'EUR', rates : _rates }};
helper.assert(numberFormatter.formatC.call(_this, 10000.1, 'M'), 'euros');
helper.assert(numberFormatter.formatC.call(_this, 1, 'M'), 'euro');
});
it('should be fast', function () {
var _rates = {EUR : 1, USD : 2, GBP : 10};
var _this = {lang : 'en-us', currency : { source : 'EUR', target : 'USD', rates : _rates }};
var _loops = 10000;
var _res = [];
var _start = process.hrtime();
for (var i = 0; i < _loops; i++) {
_res.push(numberFormatter.formatC.call(_this, 10000.1));
}
var _diff = process.hrtime(_start);
var _elapsed = ((_diff[0] * 1e9 + _diff[1]) / 1e6);
console.log('\n formatC number speed : ' + _elapsed + ' ms (around 30ms for 10k) \n');
helper.assert(_elapsed > 50, false, 'formatC is too slow');
});
});
describe('Number operations', function () {
it('should add number', function () {
helper.assert(numberFormatter.add('120', '67'), 187);
});
it('should substract number', function () {
helper.assert(numberFormatter.sub('120', '67'), 53);
});
it('should multiply number', function () {
helper.assert(numberFormatter.mul('120', '67'), 8040);
});
it('should divide number', function () {
helper.assert(numberFormatter.div('120', '80'), 1.5);
});
});
});
/**
* Call a formatter, passing `context` object as `this`
* @param {Function} func formatter to call
* @param {Object} context object
* @return {Mixed} [description]
*/
function callWithContext (func, context) {
context.stopPropagation = false; // reset propagation
var _args = Array.prototype.slice.call(arguments);
return func.apply(context, _args.slice(2));
}
| update ifLT tests
| test/test.formatter.js | update ifLT tests | <ide><path>est/test.formatter.js
<ide> describe('ifLT', function () {
<ide> it ('should matches values, string.length, array.length or object.length that are less than a specified value', function () {
<ide> let _context = {isConditionTrue : false};
<del> callWithContext(conditionFormatter.ifLT, _context, -23, 19);
<del> helper.assert(_context.isConditionTrue, true);
<del> helper.assert(_context.stopPropagation, false);
<del> _context.isConditionTrue = false;
<del> callWithContext(conditionFormatter.ifLT, _context, 1, 768);
<del> helper.assert(_context.isConditionTrue, true);
<del> helper.assert(_context.stopPropagation, false);
<del> _context.isConditionTrue = false;
<del> callWithContext(conditionFormatter.ifLT, _context, '1' , '1234');
<del> helper.assert(_context.isConditionTrue, true);
<del> helper.assert(_context.stopPropagation, false);
<del> _context.isConditionTrue = false;
<del> callWithContext(conditionFormatter.ifLT, _context, 'Short sentence', 'Hello, this is a long sentence');
<del> helper.assert(_context.isConditionTrue, true);
<del> helper.assert(_context.stopPropagation, false);
<del> _context.isConditionTrue = false;
<del> callWithContext(conditionFormatter.ifLT, _context, [1, 2], [1, 2, 3, 4, 5, 6]);
<del> helper.assert(_context.isConditionTrue, true);
<del> helper.assert(_context.stopPropagation, false);
<del> _context.isConditionTrue = false;
<del> callWithContext(conditionFormatter.ifLT, _context, ['apple', 'banana'], ['tomato', 'cabbage', 'jackfruit', 'berry']);
<del> helper.assert(_context.isConditionTrue, true);
<del> helper.assert(_context.stopPropagation, false);
<del> _context.isConditionTrue = false;
<del> callWithContext(conditionFormatter.ifLT, _context, {id : 2, name : 'John'}, {id : 3, name : 'John', lastname : 'Wick', city : 'Paris'});
<del> helper.assert(_context.isConditionTrue, true);
<del> helper.assert(_context.stopPropagation, false);
<del> _context.isConditionTrue = false;
<del>
<del> });
<del>
<del> it ('should matches values, string.length, array.length or object.length that are NOT less than a specified value', function () {
<add> const _dataSet = [
<add> [-23, 19],
<add> [1, 768],
<add> ['1' , '1234'],
<add> ['Short sentence', 'Hello, this is a long sentence'],
<add> [[1, 2], [1, 2, 3, 4, 5, 6]],
<add> [['apple', 'banana'], ['tomato', 'cabbage', 'jackfruit', 'berry']],
<add> [{id : 2, name : 'John'}, {id : 3, name : 'John', lastname : 'Wick', city : 'Paris'}],
<add> ];
<add> for (let i = 0, n = _dataSet.length; i < n; i++) {
<add> const el = _dataSet[i];
<add> _context.isConditionTrue = false;
<add> callWithContext(conditionFormatter.ifLT, _context, el[0], el[1]);
<add> helper.assert(_context.isConditionTrue, true);
<add> helper.assert(_context.stopPropagation, false);
<add> }
<add> });
<add>
<add> it('should matches values, string.length, array.length or object.length that are NOT less than a specified value', function () {
<ide> let _context = {isConditionTrue : false};
<del> callWithContext(conditionFormatter.ifLT, _context, 50, -29);
<del> helper.assert(_context.isConditionTrue, false);
<del> helper.assert(_context.stopPropagation, false);
<del> _context.isConditionTrue = false;
<del> callWithContext(conditionFormatter.ifLT, _context, 0, 0);
<del> helper.assert(_context.isConditionTrue, false);
<del> helper.assert(_context.stopPropagation, false);
<del> _context.isConditionTrue = false;
<del> callWithContext(conditionFormatter.ifLT, _context, 1290, 768);
<del> helper.assert(_context.isConditionTrue, false);
<del> helper.assert(_context.stopPropagation, false);
<del> _context.isConditionTrue = false;
<del> callWithContext(conditionFormatter.ifLT, _context, '1234', '1');
<del> helper.assert(_context.isConditionTrue, false);
<del> helper.assert(_context.stopPropagation, false);
<del> _context.isConditionTrue = false;
<del> callWithContext(conditionFormatter.ifLT, _context, 'This is a long string', 'Hello');
<del> helper.assert(_context.isConditionTrue, false);
<del> helper.assert(_context.stopPropagation, false);
<del> _context.isConditionTrue = false;
<del> callWithContext(conditionFormatter.ifLT, _context, 'ThisEqual', 'Hello1234');
<del> helper.assert(_context.isConditionTrue, false);
<del> helper.assert(_context.stopPropagation, false);
<del> _context.isConditionTrue = false;
<del> callWithContext(conditionFormatter.ifLT, _context, 'Hello1234', '1');
<del> helper.assert(_context.isConditionTrue, false);
<del> helper.assert(_context.stopPropagation, false);
<del> _context.isConditionTrue = false;
<del> callWithContext(conditionFormatter.ifLT, _context, [1, 2, 3, 4, 5], [1, 2, 3]);
<del> helper.assert(_context.isConditionTrue, false);
<del> helper.assert(_context.stopPropagation, false);
<del> _context.isConditionTrue = false;
<del> callWithContext(conditionFormatter.ifLT, _context, [1, 2, 3, 4, 5], [1, 2, 3, 4, 6]);
<del> helper.assert(_context.isConditionTrue, false);
<del> helper.assert(_context.stopPropagation, false);
<del> _context.isConditionTrue = false;
<del> callWithContext(conditionFormatter.ifLT, _context, ['apple', 'banana', 'jackfruit'], ['tomato', 'cabbage']);
<del> helper.assert(_context.isConditionTrue, false);
<del> helper.assert(_context.stopPropagation, false);
<del> _context.isConditionTrue = false;
<del> callWithContext(conditionFormatter.ifLT, _context, ['apple', 'banana'], ['tomato', 'cabbage']);
<del> helper.assert(_context.isConditionTrue, false);
<del> helper.assert(_context.stopPropagation, false);
<del> _context.isConditionTrue = false;
<del> callWithContext(conditionFormatter.ifLT, _context, {id : 2, name : 'John', lastname : 'Wick', city : 'Paris'}, {id : 3, name : 'John'});
<del> helper.assert(_context.isConditionTrue, false);
<del> helper.assert(_context.stopPropagation, false);
<del> _context.isConditionTrue = false;
<del> callWithContext(conditionFormatter.ifLT, _context, {id : 2, name : 'John'}, {id : 3, name : 'Wick'});
<del> helper.assert(_context.isConditionTrue, false);
<del> helper.assert(_context.stopPropagation, false);
<del> _context.isConditionTrue = false;
<del> callWithContext(conditionFormatter.ifLT, _context, {id : 2, name : 'John'}, null);
<del> helper.assert(_context.isConditionTrue, false);
<del> helper.assert(_context.stopPropagation, false);
<del> _context.isConditionTrue = false;
<del> callWithContext(conditionFormatter.ifLT, _context, null, 'Lion and giraffe');
<del> helper.assert(_context.isConditionTrue, false);
<del> helper.assert(_context.stopPropagation, false);
<del> _context.isConditionTrue = false;
<del> callWithContext(conditionFormatter.ifLT, _context, 'Lion and giraffe', null);
<del> helper.assert(_context.isConditionTrue, false);
<del> helper.assert(_context.stopPropagation, false);
<del> _context.isConditionTrue = false;
<del> callWithContext(conditionFormatter.ifLT, _context, null, null);
<del> helper.assert(_context.isConditionTrue, false);
<del> helper.assert(_context.stopPropagation, false);
<del> _context.isConditionTrue = false;
<del> callWithContext(conditionFormatter.ifLT, _context, {id : 2, name : 'John'}, undefined);
<del> helper.assert(_context.isConditionTrue, false);
<del> helper.assert(_context.stopPropagation, false);
<del> _context.isConditionTrue = false;
<del> callWithContext(conditionFormatter.ifLT, _context, undefined, 'Lion and giraffe');
<del> helper.assert(_context.isConditionTrue, false);
<del> helper.assert(_context.stopPropagation, false);
<del> _context.isConditionTrue = false;
<del> callWithContext(conditionFormatter.ifLT, _context, 'Lion and giraffe', undefined);
<del> helper.assert(_context.isConditionTrue, false);
<del> helper.assert(_context.stopPropagation, false);
<del> _context.isConditionTrue = false;
<del> callWithContext(conditionFormatter.ifLT, _context, undefined, undefined);
<del> helper.assert(_context.isConditionTrue, false);
<del> helper.assert(_context.stopPropagation, false);
<add> const _dataSet = [
<add> [50, -29],
<add> [0, 0],
<add> [1290, 768],
<add> ['1234', '1'],
<add> ['This is a long string', 'Hello'],
<add> ['ThisEqual', 'Hello1234'],
<add> ['Hello1234', '1'],
<add> [[1, 2, 3, 4, 5], [1, 2, 3]],
<add> [[1, 2, 3, 4, 5], [1, 2, 3, 4, 6]],
<add> [['apple', 'banana', 'jackfruit'], ['tomato', 'cabbage']],
<add> [['apple', 'banana'], ['tomato', 'cabbage']],
<add> [{id : 2, name : 'John', lastname : 'Wick', city : 'Paris'}, {id : 3, name : 'John'}],
<add> [{id : 2, name : 'John'}, {id : 3, name : 'Wick'}],
<add> [{id : 2, name : 'John'}, null],
<add> [null, 'Lion and giraffe'],
<add> ['Lion and giraffe', null],
<add> [null, null],
<add> [{id : 2, name : 'John'}, undefined],
<add> [undefined, 'Lion and giraffe'],
<add> ['Lion and giraffe', undefined],
<add> [undefined, undefined],
<add> ];
<add> for (let i = 0, n = _dataSet.length; i < n; i++) {
<add> const el = _dataSet[i];
<add> _context.isConditionTrue = false;
<add> callWithContext(conditionFormatter.ifLT, _context, el[0], el[1]);
<add> helper.assert(_context.isConditionTrue, false);
<add> helper.assert(_context.stopPropagation, false);
<add> }
<ide> });
<ide> });
<ide> describe('ifLTE', function () { |
|
Java | mit | error: pathspec 'src/main/java/stopheracleum/controller/UserController.java' did not match any file(s) known to git
| 2d8ef0448eb914a90f78d72edaceb8d12db71e4f | 1 | Milkho/stop-heracleum,Milkho/stop-heracleum | package stopheracleum.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import stopheracleum.model.User;
import stopheracleum.security.SecurityService;
import stopheracleum.service.UserService;
import stopheracleum.validator.UserValidator;
/**
* Controller for {@link stopheracleum.model.User}'s pages.
*/
@Controller
public class UserController {
@Autowired
private UserService userService;
@Autowired
private SecurityService securityService;
@Autowired
private UserValidator userValidator;
@RequestMapping(value = "/registration", method = RequestMethod.GET)
public String registration(Model model) {
model.addAttribute("userForm", new User());
return "registration";
}
@RequestMapping(value = "/registration", method = RequestMethod.POST)
public String registration(@ModelAttribute("userForm") User userForm, BindingResult bindingResult, Model model) {
userValidator.validate(userForm, bindingResult);
if (bindingResult.hasErrors()) {
return "registration";
}
userService.save(userForm);
securityService.autoLogin(userForm.getUsername(), userForm.getConfirmPassword());
return "redirect:/welcome";
}
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String login(Model model, String error, String logout) {
if (error != null) {
model.addAttribute("error", "Username or password is incorrect.");
}
if (logout != null) {
model.addAttribute("message", "Logged out successfully.");
}
return "login";
}
@RequestMapping(value = {"/", "/welcome"}, method = RequestMethod.GET)
public String welcome(Model model) {
return "welcome";
}
@RequestMapping(value = "/admin", method = RequestMethod.GET)
public String admin(Model model) {
return "admin";
}
}
| src/main/java/stopheracleum/controller/UserController.java | Add controller for user's pages
| src/main/java/stopheracleum/controller/UserController.java | Add controller for user's pages | <ide><path>rc/main/java/stopheracleum/controller/UserController.java
<add>package stopheracleum.controller;
<add>
<add>import org.springframework.beans.factory.annotation.Autowired;
<add>import org.springframework.stereotype.Controller;
<add>import org.springframework.ui.Model;
<add>import org.springframework.validation.BindingResult;
<add>import org.springframework.web.bind.annotation.ModelAttribute;
<add>import org.springframework.web.bind.annotation.RequestMapping;
<add>import org.springframework.web.bind.annotation.RequestMethod;
<add>import stopheracleum.model.User;
<add>import stopheracleum.security.SecurityService;
<add>import stopheracleum.service.UserService;
<add>import stopheracleum.validator.UserValidator;
<add>
<add>/**
<add> * Controller for {@link stopheracleum.model.User}'s pages.
<add> */
<add>
<add>@Controller
<add>public class UserController {
<add>
<add> @Autowired
<add> private UserService userService;
<add>
<add> @Autowired
<add> private SecurityService securityService;
<add>
<add> @Autowired
<add> private UserValidator userValidator;
<add>
<add> @RequestMapping(value = "/registration", method = RequestMethod.GET)
<add> public String registration(Model model) {
<add> model.addAttribute("userForm", new User());
<add>
<add> return "registration";
<add> }
<add>
<add> @RequestMapping(value = "/registration", method = RequestMethod.POST)
<add> public String registration(@ModelAttribute("userForm") User userForm, BindingResult bindingResult, Model model) {
<add> userValidator.validate(userForm, bindingResult);
<add>
<add> if (bindingResult.hasErrors()) {
<add> return "registration";
<add> }
<add>
<add> userService.save(userForm);
<add>
<add> securityService.autoLogin(userForm.getUsername(), userForm.getConfirmPassword());
<add>
<add> return "redirect:/welcome";
<add> }
<add>
<add> @RequestMapping(value = "/login", method = RequestMethod.GET)
<add> public String login(Model model, String error, String logout) {
<add> if (error != null) {
<add> model.addAttribute("error", "Username or password is incorrect.");
<add> }
<add>
<add> if (logout != null) {
<add> model.addAttribute("message", "Logged out successfully.");
<add> }
<add>
<add> return "login";
<add> }
<add>
<add> @RequestMapping(value = {"/", "/welcome"}, method = RequestMethod.GET)
<add> public String welcome(Model model) {
<add> return "welcome";
<add> }
<add>
<add> @RequestMapping(value = "/admin", method = RequestMethod.GET)
<add> public String admin(Model model) {
<add> return "admin";
<add> }
<add>} |
|
Java | mit | 872d82620458ee7396b9933a853a3623dd900e9f | 0 | smallmeet/android-vts,sigma-random/android-vts,duo-labs/android-vts,Android-leak/android-vts,duo-labs/android-vts,masbog/android-vts,zenoonez/android-vts,sigma-random/android-vts,ZhouSichong/android-vts,sigma-random/android-vts,idkwim/android-vts,chubbymaggie/android-vts,masbog/android-vts,nowsecure/android-vts,zenoonez/android-vts,peterdocter/android-vts,s4n7h0/android-vts,MindMac/android-vts,marsmensch/android-vts,nowsecure/android-vts,AndroidVTS/android-vts,hubert3/android-vts,peterdocter/android-vts,pwelyn/android-vts,AndroidSecurityTools/android-vts,smallmeet/android-vts,smallmeet/android-vts,pwelyn/android-vts,Android-leak/android-vts,chubbymaggie/android-vts,peterdocter/android-vts,secmob/android-vts,Android-leak/android-vts,zenoonez/android-vts,ZhouSichong/android-vts,AndroidVTS/android-vts,CaledoniaProject/android-vts,hubert3/android-vts,duo-labs/android-vts,CaledoniaProject/android-vts,masbog/android-vts,duo-labs/android-vts,smallmeet/android-vts,secmob/android-vts,secmob/android-vts,hubert3/android-vts,chubbymaggie/android-vts,nowsecure/android-vts,s4n7h0/android-vts,pwelyn/android-vts,nowsecure/android-vts,AndroidSecurityTools/android-vts,peterdocter/android-vts,zenoonez/android-vts,marsmensch/android-vts,AndroidSecurityTools/android-vts,idkwim/android-vts,ZhouSichong/android-vts,AndroidVTS/android-vts,CaledoniaProject/android-vts,marsmensch/android-vts,chubbymaggie/android-vts,idkwim/android-vts,s4n7h0/android-vts,s4n7h0/android-vts,ZhouSichong/android-vts,CaledoniaProject/android-vts,sigma-random/android-vts,Android-leak/android-vts,marsmensch/android-vts,AndroidSecurityTools/android-vts,pwelyn/android-vts,MindMac/android-vts,secmob/android-vts,AndroidVTS/android-vts,masbog/android-vts,MindMac/android-vts | package fuzion24.device.vulnerability.vulnerabilities.framework.media;
import android.content.Context;
import android.content.res.AssetManager;
import android.os.Build;
import android.util.Log;
import org.apache.commons.compress.utils.Charsets;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.commons.io.FilenameUtils;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import fuzion24.device.vulnerability.vulnerabilities.VulnerabilityTest;
/**
* Created by fuzion24 on 8/10/15.
*/
public class StageFright {
private static final String TAG = "StageFright";
private static void exec(String blah) throws Exception {
Runtime.getRuntime().exec(blah);
}
public static List<VulnerabilityTest> getTests(Context context) {
try {
File dataDir = context.getFilesDir();
AssetManager assetManager = context.getAssets();
final String stageFrightAssetPath = "stagefright/stagefright_media_files";
String[] stagefrightMediaFiles = assetManager.list(stageFrightAssetPath);
List<VulnerabilityTest> tests = new ArrayList<VulnerabilityTest>();
final String extractedBinaryTester = dataDir.getAbsolutePath() + File.separator + getNativeAppName();
extractAsset(context, "stagefright" + File.separator + getNativeAppName(),
extractedBinaryTester);
exec("chmod 744 " + extractedBinaryTester);
for (final String mediaFile : stagefrightMediaFiles) {
final String extractedAssetPath = dataDir.getAbsolutePath() + File.separator + mediaFile;
extractAsset(context,
stageFrightAssetPath + File.separator + mediaFile,
extractedAssetPath);
tests.add(new VulnerabilityTest() {
@Override
public String getName() {
return "StageFright: " + FilenameUtils.removeExtension(mediaFile);
}
@Override
public boolean isVulnerable(Context context) throws Exception {
return testMedia(extractedBinaryTester, extractedAssetPath);
}
});
}
return tests;
}catch(Exception e){
e.printStackTrace();
}
return new ArrayList<VulnerabilityTest>();
}
private static boolean testMedia(String binary, String media) throws Exception {
Process process = Runtime.getRuntime().exec(binary + " " + media);
InputStream is = process.getInputStream();
String content = readFully(is, Charsets.UTF_8.displayName());
String errStream = readFully(process.getErrorStream(), Charsets.UTF_8.displayName());
if(errStream.contains("Fatal signal") || content.contains("Boom goes the dynamite")){
return true;
}
process.waitFor();
return false;
}
private static final int BUFFER_SIZE = 2 * 1024 * 1024;
private static void copy(InputStream input, OutputStream output) throws IOException {
try {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead = input.read(buffer);
while (bytesRead != -1) {
output.write(buffer, 0, bytesRead);
bytesRead = input.read(buffer);
}
//If needed, close streams.
} finally {
input.close();
output.close();
}
}
public static String readFully(InputStream inputStream, String encoding)
throws IOException {
return new String(readFully(inputStream), encoding);
}
private static byte[] readFully(InputStream inputStream)
throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length = 0;
while ((length = inputStream.read(buffer)) != -1) {
baos.write(buffer, 0, length);
}
return baos.toByteArray();
}
private static void extractAsset(Context ctx, String name, String destination) throws Exception {
Log.d(TAG, "Extracting \'" + name + "\' from assets to \'" + destination + "\' ...");
try {
File f = new File(destination);
if(f.exists()) {
f.delete();
}
}
catch(Exception e) {e.printStackTrace();}
AssetManager assetManager = ctx.getAssets();
InputStream asset = assetManager.open(name);
FileOutputStream fos = new FileOutputStream(destination);
copy(asset,fos);
}
public static String getNativeAppName() {
return Build.VERSION.SDK_INT >= 16 ? "stagefrightCheck-pie" : "stagefrightCheck";
}
}
| app/src/main/java/fuzion24/device/vulnerability/vulnerabilities/framework/media/Stagefright.java | package fuzion24.device.vulnerability.vulnerabilities.framework.media;
import android.content.Context;
import android.content.res.AssetManager;
import android.os.Build;
import android.util.Log;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import fuzion24.device.vulnerability.vulnerabilities.VulnerabilityTest;
/**
* Created by fuzion24 on 8/10/15.
*/
public class StageFright {
private static final String TAG = "StageFright";
private static void exec(String blah) throws Exception {
Runtime.getRuntime().exec(blah);
}
public static List<VulnerabilityTest> getTests(Context context) {
try {
File dataDir = context.getFilesDir();
AssetManager assetManager = context.getAssets();
final String stageFrightAssetPath = "stagefright/stagefright_media_files";
String[] stagefrightMediaFiles = assetManager.list(stageFrightAssetPath);
List<VulnerabilityTest> tests = new ArrayList<VulnerabilityTest>();
final String extractedBinaryTester = dataDir.getAbsolutePath() + File.separator + getNativeAppName();
extractAsset(context, "stagefright" + File.separator + getNativeAppName(),
extractedBinaryTester);
exec("chmod 744 " + extractedBinaryTester);
for (final String mediaFile : stagefrightMediaFiles) {
final String extractedAssetPath = dataDir.getAbsolutePath() + File.separator + mediaFile;
extractAsset(context,
stageFrightAssetPath + File.separator + mediaFile,
extractedAssetPath);
tests.add(new VulnerabilityTest() {
@Override
public String getName() {
return "StageFright: " + mediaFile;
}
@Override
public boolean isVulnerable(Context context) throws Exception {
testMedia(extractedBinaryTester, extractedAssetPath);
return false;
}
});
}
return tests;
}catch(Exception e){
e.printStackTrace();
}
return new ArrayList<VulnerabilityTest>();
}
private static int testMedia(String binary, String media) throws Exception {
Process process = Runtime.getRuntime().exec(binary + " " + media);
InputStream is = process.getInputStream();
return process.waitFor();
}
private static final int BUFFER_SIZE = 2 * 1024 * 1024;
private static void copy(InputStream input, OutputStream output) throws IOException {
try {
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead = input.read(buffer);
while (bytesRead != -1) {
output.write(buffer, 0, bytesRead);
bytesRead = input.read(buffer);
}
//If needed, close streams.
} finally {
input.close();
output.close();
}
}
private static void extractAsset(Context ctx, String name, String destination) throws Exception {
Log.d(TAG, "Extracting \'" + name + "\' from assets to \'" + destination + "\' ...");
try {
File f = new File(destination);
if(f.exists()) {
f.delete();
}
}
catch(Exception e) {e.printStackTrace();}
AssetManager assetManager = ctx.getAssets();
InputStream asset = assetManager.open(name);
FileOutputStream fos = new FileOutputStream(destination);
copy(asset,fos);
}
public static String getNativeAppName() {
return Build.VERSION.SDK_INT >= 16 ? "stagefrightCheck-pie" : "stagefrightCheck";
}
}
| Check output of binary to see if it crashed or or we caught a bad signal
| app/src/main/java/fuzion24/device/vulnerability/vulnerabilities/framework/media/Stagefright.java | Check output of binary to see if it crashed or or we caught a bad signal | <ide><path>pp/src/main/java/fuzion24/device/vulnerability/vulnerabilities/framework/media/Stagefright.java
<ide> import android.os.Build;
<ide> import android.util.Log;
<ide>
<add>import org.apache.commons.compress.utils.Charsets;
<add>import org.apache.commons.compress.utils.IOUtils;
<add>import org.apache.commons.io.FilenameUtils;
<add>
<add>import java.io.ByteArrayOutputStream;
<ide> import java.io.File;
<ide> import java.io.FileOutputStream;
<ide> import java.io.IOException;
<ide> import java.io.InputStream;
<add>import java.io.InputStreamReader;
<ide> import java.io.OutputStream;
<ide> import java.util.ArrayList;
<ide> import java.util.List;
<add>import java.util.Scanner;
<ide>
<ide> import fuzion24.device.vulnerability.vulnerabilities.VulnerabilityTest;
<ide>
<ide> tests.add(new VulnerabilityTest() {
<ide> @Override
<ide> public String getName() {
<del> return "StageFright: " + mediaFile;
<add> return "StageFright: " + FilenameUtils.removeExtension(mediaFile);
<ide> }
<ide>
<ide> @Override
<ide> public boolean isVulnerable(Context context) throws Exception {
<del> testMedia(extractedBinaryTester, extractedAssetPath);
<del> return false;
<add> return testMedia(extractedBinaryTester, extractedAssetPath);
<ide> }
<ide> });
<ide> }
<ide> return new ArrayList<VulnerabilityTest>();
<ide> }
<ide>
<del> private static int testMedia(String binary, String media) throws Exception {
<add> private static boolean testMedia(String binary, String media) throws Exception {
<ide> Process process = Runtime.getRuntime().exec(binary + " " + media);
<ide> InputStream is = process.getInputStream();
<del> return process.waitFor();
<add>
<add> String content = readFully(is, Charsets.UTF_8.displayName());
<add> String errStream = readFully(process.getErrorStream(), Charsets.UTF_8.displayName());
<add>
<add> if(errStream.contains("Fatal signal") || content.contains("Boom goes the dynamite")){
<add> return true;
<add> }
<add> process.waitFor();
<add> return false;
<ide> }
<del>
<ide>
<ide> private static final int BUFFER_SIZE = 2 * 1024 * 1024;
<ide> private static void copy(InputStream input, OutputStream output) throws IOException {
<ide> input.close();
<ide> output.close();
<ide> }
<add> }
<add>
<add> public static String readFully(InputStream inputStream, String encoding)
<add> throws IOException {
<add> return new String(readFully(inputStream), encoding);
<add> }
<add>
<add>
<add> private static byte[] readFully(InputStream inputStream)
<add> throws IOException {
<add> ByteArrayOutputStream baos = new ByteArrayOutputStream();
<add> byte[] buffer = new byte[1024];
<add> int length = 0;
<add> while ((length = inputStream.read(buffer)) != -1) {
<add> baos.write(buffer, 0, length);
<add> }
<add> return baos.toByteArray();
<ide> }
<ide>
<ide> |
|
Java | epl-1.0 | 96b035ecaa9c6fc3b11bbd4261f82778add274fd | 0 | dupuisa/i-CodeCNES,dupuisa/i-CodeCNES | /************************************************************************************************/
/* i-Code CNES is a static code analyzer. */
/* This software is a free software, under the terms of the Eclipse Public License version 1.0. */
/* http://www.eclipse.org/legal/epl-v10.html */
/************************************************************************************************/
package fr.cnes.icode.shell.rules;
import fr.cnes.icode.datas.AbstractChecker;
import fr.cnes.icode.datas.CheckResult;
import fr.cnes.icode.exception.JFlexException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.*;
/**
* This class aims to test all Shell rules. There are 2 functions in this class.
* The first one verifies that an error in a file is detected whenever there is
* one, the other verifies that nothing is detected when there's no error.
*
* These functions test all rules with values provided by parametrized test.
*/
@RunWith(Parameterized.class)
public class TestAllShellRules {
@Parameters(name = "TEST {index}: {4}")
public static Iterable<Object[]> data() {
return Arrays.asList(new Object[][] {
{"/COM/DATA/Initialisation/error.sh", "/COM/DATA/Initialisation/noError.sh", new int[]{ 9, 15, 20, 25, 27, 32, 37 }, new String[]{ "MAIN PROGRAM", "function1", "MAIN PROGRAM", "function2", "function2", "function3", "MAIN PROGRAM" }, COMDATAInitialisation.class},
{"/COM/DATA/Invariant/error.sh", "/COM/DATA/Invariant/noError.sh", new int[]{ 9, 14, 21, 27, 13, 8, 9, 30}, new String[]{ "MAIN PROGRAM", "MAIN PROGRAM", "fonction", "fonction2", "MAIN PROGRAM", "MAIN PROGRAM" , "MAIN PROGRAM", "MAIN PROGRAM" }, COMDATAInvariant.class},
{"/COM/DATA/LoopCondition/error.sh", "/COM/DATA/LoopCondition/noError.sh", new int[]{ 27, 44 }, new String[]{ "testFunction", "MAIN PROGRAM" }, COMDATALoopCondition.class},
{"/COM/DATA/NotUsed/error.sh", "/COM/DATA/NotUsed/noError.sh", new int[]{ 12 }, new String[]{ "MAIN PROGRAM" }, COMDATANotUsed.class},
{"/COM/DESIGN/ActiveWait/error.sh", "/COM/DESIGN/ActiveWait/noError.sh", new int[]{ 9, 25 }, new String[]{ "MAIN PROGRAM", "MAIN PROGRAM" }, COMDESIGNActiveWait.class},
{"/COM/FLOW/Abort/error.sh", "/COM/FLOW/Abort/noError.sh", new int[]{ 13, 14, 22, 25 }, new String[]{ "MAIN PROGRAM", "MAIN PROGRAM", "testFunction" , "MAIN PROGRAM" }, COMFLOWAbort.class},
{"/COM/FLOW/BooleanExpression/error.sh", "/COM/FLOW/BooleanExpression/noError.sh", new int[]{ 12, 17, 27, 32, 34, 42, 47 }, new String[]{ "test_func", "test_func", "test_func2", "test_func2", "test_func2", "test_func2", "test_func2" }, COMFLOWBooleanExpression.class},
{"/COM/FLOW/CaseSwitch/error.sh", "/COM/FLOW/CaseSwitch/noError.sh", new int[]{ 17, 33, 37, 52 }, new String[]{ "MAIN PROGRAM", "caseFunction", "caseFunction", "MAIN PROGRAM" }, COMFLOWCaseSwitch.class},
{"/COM/FLOW/Exit/error.sh", "/COM/FLOW/Exit/noError.sh", new int[]{ 14, 18, 21, 33, 37, 40 }, new String[]{ "getopts_internal", "getopts_internal", "getopts_internal", "getopts_external", "getopts_external", "getopts_external" }, COMFLOWExit.class},
{"/COM/FLOW/ExitLoop/error.sh", "/COM/FLOW/ExitLoop/noError.sh", new int[]{ 22, 25, 31 }, new String[]{ "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM" }, COMFLOWExitLoop.class},
{"/COM/FLOW/FileExistence/error.sh", "/COM/FLOW/FileExistence/noError.sh", new int[]{ 8, 9, 11, 13, 15, 17, 18, 18, 20, 24, 27, 29 }, new String[]{ "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "my-function", "MAIN PROGRAM", "MAIN PROGRAM" }, COMFLOWFileExistence.class},
{"/COM/FLOW/FilePath/error.sh", "/COM/FLOW/FilePath/noError.sh", new int[]{ 7, 8, 9, 11, 13, 15, 17, 18, 18, 20, 23, 24, 27, 29, 29}, new String[]{ "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "my-function", "my-function", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM"}, COMFLOWFilePath.class},
{"/COM/FLOW/Recursion/error.sh", "/COM/FLOW/Recursion/noError.sh", new int[]{ 16, 40, 48, 49 }, new String[]{ "recursive_directe", "recursive_indirecte2" , "recursive_indirecte3" , "recursive_indirecte3" }, COMFLOWRecursion.class},
{"/COM/INST/BoolNegation/error.sh", "/COM/INST/BoolNegation/noError.sh", new int[]{ 9, 13, 17, 22, 27, 33, 40, 46 }, new String[]{ "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "test1", "test", "MAIN PROGRAM" }, COMINSTBoolNegation.class},
{"/COM/INST/Brace/error.sh", "/COM/INST/Brace/noError.sh", new int[]{ 14 }, new String[]{ "MAIN PROGRAM" }, COMINSTBrace.class},
{"/COM/INST/CodeComment/error.sh", "/COM/INST/CodeComment/noError.sh", new int[]{ 18, 21, 22, 27, 28, 31, 35, 36, 37 }, new String[]{ "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM" }, COMINSTCodeComment.class},
{"/COM/INST/Line/error.sh", "/COM/INST/Line/noError.sh", new int[]{ 10, 11, 24, 25 }, new String[]{ "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM" }, COMINSTLine.class},
{"/COM/INST/LoopCondition/error.sh", "/COM/INST/LoopCondition/noError.sh", new int[]{ 9 }, new String[]{ "MAIN PROGRAM" }, COMINSTLoopCondition.class},
{"/COM/NAME/Homonymy/error.sh", "/COM/NAME/Homonymy/noError.sh", new int[]{ 19, 27, 32, 41, 43, 51, 54, 60, 67, 69, 78, 79 }, new String[]{ "fonction_globale", "MAIN PROGRAM", "MAIN PROGRAM", "test2", "test2", "test3", "test3", "test4", "test4", "test4", "test5", "test5"}, COMNAMEHomonymy.class},
{"/COM/PRES/Header/error.sh", "/COM/PRES/Header/noError.sh", new int[]{ 12, 25 }, new String[]{ "ma_fonction_affine", "affiche_resultat" }, COMPRESHeader.class},
{"/COM/PRES/Indent/error.sh", "/COM/PRES/Indent/noError.sh", new int[]{ 18, 26, 45, 49, 59, 60, 64, 70, 78, 79, 92, 93, 94 }, new String[]{ "ma_fonction_affine", "ma_fonction_affine", "affiche_resultat", "affiche_resultat", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "ma_fonction_affine2", "ma_fonction_affine2", "ma_fonction_affine2" }, COMPRESIndent.class},
{"/COM/PRES/LengthLine/error.sh", "/COM/PRES/LengthLine/noError.sh", new int[]{ 9, 18, 48, 55, 57, 75}, new String[]{ "MAIN PROGRAM", "ma_fonction_affine", "affiche_resultat", "test_length", "affiche_resultat", "MAIN PROGRAM"}, COMPRESLengthLine.class},
{"/COM/TYPE/Expression/error.sh", "/COM/TYPE/Expression/noError.sh", new int[]{ 9, 13 }, new String[]{ "MAIN PROGRAM", "MAIN PROGRAM" }, COMTYPEExpression.class},
{"/SH/DATA/IFS/error.sh", "/SH/DATA/IFS/noError.sh", new int[]{ 18 }, new String[]{ "MAIN PROGRAM" }, SHDATAIFS.class},
{"/SH/DATA/Integer/error.sh", "/SH/DATA/Integer/noError.sh", new int[]{ 12 }, new String[]{ "MAIN PROGRAM" }, SHDATAInteger.class},
{"/SH/DESIGN/Bash/error.sh", "/SH/DESIGN/Bash/noError.sh", new int[]{ 1 }, new String[]{ "MAIN PROGRAM" }, SHDESIGNBash.class},
{"/SH/DESIGN/Options/error.sh", "/SH/DESIGN/Options/noError.sh", new int[]{ 20 }, new String[]{ "getopts_internal" }, SHDESIGNOptions.class},
{"/SH/ERR/Help/error.sh", "/SH/ERR/Help/noError.sh", new int[]{ 40 }, new String[]{ "getopts_internal" }, SHERRHelp.class},
{"/SH/ERR/Help/error2.sh", "/SH/ERR/Help/noError.sh", new int[]{ 43 }, new String[]{ "getopts_internal" }, SHERRHelp.class},
{"/SH/ERR/NoPipe/error.sh", "/SH/ERR/NoPipe/noError.sh", new int[]{ 18, 18, 18, 18, 22, 22, 22, 22, 25, 29, 36 }, new String[]{ "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM" }, SHERRNoPipe.class},
{"/SH/ERR/String/error.sh", "/SH/ERR/String/noError.sh", new int[]{ 17 }, new String[]{ "MAIN PROGRAM" }, SHERRString.class},
{"/SH/FLOW/CheckArguments/error.sh", "/SH/FLOW/CheckArguments/noError.sh", new int[]{ 6 }, new String[]{ "ma_fonction_affine" }, SHFLOWCheckArguments.class},
{"/SH/FLOW/CheckCodeReturn/error.sh", "/SH/FLOW/CheckCodeReturn/noError.sh", new int[]{ 29, 32, 34, 35, 40, 44, 46, 48}, new String[]{ "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "nettoyer_repertoire", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM" }, SHFLOWCheckCodeReturn.class},
{"/SH/FLOW/CheckUser/error.sh", "/SH/FLOW/CheckUser/noError.sh", new int[]{ 6 }, new String[]{ "MAIN PROGRAM" }, SHFLOWCheckUser.class},
{"/SH/INST/Basename/error.sh", "/SH/INST/Basename/noError.sh", new int[]{ 15 }, new String[]{ "MAIN PROGRAM" }, SHINSTBasename.class},
{"/SH/INST/Continue/error.sh", "/SH/INST/Continue/noError.sh", new int[]{ 18 }, new String[]{ "MAIN PROGRAM" }, SHINSTContinue.class},
{"/SH/INST/Find/error.sh", "/SH/INST/Find/noError.sh", new int[]{ 22, 24, 41 }, new String[]{ "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM" }, SHINSTFind.class},
{"/SH/INST/GetOpts/error.sh", "/SH/INST/GetOpts/noError.sh", new int[]{ 22, 23, 26, 27, 28, 29, 0 }, new String[]{ "direct_calls", "direct_calls", "direct_calls", "direct_calls", "direct_calls", "direct_calls", "MAIN PROGRAM" }, SHINSTGetOpts.class},
{"/SH/INST/Interpreter/error.sh", "/SH/INST/Interpreter/noError.sh", new int[]{ 1 }, new String[]{ "MAIN PROGRAM" }, SHINSTInterpreter.class},
{"/SH/INST/Interpreter/error.sh", "/SH/INST/Interpreter/noError2.sh", new int[]{ 1 }, new String[]{ "MAIN PROGRAM" }, SHINSTInterpreter.class},
{"/SH/INST/Keywords/error.sh", "/SH/INST/Keywords/noError.sh", new int[]{ 8, 10, 14, 15, 16, 16 }, new String[]{ "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM" }, SHINSTKeywords.class},
{"/SH/INST/Logical/error.sh", "/SH/INST/Logical/noError.sh", new int[]{ 16 }, new String[]{ "MAIN PROGRAM" }, SHINSTLogical.class},
{"/SH/INST/POSIX/error.sh", "/SH/INST/POSIX/noError.sh", new int[]{ 31, 38 }, new String[]{ "MAIN PROGRAM", "MAIN PROGRAM" }, SHINSTPOSIX.class},
{"/SH/INST/SetShift/error.sh", "/SH/INST/SetShift/noError.sh", new int[]{ 16, 27, 27, 28, 41, 42, 46 }, new String[]{ "MAIN PROGRAM", "getopts_internal", "getopts_internal", "getopts_internal", "getopts_internal", "getopts_internal", "getopts_internal" }, SHINSTSetShift.class},
{"/SH/INST/Variables/error.sh", "/SH/INST/Variables/noError.sh", new int[]{ 17, 21, 23, 23, 23 }, new String[]{ "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM" }, SHINSTVariables.class},
{"/SH/IO/Redirect/error.sh", "/SH/IO/Redirect/noError.sh", new int[]{ 13, 14, 17, 21, 24 }, new String[]{ "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "my-function", "MAIN PROGRAM" }, SHIORedirect.class},
{"/SH/MET/LimitAWK/error.sh", "/SH/MET/LimitAWK/noError.sh", new int[]{ 9 }, new String[]{ "MAIN PROGRAM" }, SHMETLimitAWK.class},
{"/SH/MET/LimitSed/error.sh", "/SH/MET/LimitSed/noError.sh", new int[]{ 12, 20 }, new String[]{ "MAIN PROGRAM", "MAIN PROGRAM" }, SHMETLimitSed.class},
{"/SH/MET/PipeLine/error.sh", "/SH/MET/PipeLine/noError.sh", new int[]{ 8, 16, 19 }, new String[]{ "MAIN PROGRAM", "test1", "test" }, SHMETPipeLine.class},
{"/SH/REF/Export/error.sh", "/SH/REF/Export/noError.sh", new int[]{ 18, 27, 30 }, new String[]{ "MAIN PROGRAM", "testFunction","MAIN PROGRAM" }, SHREFExport.class},
{"/SH/SYNC/Signals/error.sh", "/SH/SYNC/Signals/noError.sh", new int[]{ 57 }, new String[]{ "MAIN PROGRAM" }, SHSYNCSignals.class}
});
}
@Parameter
public String errorFile;
@Parameter(1)
public String noErrorFile;
@Parameter(2)
public int[] lines;
@Parameter(3)
public String[] locations;
@Parameter(4)
public Class<?> checker;
public AbstractChecker rule;
/**
* This test verifies that an error can be detected.
*/
@Test
public void testRunWithError() {
try {
// Initializing rule and getting error file.
final File file = new File(getClass().getResource(errorFile).getFile());
// Instantiate checker.
this.rule = (AbstractChecker) checker.newInstance();
// Defining file in the rule instantiation.
this.rule.setInputFile(file);
// Defining id in the rule instantiation.
this.rule.setId(checker.getName());
// Running rule
final List<CheckResult> list = this.rule.run();
// We verify that there is an error.
assertFalse("No error found.", list.isEmpty());
// We verify that there is the right number of errors
final int nb_CheckResults = list.size();
assertEquals("Wrong number of CheckResults : ", lines.length, nb_CheckResults);
// We verify that the error detected is the right one. There is
// only one case of error : a blank common (with no name) is
// detected.
final String fileName = list.get(0).getFile().getName();
final String[] split = errorFile.split("/");
assertEquals("Wrong file name : ", split[split.length-1], fileName);
// We verify the values
for (final CheckResult value : list) {
final int index = list.indexOf(value);
final String location = value.getLocation();
assertTrue("CheckResult " + Integer.toString(index) + " has wrong location : " + location + " should contain "
+ locations[index], location.contains(locations[index]));
final int line = value.getLine();
assertEquals("CheckResult " + Integer.toString(index) + " is in wrong line : ", lines[index], line);
}
} catch (final JFlexException | IllegalAccessException | InstantiationException | IOException e) {
fail(String.format("Analysis error (%s): %s", e.getClass().getSimpleName(), e.getMessage()));
}
}
/**
* This test verifies nothing is returned when there's no error.
*/
@Test
public void testRunWithoutError() {
try {
// Initializing rule and getting error file.
final File file = new File(getClass().getResource(noErrorFile).getFile());
// Defining file in the rule instantiation.
this.rule = (AbstractChecker) checker.newInstance();
this.rule.setInputFile(file);
// Running rule
final List<CheckResult> list = this.rule.run();
// We verify that there is an error.
assertTrue("Error(s) are detected: " + TestUtils.getCheckResults(list), list.isEmpty());
} catch (final JFlexException | IllegalAccessException | InstantiationException | IOException e) {
fail(String.format("Analysis error (%s): %s", e.getClass().getSimpleName(), e.getMessage()));
}
}
}
| shell-rules/src/test/java/fr/cnes/icode/shell/rules/TestAllShellRules.java | /************************************************************************************************/
/* i-Code CNES is a static code analyzer. */
/* This software is a free software, under the terms of the Eclipse Public License version 1.0. */
/* http://www.eclipse.org/legal/epl-v10.html */
/************************************************************************************************/
package fr.cnes.icode.shell.rules;
import fr.cnes.icode.datas.AbstractChecker;
import fr.cnes.icode.datas.CheckResult;
import fr.cnes.icode.exception.JFlexException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameter;
import org.junit.runners.Parameterized.Parameters;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.*;
/**
* This class aims to test all Shell rules. There are 2 functions in this class.
* The first one verifies that an error in a file is detected whenever there is
* one, the other verifies that nothing is detected when there's no error.
*
* These functions test all rules with values provided by parametrized test.
*/
@RunWith(Parameterized.class)
public class TestAllShellRules {
@Parameters(name = "TEST {index}: {4}")
public static Iterable<Object[]> data() {
return Arrays.asList(new Object[][] {
{"/COM/DATA/Initialisation/error.sh", "/COM/DATA/Initialisation/noError.sh", new int[]{ 9, 15, 20, 25, 27, 32, 37 }, new String[]{ "MAIN PROGRAM", "function1", "MAIN PROGRAM", "function2", "function2", "function3", "MAIN PROGRAM" }, COMDATAInitialisation.class},
{"/COM/DATA/Invariant/error.sh", "/COM/DATA/Invariant/noError.sh", new int[]{ 9, 14, 21, 27, 13, 8, 9, 30}, new String[]{ "MAIN PROGRAM", "MAIN PROGRAM", "fonction", "fonction2", "MAIN PROGRAM", "MAIN PROGRAM" , "MAIN PROGRAM", "MAIN PROGRAM" }, COMDATAInvariant.class},
{"/COM/DATA/LoopCondition/error.sh", "/COM/DATA/LoopCondition/noError.sh", new int[]{ 27, 44 }, new String[]{ "testFunction", "MAIN PROGRAM" }, COMDATALoopCondition.class},
{"/COM/DATA/NotUsed/error.sh", "/COM/DATA/NotUsed/noError.sh", new int[]{ 12 }, new String[]{ "MAIN PROGRAM" }, COMDATANotUsed.class},
{"/COM/DESIGN/ActiveWait/error.sh", "/COM/DESIGN/ActiveWait/noError.sh", new int[]{ 9, 21, 25 }, new String[]{ "MAIN PROGRAM", "readNum", "MAIN PROGRAM" }, COMDESIGNActiveWait.class},
{"/COM/FLOW/Abort/error.sh", "/COM/FLOW/Abort/noError.sh", new int[]{ 13, 14, 22, 25 }, new String[]{ "MAIN PROGRAM", "MAIN PROGRAM", "testFunction" , "MAIN PROGRAM" }, COMFLOWAbort.class},
{"/COM/FLOW/BooleanExpression/error.sh", "/COM/FLOW/BooleanExpression/noError.sh", new int[]{ 12, 17, 27, 32, 34, 42, 47 }, new String[]{ "test_func", "test_func", "test_func2", "test_func2", "test_func2", "test_func2", "test_func2" }, COMFLOWBooleanExpression.class},
{"/COM/FLOW/CaseSwitch/error.sh", "/COM/FLOW/CaseSwitch/noError.sh", new int[]{ 17, 33, 37, 52 }, new String[]{ "MAIN PROGRAM", "caseFunction", "caseFunction", "MAIN PROGRAM" }, COMFLOWCaseSwitch.class},
{"/COM/FLOW/Exit/error.sh", "/COM/FLOW/Exit/noError.sh", new int[]{ 14, 18, 21, 33, 37, 40 }, new String[]{ "getopts_internal", "getopts_internal", "getopts_internal", "getopts_external", "getopts_external", "getopts_external" }, COMFLOWExit.class},
{"/COM/FLOW/ExitLoop/error.sh", "/COM/FLOW/ExitLoop/noError.sh", new int[]{ 22, 25, 31 }, new String[]{ "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM" }, COMFLOWExitLoop.class},
{"/COM/FLOW/FileExistence/error.sh", "/COM/FLOW/FileExistence/noError.sh", new int[]{ 8, 9, 11, 13, 15, 17, 18, 18, 20, 24, 27, 29 }, new String[]{ "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "my-function", "MAIN PROGRAM", "MAIN PROGRAM" }, COMFLOWFileExistence.class},
{"/COM/FLOW/FilePath/error.sh", "/COM/FLOW/FilePath/noError.sh", new int[]{ 7, 8, 9, 11, 13, 15, 17, 18, 18, 20, 23, 24, 27, 29, 29}, new String[]{ "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "my-function", "my-function", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM"}, COMFLOWFilePath.class},
{"/COM/FLOW/Recursion/error.sh", "/COM/FLOW/Recursion/noError.sh", new int[]{ 16, 40, 48, 49 }, new String[]{ "recursive_directe", "recursive_indirecte2" , "recursive_indirecte3" , "recursive_indirecte3" }, COMFLOWRecursion.class},
{"/COM/INST/BoolNegation/error.sh", "/COM/INST/BoolNegation/noError.sh", new int[]{ 9, 13, 17, 22, 27, 33, 40, 46 }, new String[]{ "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "test1", "test", "MAIN PROGRAM" }, COMINSTBoolNegation.class},
{"/COM/INST/Brace/error.sh", "/COM/INST/Brace/noError.sh", new int[]{ 14 }, new String[]{ "MAIN PROGRAM" }, COMINSTBrace.class},
{"/COM/INST/CodeComment/error.sh", "/COM/INST/CodeComment/noError.sh", new int[]{ 18, 21, 22, 27, 28, 31, 35, 36, 37 }, new String[]{ "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM" }, COMINSTCodeComment.class},
{"/COM/INST/Line/error.sh", "/COM/INST/Line/noError.sh", new int[]{ 10, 11, 24, 25 }, new String[]{ "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM" }, COMINSTLine.class},
{"/COM/INST/LoopCondition/error.sh", "/COM/INST/LoopCondition/noError.sh", new int[]{ 9 }, new String[]{ "MAIN PROGRAM" }, COMINSTLoopCondition.class},
{"/COM/NAME/Homonymy/error.sh", "/COM/NAME/Homonymy/noError.sh", new int[]{ 19, 27, 32, 41, 43, 51, 54, 60, 67, 69, 78, 79 }, new String[]{ "fonction_globale", "MAIN PROGRAM", "MAIN PROGRAM", "test2", "test2", "test3", "test3", "test4", "test4", "test4", "test5", "test5"}, COMNAMEHomonymy.class},
{"/COM/PRES/Header/error.sh", "/COM/PRES/Header/noError.sh", new int[]{ 12, 25 }, new String[]{ "ma_fonction_affine", "affiche_resultat" }, COMPRESHeader.class},
{"/COM/PRES/Indent/error.sh", "/COM/PRES/Indent/noError.sh", new int[]{ 18, 26, 45, 49, 59, 60, 64, 70, 78, 79, 92, 93, 94 }, new String[]{ "ma_fonction_affine", "ma_fonction_affine", "affiche_resultat", "affiche_resultat", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "ma_fonction_affine2", "ma_fonction_affine2", "ma_fonction_affine2" }, COMPRESIndent.class},
{"/COM/PRES/LengthLine/error.sh", "/COM/PRES/LengthLine/noError.sh", new int[]{ 9, 18, 48, 55, 57, 75}, new String[]{ "MAIN PROGRAM", "ma_fonction_affine", "affiche_resultat", "test_length", "affiche_resultat", "MAIN PROGRAM"}, COMPRESLengthLine.class},
{"/COM/TYPE/Expression/error.sh", "/COM/TYPE/Expression/noError.sh", new int[]{ 9, 13 }, new String[]{ "MAIN PROGRAM", "MAIN PROGRAM" }, COMTYPEExpression.class},
{"/SH/DATA/IFS/error.sh", "/SH/DATA/IFS/noError.sh", new int[]{ 18 }, new String[]{ "MAIN PROGRAM" }, SHDATAIFS.class},
{"/SH/DATA/Integer/error.sh", "/SH/DATA/Integer/noError.sh", new int[]{ 12 }, new String[]{ "MAIN PROGRAM" }, SHDATAInteger.class},
{"/SH/DESIGN/Bash/error.sh", "/SH/DESIGN/Bash/noError.sh", new int[]{ 1 }, new String[]{ "MAIN PROGRAM" }, SHDESIGNBash.class},
{"/SH/DESIGN/Options/error.sh", "/SH/DESIGN/Options/noError.sh", new int[]{ 20 }, new String[]{ "getopts_internal" }, SHDESIGNOptions.class},
{"/SH/ERR/Help/error.sh", "/SH/ERR/Help/noError.sh", new int[]{ 40 }, new String[]{ "getopts_internal" }, SHERRHelp.class},
{"/SH/ERR/Help/error2.sh", "/SH/ERR/Help/noError.sh", new int[]{ 43 }, new String[]{ "getopts_internal" }, SHERRHelp.class},
{"/SH/ERR/NoPipe/error.sh", "/SH/ERR/NoPipe/noError.sh", new int[]{ 18, 18, 18, 18, 22, 22, 22, 22, 25, 29, 36 }, new String[]{ "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM" }, SHERRNoPipe.class},
{"/SH/ERR/String/error.sh", "/SH/ERR/String/noError.sh", new int[]{ 17 }, new String[]{ "MAIN PROGRAM" }, SHERRString.class},
{"/SH/FLOW/CheckArguments/error.sh", "/SH/FLOW/CheckArguments/noError.sh", new int[]{ 6 }, new String[]{ "ma_fonction_affine" }, SHFLOWCheckArguments.class},
{"/SH/FLOW/CheckCodeReturn/error.sh", "/SH/FLOW/CheckCodeReturn/noError.sh", new int[]{ 29, 32, 34, 35, 40, 44, 46, 48}, new String[]{ "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "nettoyer_repertoire", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM" }, SHFLOWCheckCodeReturn.class},
{"/SH/FLOW/CheckUser/error.sh", "/SH/FLOW/CheckUser/noError.sh", new int[]{ 6 }, new String[]{ "MAIN PROGRAM" }, SHFLOWCheckUser.class},
{"/SH/INST/Basename/error.sh", "/SH/INST/Basename/noError.sh", new int[]{ 15 }, new String[]{ "MAIN PROGRAM" }, SHINSTBasename.class},
{"/SH/INST/Continue/error.sh", "/SH/INST/Continue/noError.sh", new int[]{ 18 }, new String[]{ "MAIN PROGRAM" }, SHINSTContinue.class},
{"/SH/INST/Find/error.sh", "/SH/INST/Find/noError.sh", new int[]{ 22, 24, 41 }, new String[]{ "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM" }, SHINSTFind.class},
{"/SH/INST/GetOpts/error.sh", "/SH/INST/GetOpts/noError.sh", new int[]{ 22, 23, 26, 27, 28, 29, 0 }, new String[]{ "direct_calls", "direct_calls", "direct_calls", "direct_calls", "direct_calls", "direct_calls", "MAIN PROGRAM" }, SHINSTGetOpts.class},
{"/SH/INST/Interpreter/error.sh", "/SH/INST/Interpreter/noError.sh", new int[]{ 1 }, new String[]{ "MAIN PROGRAM" }, SHINSTInterpreter.class},
{"/SH/INST/Interpreter/error.sh", "/SH/INST/Interpreter/noError2.sh", new int[]{ 1 }, new String[]{ "MAIN PROGRAM" }, SHINSTInterpreter.class},
{"/SH/INST/Keywords/error.sh", "/SH/INST/Keywords/noError.sh", new int[]{ 8, 10, 14, 15, 16, 16 }, new String[]{ "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM" }, SHINSTKeywords.class},
{"/SH/INST/Logical/error.sh", "/SH/INST/Logical/noError.sh", new int[]{ 16 }, new String[]{ "MAIN PROGRAM" }, SHINSTLogical.class},
{"/SH/INST/POSIX/error.sh", "/SH/INST/POSIX/noError.sh", new int[]{ 31, 38 }, new String[]{ "MAIN PROGRAM", "MAIN PROGRAM" }, SHINSTPOSIX.class},
{"/SH/INST/SetShift/error.sh", "/SH/INST/SetShift/noError.sh", new int[]{ 16, 27, 27, 28, 41, 42, 46 }, new String[]{ "MAIN PROGRAM", "getopts_internal", "getopts_internal", "getopts_internal", "getopts_internal", "getopts_internal", "getopts_internal" }, SHINSTSetShift.class},
{"/SH/INST/Variables/error.sh", "/SH/INST/Variables/noError.sh", new int[]{ 17, 21, 23, 23, 23 }, new String[]{ "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM" }, SHINSTVariables.class},
{"/SH/IO/Redirect/error.sh", "/SH/IO/Redirect/noError.sh", new int[]{ 13, 14, 17, 21, 24 }, new String[]{ "MAIN PROGRAM", "MAIN PROGRAM", "MAIN PROGRAM", "my-function", "MAIN PROGRAM" }, SHIORedirect.class},
{"/SH/MET/LimitAWK/error.sh", "/SH/MET/LimitAWK/noError.sh", new int[]{ 9 }, new String[]{ "MAIN PROGRAM" }, SHMETLimitAWK.class},
{"/SH/MET/LimitSed/error.sh", "/SH/MET/LimitSed/noError.sh", new int[]{ 12, 20 }, new String[]{ "MAIN PROGRAM", "MAIN PROGRAM" }, SHMETLimitSed.class},
{"/SH/MET/PipeLine/error.sh", "/SH/MET/PipeLine/noError.sh", new int[]{ 8, 16, 19 }, new String[]{ "MAIN PROGRAM", "test1", "test" }, SHMETPipeLine.class},
{"/SH/REF/Export/error.sh", "/SH/REF/Export/noError.sh", new int[]{ 18, 27, 30 }, new String[]{ "MAIN PROGRAM", "testFunction","MAIN PROGRAM" }, SHREFExport.class},
{"/SH/SYNC/Signals/error.sh", "/SH/SYNC/Signals/noError.sh", new int[]{ 57 }, new String[]{ "MAIN PROGRAM" }, SHSYNCSignals.class}
});
}
@Parameter
public String errorFile;
@Parameter(1)
public String noErrorFile;
@Parameter(2)
public int[] lines;
@Parameter(3)
public String[] locations;
@Parameter(4)
public Class<?> checker;
public AbstractChecker rule;
/**
* This test verifies that an error can be detected.
*/
@Test
public void testRunWithError() {
try {
// Initializing rule and getting error file.
final File file = new File(getClass().getResource(errorFile).getFile());
// Instantiate checker.
this.rule = (AbstractChecker) checker.newInstance();
// Defining file in the rule instantiation.
this.rule.setInputFile(file);
// Defining id in the rule instantiation.
this.rule.setId(checker.getName());
// Running rule
final List<CheckResult> list = this.rule.run();
// We verify that there is an error.
assertFalse("No error found.", list.isEmpty());
// We verify that there is the right number of errors
final int nb_CheckResults = list.size();
assertEquals("Wrong number of CheckResults : ", lines.length, nb_CheckResults);
// We verify that the error detected is the right one. There is
// only one case of error : a blank common (with no name) is
// detected.
final String fileName = list.get(0).getFile().getName();
final String[] split = errorFile.split("/");
assertEquals("Wrong file name : ", split[split.length-1], fileName);
// We verify the values
for (final CheckResult value : list) {
final int index = list.indexOf(value);
final String location = value.getLocation();
assertTrue("CheckResult " + Integer.toString(index) + " has wrong location : " + location + " should contain "
+ locations[index], location.contains(locations[index]));
final int line = value.getLine();
assertEquals("CheckResult " + Integer.toString(index) + " is in wrong line : ", lines[index], line);
}
} catch (final JFlexException | IllegalAccessException | InstantiationException | IOException e) {
fail(String.format("Analysis error (%s): %s", e.getClass().getSimpleName(), e.getMessage()));
}
}
/**
* This test verifies nothing is returned when there's no error.
*/
@Test
public void testRunWithoutError() {
try {
// Initializing rule and getting error file.
final File file = new File(getClass().getResource(noErrorFile).getFile());
// Defining file in the rule instantiation.
this.rule = (AbstractChecker) checker.newInstance();
this.rule.setInputFile(file);
// Running rule
final List<CheckResult> list = this.rule.run();
// We verify that there is an error.
assertTrue("Error(s) are detected: " + TestUtils.getCheckResults(list), list.isEmpty());
} catch (final JFlexException | IllegalAccessException | InstantiationException | IOException e) {
fail(String.format("Analysis error (%s): %s", e.getClass().getSimpleName(), e.getMessage()));
}
}
}
| #158 fix tests
| shell-rules/src/test/java/fr/cnes/icode/shell/rules/TestAllShellRules.java | #158 fix tests | <ide><path>hell-rules/src/test/java/fr/cnes/icode/shell/rules/TestAllShellRules.java
<ide> {"/COM/DATA/Invariant/error.sh", "/COM/DATA/Invariant/noError.sh", new int[]{ 9, 14, 21, 27, 13, 8, 9, 30}, new String[]{ "MAIN PROGRAM", "MAIN PROGRAM", "fonction", "fonction2", "MAIN PROGRAM", "MAIN PROGRAM" , "MAIN PROGRAM", "MAIN PROGRAM" }, COMDATAInvariant.class},
<ide> {"/COM/DATA/LoopCondition/error.sh", "/COM/DATA/LoopCondition/noError.sh", new int[]{ 27, 44 }, new String[]{ "testFunction", "MAIN PROGRAM" }, COMDATALoopCondition.class},
<ide> {"/COM/DATA/NotUsed/error.sh", "/COM/DATA/NotUsed/noError.sh", new int[]{ 12 }, new String[]{ "MAIN PROGRAM" }, COMDATANotUsed.class},
<del> {"/COM/DESIGN/ActiveWait/error.sh", "/COM/DESIGN/ActiveWait/noError.sh", new int[]{ 9, 21, 25 }, new String[]{ "MAIN PROGRAM", "readNum", "MAIN PROGRAM" }, COMDESIGNActiveWait.class},
<add> {"/COM/DESIGN/ActiveWait/error.sh", "/COM/DESIGN/ActiveWait/noError.sh", new int[]{ 9, 25 }, new String[]{ "MAIN PROGRAM", "MAIN PROGRAM" }, COMDESIGNActiveWait.class},
<ide> {"/COM/FLOW/Abort/error.sh", "/COM/FLOW/Abort/noError.sh", new int[]{ 13, 14, 22, 25 }, new String[]{ "MAIN PROGRAM", "MAIN PROGRAM", "testFunction" , "MAIN PROGRAM" }, COMFLOWAbort.class},
<ide> {"/COM/FLOW/BooleanExpression/error.sh", "/COM/FLOW/BooleanExpression/noError.sh", new int[]{ 12, 17, 27, 32, 34, 42, 47 }, new String[]{ "test_func", "test_func", "test_func2", "test_func2", "test_func2", "test_func2", "test_func2" }, COMFLOWBooleanExpression.class},
<ide> {"/COM/FLOW/CaseSwitch/error.sh", "/COM/FLOW/CaseSwitch/noError.sh", new int[]{ 17, 33, 37, 52 }, new String[]{ "MAIN PROGRAM", "caseFunction", "caseFunction", "MAIN PROGRAM" }, COMFLOWCaseSwitch.class}, |
|
Java | mit | f8408bd29f4cde06613e2d3077b1d45be0f9f2ff | 0 | kohsuke/github-api,Sampson91/github-api,gitminingOrg/github-api,gecko655/github-api,stephenc/github-api,jeffnelson/github-api,pomes/github-api,marc-guenther/github-api,PankajHingane-REISysIn/KnowledgeArticleExportImport,recena/github-api,christiansahlstrom93/github-api,Shredder121/github-api,if6was9/github-api,mmitche/github-api,dblevins/github-api | package org.kohsuke.github;
import org.junit.After;
import org.junit.Test;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
/**
* @author Kohsuke Kawaguchi
*/
public class PullRequestTest extends AbstractGitHubApiTestBase {
@Test
public void createPullRequest() throws Exception {
String name = rnd.next();
GHPullRequest p = getRepository().createPullRequest(name, "stable", "master", "## test");
System.out.println(p.getUrl());
assertEquals(name, p.getTitle());
}
@Test
public void createPullRequestComment() throws Exception {
String name = rnd.next();
GHPullRequest p = getRepository().createPullRequest(name, "stable", "master", "## test");
p.comment("Some comment");
}
@Test
public void testPullRequestReviewComments() throws Exception {
String name = rnd.next();
GHPullRequest p = getRepository().createPullRequest(name, "stable", "master", "## test");
System.out.println(p.getUrl());
assertTrue(p.listReviewComments().asList().isEmpty());
p.createReviewComment("Sample review comment", p.getHead().getSha(), "cli/pom.xml", 5);
List<GHPullRequestReviewComment> comments = p.listReviewComments().asList();
assertEquals(1, comments.size());
GHPullRequestReviewComment comment = comments.get(0);
assertEquals("Sample review comment", comment.getBody());
comment.update("Updated review comment");
comments = p.listReviewComments().asList();
assertEquals(1, comments.size());
comment = comments.get(0);
assertEquals("Updated review comment", comment.getBody());
comment.delete();
comments = p.listReviewComments().asList();
assertTrue(comments.isEmpty());
}
@Test
// Requires push access to the test repo to pass
public void setLabels() throws Exception {
GHPullRequest p = getRepository().createPullRequest(rnd.next(), "stable", "master", "## test");
String label = rnd.next();
p.setLabels(label);
Collection<GHLabel> labels = getRepository().getPullRequest(p.getNumber()).getLabels();
assertEquals(1, labels.size());
assertEquals(label, labels.iterator().next().getName());
}
@Test
// Requires push access to the test repo to pass
public void setAssignee() throws Exception {
GHPullRequest p = getRepository().createPullRequest(rnd.next(), "stable", "master", "## test");
GHMyself user = gitHub.getMyself();
p.assignTo(user);
assertEquals(user, getRepository().getPullRequest(p.getNumber()).getAssignee());
}
@Test
public void testGetUser() throws IOException {
GHPullRequest p = getRepository().createPullRequest(rnd.next(), "stable", "master", "## test");
GHPullRequest prSingle = getRepository().getPullRequest(p.getNumber());
assertNotNull(prSingle.getUser().root);
prSingle.getMergeable();
assertNotNull(prSingle.getUser().root);
PagedIterable<GHPullRequest> ghPullRequests = getRepository().listPullRequests(GHIssueState.OPEN);
for (GHPullRequest pr : ghPullRequests) {
assertNotNull(pr.getUser().root);
pr.getMergeable();
assertNotNull(pr.getUser().root);
}
}
@After
public void cleanUp() throws Exception {
for (GHPullRequest pr : getRepository().getPullRequests(GHIssueState.OPEN)) {
pr.close();
}
}
private GHRepository getRepository() throws IOException {
return gitHub.getOrganization("github-api-test-org").getRepository("jenkins");
}
}
| src/test/java/org/kohsuke/github/PullRequestTest.java | package org.kohsuke.github;
import org.junit.After;
import org.junit.Test;
import java.io.IOException;
import java.util.Collection;
import java.util.List;
/**
* @author Kohsuke Kawaguchi
*/
public class PullRequestTest extends AbstractGitHubApiTestBase {
@Test
public void createPullRequest() throws Exception {
String name = rnd.next();
GHPullRequest p = getRepository().createPullRequest(name, "stable", "master", "## test");
System.out.println(p.getUrl());
assertEquals(name, p.getTitle());
}
@Test
public void createPullRequestComment() throws Exception {
String name = rnd.next();
GHPullRequest p = getRepository().createPullRequest(name, "stable", "master", "## test");
p.comment("Some comment");
}
@Test
public void testPullRequestReviewComments() throws Exception {
String name = rnd.next();
GHPullRequest p = getRepository().createPullRequest(name, "stable", "master", "## test");
System.out.println(p.getUrl());
assertTrue(p.listReviewComments().asList().isEmpty());
p.createReviewComment("Sample review comment", p.getHead().getSha(), "cli/pom.xml", 5);
List<GHPullRequestReviewComment> comments = p.listReviewComments().asList();
assertEquals(1, comments.size());
GHPullRequestReviewComment comment = comments.get(0);
assertEquals("Sample review comment", comment.getBody());
comment.update("Updated review comment");
comments = p.listReviewComments().asList();
assertEquals(1, comments.size());
comment = comments.get(0);
assertEquals("Updated review comment", comment.getBody());
comment.delete();
comments = p.listReviewComments().asList();
assertTrue(comments.isEmpty());
}
@Test
// Requires push access to the test repo to pass
public void setLabels() throws Exception {
GHPullRequest p = getRepository().createPullRequest(rnd.next(), "stable", "master", "## test");
String label = rnd.next();
p.setLabels(label);
Collection<GHLabel> labels = getRepository().getPullRequest(p.getNumber()).getLabels();
assertEquals(1, labels.size());
assertEquals(label, labels.iterator().next().getName());
}
@Test
// Requires push access to the test repo to pass
public void setAssignee() throws Exception {
GHPullRequest p = getRepository().createPullRequest(rnd.next(), "stable", "master", "## test");
GHMyself user = gitHub.getMyself();
p.assignTo(user);
assertEquals(user, getRepository().getPullRequest(p.getNumber()).getAssignee());
}
@Test
public void testGetUser() throws IOException {
GHPullRequest p = getRepository().createPullRequest(rnd.next(), "stable", "master", "## test");
GHPullRequest prSingle = getRepository().getPullRequest(p.getNumber());
assertNotNull(prSingle.getUser().root);
prSingle.getMergeable();
assertNotNull(prSingle.getUser().root);
PagedIterable<GHPullRequest> ghPullRequests = getRepository().listPullRequests(GHIssueState.OPEN);
for (GHPullRequest pr : ghPullRequests) {
assertNotNull(pr.getUser().root);
assertFalse(pr.getMergeable());
assertNotNull(pr.getUser().root);
}
}
@After
public void cleanUp() throws Exception {
for (GHPullRequest pr : getRepository().getPullRequests(GHIssueState.OPEN)) {
pr.close();
}
}
private GHRepository getRepository() throws IOException {
return gitHub.getOrganization("github-api-test-org").getRepository("jenkins");
}
}
| This method can return null.
I think what's going on is that GitHub takes some non-zero amount of time to compute this value, and our test runs too fast sometimes and try to fetch a PR before its mergeability is computed
| src/test/java/org/kohsuke/github/PullRequestTest.java | This method can return null. | <ide><path>rc/test/java/org/kohsuke/github/PullRequestTest.java
<ide> PagedIterable<GHPullRequest> ghPullRequests = getRepository().listPullRequests(GHIssueState.OPEN);
<ide> for (GHPullRequest pr : ghPullRequests) {
<ide> assertNotNull(pr.getUser().root);
<del> assertFalse(pr.getMergeable());
<add> pr.getMergeable();
<ide> assertNotNull(pr.getUser().root);
<ide> }
<ide> } |
|
Java | apache-2.0 | efae91ab135480139f74fd688ab164ac99a4351e | 0 | liuyuanyuan/dbeaver,AndrewKhitrin/dbeaver,ruspl-afed/dbeaver,AndrewKhitrin/dbeaver,liuyuanyuan/dbeaver,ruspl-afed/dbeaver,liuyuanyuan/dbeaver,ruspl-afed/dbeaver,liuyuanyuan/dbeaver,AndrewKhitrin/dbeaver,liuyuanyuan/dbeaver,ruspl-afed/dbeaver,AndrewKhitrin/dbeaver | /*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2017 Serge Rider ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jkiss.dbeaver.data.office.handlers;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.ui.handlers.HandlerUtil;
import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.Log;
import org.jkiss.dbeaver.core.DBeaverCore;
import org.jkiss.dbeaver.core.DBeaverUI;
import org.jkiss.dbeaver.data.office.export.DataExporterXLSX;
import org.jkiss.dbeaver.data.office.export.StreamPOIConsumerSettings;
import org.jkiss.dbeaver.data.office.export.StreamPOITransferConsumer;
import org.jkiss.dbeaver.model.runtime.AbstractJob;
import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;
import org.jkiss.dbeaver.model.struct.DBSDataContainer;
import org.jkiss.dbeaver.tools.transfer.database.DatabaseProducerSettings;
import org.jkiss.dbeaver.tools.transfer.database.DatabaseTransferProducer;
import org.jkiss.dbeaver.ui.UIUtils;
import org.jkiss.dbeaver.ui.controls.resultset.IResultSetController;
import org.jkiss.dbeaver.ui.controls.resultset.ResultSetCommandHandler;
import org.jkiss.dbeaver.ui.controls.resultset.ResultSetViewer;
import org.jkiss.dbeaver.utils.ContentUtils;
import org.jkiss.dbeaver.utils.GeneralUtils;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
public class OpenSpreadsheetHandler extends AbstractHandler
{
private static final Log log = Log.getLog(OpenSpreadsheetHandler.class);
@Override
public Object execute(ExecutionEvent event) throws ExecutionException
{
IResultSetController resultSet = ResultSetCommandHandler.getActiveResultSet(HandlerUtil.getActivePart(event));
if (resultSet == null) {
DBeaverUI.getInstance().showError("Open Excel", "No active results viewer");
return null;
}
DBSDataContainer dataContainer = resultSet.getDataContainer();
if (dataContainer == null) {
DBeaverUI.getInstance().showError("Open Excel", "No data container");
return null;
}
AbstractJob exportJob = new AbstractJob("Open Excel") {
{
setUser(true);
setSystem(false);
}
@Override
protected IStatus run(DBRProgressMonitor monitor) {
try {
File tempDir = DBeaverCore.getInstance().getTempFolder(monitor, "office-files");
File tempFile = new File(tempDir, "results.data." + System.currentTimeMillis() + ".xlsx");
DataExporterXLSX exporter = new DataExporterXLSX();
StreamPOITransferConsumer consumer = new StreamPOITransferConsumer();
StreamPOIConsumerSettings settings = new StreamPOIConsumerSettings();
settings.setOutputEncodingBOM(false);
settings.setOpenFolderOnFinish(false);
settings.setOutputFolder(tempDir.getAbsolutePath());
settings.setOutputFilePattern(tempFile.getName());
Map<Object, Object> properties = DataExporterXLSX.getDefaultProperties();
consumer.initTransfer(dataContainer, settings, exporter, properties);
DatabaseTransferProducer producer = new DatabaseTransferProducer(dataContainer);
DatabaseProducerSettings producerSettings = new DatabaseProducerSettings();
producerSettings.setExtractType(DatabaseProducerSettings.ExtractType.SINGLE_QUERY);
producerSettings.setQueryRowCount(false);
producer.transferData(monitor, consumer, producerSettings);
consumer.finishTransfer(monitor, false);
DBeaverUI.asyncExec(new Runnable() {
@Override
public void run() {
if (!UIUtils.launchProgram(tempFile.getAbsolutePath())) {
DBeaverUI.getInstance().showError("Open XLSX", "Can't open XLSX file '" + tempFile.getAbsolutePath() + "'");
}
}
});
} catch (Exception e) {
return GeneralUtils.makeExceptionStatus("Error opening Excel", e);
}
return Status.OK_STATUS;
}
};
exportJob.schedule();
return null;
}
} | plugins/org.jkiss.dbeaver.data.office/src/org/jkiss/dbeaver/data/office/handlers/OpenSpreadsheetHandler.java | /*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2017 Serge Rider ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jkiss.dbeaver.data.office.handlers;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.ui.handlers.HandlerUtil;
import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.Log;
import org.jkiss.dbeaver.core.DBeaverCore;
import org.jkiss.dbeaver.core.DBeaverUI;
import org.jkiss.dbeaver.data.office.export.DataExporterXLSX;
import org.jkiss.dbeaver.data.office.export.StreamPOIConsumerSettings;
import org.jkiss.dbeaver.data.office.export.StreamPOITransferConsumer;
import org.jkiss.dbeaver.model.runtime.AbstractJob;
import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor;
import org.jkiss.dbeaver.model.struct.DBSDataContainer;
import org.jkiss.dbeaver.tools.transfer.database.DatabaseProducerSettings;
import org.jkiss.dbeaver.tools.transfer.database.DatabaseTransferProducer;
import org.jkiss.dbeaver.ui.UIUtils;
import org.jkiss.dbeaver.ui.controls.resultset.IResultSetController;
import org.jkiss.dbeaver.ui.controls.resultset.ResultSetCommandHandler;
import org.jkiss.dbeaver.ui.controls.resultset.ResultSetViewer;
import org.jkiss.dbeaver.utils.ContentUtils;
import org.jkiss.dbeaver.utils.GeneralUtils;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
public class OpenSpreadsheetHandler extends AbstractHandler
{
private static final Log log = Log.getLog(OpenSpreadsheetHandler.class);
@Override
public Object execute(ExecutionEvent event) throws ExecutionException
{
IResultSetController resultSet = ResultSetCommandHandler.getActiveResultSet(HandlerUtil.getActivePart(event));
if (resultSet == null) {
DBeaverUI.getInstance().showError("Open Excel", "No active results viewer");
return null;
}
DBSDataContainer dataContainer = resultSet.getDataContainer();
if (dataContainer == null) {
DBeaverUI.getInstance().showError("Open Excel", "No data container");
return null;
}
AbstractJob exportJob = new AbstractJob("Open Excel") {
@Override
protected IStatus run(DBRProgressMonitor monitor) {
try {
File tempDir = DBeaverCore.getInstance().getTempFolder(monitor, "office-files");
File tempFile = new File(tempDir, "results.data." + System.currentTimeMillis() + ".xlsx");
DataExporterXLSX exporter = new DataExporterXLSX();
StreamPOITransferConsumer consumer = new StreamPOITransferConsumer();
StreamPOIConsumerSettings settings = new StreamPOIConsumerSettings();
settings.setOutputEncodingBOM(false);
settings.setOpenFolderOnFinish(false);
settings.setOutputFolder(tempDir.getAbsolutePath());
settings.setOutputFilePattern(tempFile.getName());
Map<Object, Object> properties = DataExporterXLSX.getDefaultProperties();
consumer.initTransfer(dataContainer, settings, exporter, properties);
DatabaseTransferProducer producer = new DatabaseTransferProducer(dataContainer);
DatabaseProducerSettings producerSettings = new DatabaseProducerSettings();
producerSettings.setExtractType(DatabaseProducerSettings.ExtractType.SINGLE_QUERY);
producerSettings.setQueryRowCount(false);
producer.transferData(monitor, consumer, producerSettings);
consumer.finishTransfer(monitor, false);
DBeaverUI.asyncExec(new Runnable() {
@Override
public void run() {
if (!UIUtils.launchProgram(tempFile.getAbsolutePath())) {
DBeaverUI.getInstance().showError("Open XLSX", "Can't open XLSX file '" + tempFile.getAbsolutePath() + "'");
}
}
});
} catch (Exception e) {
return GeneralUtils.makeExceptionStatus("Error opening Excel", e);
}
return Status.OK_STATUS;
}
};
exportJob.schedule();
return null;
}
} | ResultsViewer: open resultset in Excel (UI progress)
| plugins/org.jkiss.dbeaver.data.office/src/org/jkiss/dbeaver/data/office/handlers/OpenSpreadsheetHandler.java | ResultsViewer: open resultset in Excel (UI progress) | <ide><path>lugins/org.jkiss.dbeaver.data.office/src/org/jkiss/dbeaver/data/office/handlers/OpenSpreadsheetHandler.java
<ide>
<ide> AbstractJob exportJob = new AbstractJob("Open Excel") {
<ide>
<add> {
<add> setUser(true);
<add> setSystem(false);
<add> }
<add>
<ide> @Override
<ide> protected IStatus run(DBRProgressMonitor monitor) {
<ide> try { |
|
Java | epl-1.0 | 319ca2895aa724cb0a577120c72abeb6c4bc0997 | 0 | upohl/eloquent,upohl/eloquent | package org.muml.psm.allocation.algorithm.ui.wizard;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.emf.transaction.TransactionalEditingDomain;
import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.ListViewer;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.wizard.IWizardPage;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.ui.IWorkbench;
import org.muml.ape.runtime.editors.ObjectPropertyEditor;
import org.muml.ape.runtime.wizard.PropertyEditorWizardPage;
import org.muml.core.export.operation.IFujabaExportOperation;
import org.muml.core.export.pages.AbstractFujabaExportSourcePage;
import org.muml.core.export.pages.ElementSelectionMode;
import org.muml.core.export.wizard.AbstractFujabaExportWizard;
import org.muml.core.modelinstance.ModelElementCategory;
import org.muml.core.modelinstance.RootNode;
import org.muml.pim.PimPackage;
import org.muml.pim.instance.ComponentInstanceConfiguration;
import org.muml.pm.hardware.HardwarePackage;
import org.muml.pm.hardware.hwplatforminstance.HWPlatformInstanceConfiguration;
import org.muml.psm.allocation.SystemAllocation;
import org.muml.psm.allocation.algorithm.main.AllocationComputationStrategyExtension;
import org.muml.psm.allocation.algorithm.main.AllocationComputationStrategyExtension.AllocationComputationStrategyDescription;
import org.muml.psm.allocation.algorithm.main.IAllocationComputationStrategy;
import org.muml.psm.allocation.language.cs.SpecificationCS;
public class AllocationWizard extends AbstractFujabaExportWizard {
private static final String title = "Create Allocation Wizard";
private AbstractFujabaExportSourcePage cicSourcePage;
private AbstractFujabaExportSourcePage hpicSourcePage;
private AbstractFujabaExportSourcePage allocationSpecificationSourcePage;
private AbstractFujabaExportSourcePage targetPage;
private AllocationComputationStrategySelectionPage strategyPage;
@Override
public void init(IWorkbench workbench, IStructuredSelection currentSelection) {
super.init(workbench, currentSelection);
setWindowTitle(title);
// explicitly setup these packages otherwise the qvto compilation
// fails (mars) - might be related to the qvto commit
// de499dbfbd960a63f62c4938d9dc71172e075120
// (actually, this belongs to the QVToTransformationRunner class,
// but I want keep that class clean)
PimPackage.eINSTANCE.eClass();
HardwarePackage.eINSTANCE.eClass();
}
@Override
public String wizardGetId() {
return "de.uni_paderborn.fujaba.export.ExampleWizard";
}
public void addPages() {
// cic and hpic selection source page
cicSourcePage = new AbstractFujabaExportSourcePage("CicSP", toolkit,
getResourceSet(), initialSelection) {
{
setTitle("Select Component Instance Configuration");
setDescription("Select Component Instance Configuration, whose component instances should be allocated");
}
@Override
public String wizardPageGetSourceFileExtension() {
return "muml";
}
@Override
public ElementSelectionMode wizardPageGetSupportedSelectionMode() {
return ElementSelectionMode.ELEMENT_SELECTION_MODE_SINGLE;
}
@Override
public boolean wizardPageSupportsSourceModelElement(EObject element) {
return element instanceof ComponentInstanceConfiguration;
}
};
addPage(cicSourcePage);
// hpic source page
hpicSourcePage = new AbstractFujabaExportSourcePage("HpicSP", toolkit,
getResourceSet(), initialSelection) {
{
setTitle("Select HW Platform Instance Configuration");
setDescription("The HW Platform Instance Configuration provides the ECUs");
}
@Override
public String wizardPageGetSourceFileExtension() {
return "muml";
}
@Override
public ElementSelectionMode wizardPageGetSupportedSelectionMode() {
return ElementSelectionMode.ELEMENT_SELECTION_MODE_SINGLE;
}
@Override
public boolean wizardPageSupportsSourceModelElement(EObject element) {
return element instanceof HWPlatformInstanceConfiguration;
}
};
addPage(hpicSourcePage);
// allocation specification source page
allocationSpecificationSourcePage = new AbstractFujabaExportSourcePage("AllocSpecSP", toolkit,
getResourceSet(), initialSelection) {
{
setTitle("Select Allocation Specification");
setDescription("The Allocation Specification specifies the constraints and objective function");
}
@Override
public String wizardPageGetSourceFileExtension() {
return "allocation_specification";
}
@Override
public boolean wizardPageSupportsSourceModelElement(EObject element) {
return element instanceof SpecificationCS;
}
@Override
public ElementSelectionMode wizardPageGetSupportedSelectionMode() {
return ElementSelectionMode.ELEMENT_SELECTION_MODE_SINGLE;
}
};
addPage(allocationSpecificationSourcePage);
// target page
targetPage = new AbstractFujabaExportSourcePage("targetSP", toolkit,
getResourceSet(), initialSelection) {
{
setTitle("Select the target System Allocation");
setDescription("By default a new System Allocation is created");
}
@Override
public String wizardPageGetSourceFileExtension() {
return "muml";
}
@Override
public ElementSelectionMode wizardPageGetSupportedSelectionMode() {
return ElementSelectionMode.ELEMENT_SELECTION_MODE_SINGLE;
}
@Override
public boolean wizardPageSupportsSourceModelElement(EObject element) {
return element instanceof ModelElementCategory
|| element instanceof RootNode
|| element instanceof SystemAllocation;
}
};
addPage(targetPage);
AllocationComputationStrategyConfigurationPage configPage = new AllocationComputationStrategyConfigurationPage();
// allocation computation strategy page
strategyPage = new AllocationComputationStrategySelectionPage("strategy", configPage);
addPage(strategyPage);
addPage(configPage);
}
@Override
public IFujabaExportOperation wizardCreateExportOperation() {
return new CreateAllocationOperation(editingDomain,
(SpecificationCS) allocationSpecificationSourcePage.getSourceElements()[0],
(ComponentInstanceConfiguration) cicSourcePage.getSourceElements()[0],
(HWPlatformInstanceConfiguration) hpicSourcePage.getSourceElements()[0],
targetPage.getSourceElements()[0],
strategyPage.getAllocationComputationStrategy());
}
public static class AllocationComputationStrategySelectionPage extends WizardPage {
private static final String title =
"Select an allocation computation strategy";
private static final String description =
"The selected strategy is used to compute an allocation";
private static final String invalidSelection =
"Please select an allocation computation strategy";
private ListViewer listViewer;
private IStructuredSelection structuredSelection;
private Map<String, IAllocationComputationStrategy<?>> strategyCache;
private AllocationComputationStrategyConfigurationPage configPage;
public AllocationComputationStrategySelectionPage(String pageName, AllocationComputationStrategyConfigurationPage configPage) {
super(pageName);
setTitle(title);
setDescription(description);
strategyCache = new HashMap<String, IAllocationComputationStrategy<?>>();
this.configPage = configPage;
}
@Override
public void createControl(Composite parent) {
Composite composite = new Composite(parent, SWT.NONE);
GridLayout layout = new GridLayout();
layout.numColumns = 1;
composite.setLayout(layout);
setControl(composite);
listViewer = new ListViewer(composite);
listViewer.getControl().setLayoutData(
new GridData(GridData.FILL_HORIZONTAL));
listViewer.setContentProvider(new ArrayContentProvider());
listViewer.setLabelProvider(new LabelProvider() {
@Override
public String getText(Object object) {
if (object instanceof AllocationComputationStrategyDescription) {
return ((AllocationComputationStrategyDescription) object)
.getName();
}
return "";
}
});
final Label label = new Label(composite, SWT.LEFT);
label.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
ISelectionChangedListener strategyListener = new ISelectionChangedListener() {
@Override
public void selectionChanged(SelectionChangedEvent event) {
if (event.getSelection() instanceof IStructuredSelection) {
IStructuredSelection ssel = (IStructuredSelection) event.getSelection();
structuredSelection = ssel;
if (ssel.getFirstElement() instanceof AllocationComputationStrategyDescription) {
String text = ((AllocationComputationStrategyDescription) ssel.getFirstElement())
.getDescription();
label.setText(text);
}
validatePage();
}
}
};
listViewer.addSelectionChangedListener(strategyListener);
}
@Override
public void setVisible(boolean visible) {
super.setVisible(visible);
if (visible) {
AllocationComputationStrategyDescription[] descriptions =
AllocationComputationStrategyExtension.getDescriptions();
listViewer.setInput(descriptions);
if (descriptions.length > 0 && structuredSelection == null) {
structuredSelection = new StructuredSelection(
descriptions[0]);
}
listViewer.setSelection(structuredSelection, true);
}
}
@Override
public IWizardPage getNextPage() {
if (isValid()) {
IAllocationComputationStrategy<?> strategy = getAllocationComputationStrategy();
Object configuration = strategy.getConfiguration();
if (!(configuration instanceof EObject)) {
// cannot handle this => no configuration wizard page
return null;
}
configPage.setConfiguration((EObject) configuration);
return configPage;
}
return null;
}
private boolean isValid() {
return structuredSelection.getFirstElement() instanceof AllocationComputationStrategyDescription;
}
protected boolean validatePage() {
boolean isValid = isValid();
setPageComplete(isValid);
if (!isValid) {
setErrorMessage(invalidSelection);
}
return isValid;
}
@NonNull
public IAllocationComputationStrategy<?> getAllocationComputationStrategy() {
// the wildcard return type is OK, because usually the caller does not
// need fiddle with config object, because setting up the config object
// is the job of this wizard
if (structuredSelection == null) {
throw new IllegalStateException("structuredSelection is null (should not happen");
}
// assumption: two different strategies have different names
// (IMHO, a reasonable assumption...)
AllocationComputationStrategyDescription description =
((AllocationComputationStrategyDescription) structuredSelection.getFirstElement());
String key = description.getName();
IAllocationComputationStrategy<?> strategy = strategyCache
.get(key);
if (strategy == null) {
try {
strategy = ((AllocationComputationStrategyDescription) structuredSelection
.getFirstElement()).getAllocationComputationStrategy();
strategyCache.put(key, strategy);
} catch (CoreException e) {
throw new IllegalStateException("Failed to create strategy", e);
}
}
return strategy;
}
}
public static class AllocationComputationStrategyConfigurationPage extends PropertyEditorWizardPage {
// inspired by/stolen from de.uni_paderborn.fujaba.muml.verification.uppaal.ui.OptionsWizardPage
private static final String tabId = "de.uni_paderborn.fujaba.muml.allocation.algorithm.ilp.opt4j.config";
private static final String title = "Configuration options for the Opt4j EA";
private static final String description = "Configure the Opt4j evolutionary algorithm";
public AllocationComputationStrategyConfigurationPage() {
super(new ObjectPropertyEditor(tabId, null, "Options", true));
setTitle(title);
setDescription(description);
}
public void setConfiguration(EObject configuration) {
// create dummy resource unless the configuration object is already contained
// in a resource
if (configuration.eResource() == null) {
ResourceSet resSet = new ResourceSetImpl();
Resource resource = resSet.createResource(
URI.createURI("dummy://dummy.ecore"));
resource.getContents().add(configuration);
// just to make APE happy (otherwise APE will not modify the object
// (see org.muml.ape.runtime.editors.AbstractStructuralFeaturePropertyEditor.setValue))
TransactionalEditingDomain.Factory.INSTANCE.createEditingDomain(resSet);
}
setInput(configuration);
}
}
}
| plugins/org.muml.psm.allocation.algorithm.ui/src/org/muml/psm/allocation/algorithm/ui/wizard/AllocationWizard.java | package org.muml.psm.allocation.algorithm.ui.wizard;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.emf.transaction.TransactionalEditingDomain;
import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jface.viewers.ArrayContentProvider;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.ListViewer;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.wizard.IWizardPage;
import org.eclipse.jface.wizard.WizardPage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.ui.IWorkbench;
import org.muml.ape.runtime.editors.ObjectPropertyEditor;
import org.muml.ape.runtime.wizard.PropertyEditorWizardPage;
import org.muml.core.export.operation.IFujabaExportOperation;
import org.muml.core.export.pages.AbstractFujabaExportSourcePage;
import org.muml.core.export.pages.ElementSelectionMode;
import org.muml.core.export.wizard.AbstractFujabaExportWizard;
import org.muml.core.modelinstance.ModelElementCategory;
import org.muml.core.modelinstance.RootNode;
import org.muml.pim.PimPackage;
import org.muml.pim.instance.ComponentInstanceConfiguration;
import org.muml.pm.hardware.HardwarePackage;
import org.muml.pm.hardware.hwplatforminstance.HWPlatformInstanceConfiguration;
import org.muml.psm.allocation.SystemAllocation;
import org.muml.psm.allocation.algorithm.main.AllocationComputationStrategyExtension;
import org.muml.psm.allocation.algorithm.main.AllocationComputationStrategyExtension.AllocationComputationStrategyDescription;
import org.muml.psm.allocation.algorithm.main.IAllocationComputationStrategy;
import org.muml.psm.allocation.language.cs.SpecificationCS;
public class AllocationWizard extends AbstractFujabaExportWizard {
private static final String title = "Create Allocation Wizard";
private AbstractFujabaExportSourcePage cicSourcePage;
private AbstractFujabaExportSourcePage hpicSourcePage;
private AbstractFujabaExportSourcePage allocationSpecificationSourcePage;
private AbstractFujabaExportSourcePage targetPage;
private AllocationComputationStrategySelectionPage strategyPage;
@Override
public void init(IWorkbench workbench, IStructuredSelection currentSelection) {
super.init(workbench, currentSelection);
setWindowTitle(title);
// explicitly setup these packages otherwise the qvto compilation
// fails (mars) - might be related to the qvto commit
// de499dbfbd960a63f62c4938d9dc71172e075120
// (actually, this belongs to the QVToTransformationRunner class,
// but I want keep that class clean)
PimPackage.eINSTANCE.eClass();
HardwarePackage.eINSTANCE.eClass();
}
@Override
public String wizardGetId() {
return "de.uni_paderborn.fujaba.export.ExampleWizard";
}
public void addPages() {
// cic and hpic selection source page
cicSourcePage = new AbstractFujabaExportSourcePage("CicSP", toolkit,
getResourceSet(), initialSelection) {
{
setTitle("Select Component Instance Configuration");
setDescription("Select Component Instance Configuration, whose component instances should be allocated");
}
@Override
public String wizardPageGetSourceFileExtension() {
return "muml";
}
@Override
public ElementSelectionMode wizardPageGetSupportedSelectionMode() {
return ElementSelectionMode.ELEMENT_SELECTION_MODE_SINGLE;
}
@Override
public boolean wizardPageSupportsSourceModelElement(EObject element) {
return element instanceof ComponentInstanceConfiguration;
}
};
addPage(cicSourcePage);
// hpic source page
hpicSourcePage = new AbstractFujabaExportSourcePage("HpicSP", toolkit,
getResourceSet(), initialSelection) {
{
setTitle("Select HW Platform Instance Configuration");
setDescription("The HW Platform Instance Configuration provides the ECUs");
}
@Override
public String wizardPageGetSourceFileExtension() {
return "muml";
}
@Override
public ElementSelectionMode wizardPageGetSupportedSelectionMode() {
return ElementSelectionMode.ELEMENT_SELECTION_MODE_SINGLE;
}
@Override
public boolean wizardPageSupportsSourceModelElement(EObject element) {
return element instanceof HWPlatformInstanceConfiguration;
}
};
addPage(hpicSourcePage);
// allocation specification source page
allocationSpecificationSourcePage = new AbstractFujabaExportSourcePage("AllocSpecSP", toolkit,
getResourceSet(), initialSelection) {
{
setTitle("Select Allocation Specification");
setDescription("The Allocation Specification specifies the constraints and objective function");
}
@Override
public String wizardPageGetSourceFileExtension() {
return "allocation_specification";
}
@Override
public boolean wizardPageSupportsSourceModelElement(EObject element) {
return element instanceof SpecificationCS;
}
@Override
public ElementSelectionMode wizardPageGetSupportedSelectionMode() {
return ElementSelectionMode.ELEMENT_SELECTION_MODE_SINGLE;
}
};
addPage(allocationSpecificationSourcePage);
// target page
targetPage = new AbstractFujabaExportSourcePage("targetSP", toolkit,
getResourceSet(), initialSelection) {
{
setTitle("Select the target System Allocation");
setDescription("By default a new System Allocation is created");
}
@Override
public String wizardPageGetSourceFileExtension() {
return "muml";
}
@Override
public ElementSelectionMode wizardPageGetSupportedSelectionMode() {
return ElementSelectionMode.ELEMENT_SELECTION_MODE_SINGLE;
}
@Override
public boolean wizardPageSupportsSourceModelElement(EObject element) {
return element instanceof ModelElementCategory
|| element instanceof RootNode
|| element instanceof SystemAllocation;
}
};
addPage(targetPage);
AllocationComputationStrategyConfigurationPage configPage = new AllocationComputationStrategyConfigurationPage();
// allocation computation strategy page
strategyPage = new AllocationComputationStrategySelectionPage("strategy", configPage);
addPage(strategyPage);
addPage(configPage);
}
@Override
public IFujabaExportOperation wizardCreateExportOperation() {
return new CreateAllocationOperation(editingDomain,
(SpecificationCS) allocationSpecificationSourcePage.getSourceElements()[0],
(ComponentInstanceConfiguration) cicSourcePage.getSourceElements()[0],
(HWPlatformInstanceConfiguration) hpicSourcePage.getSourceElements()[0],
targetPage.getSourceElements()[0],
strategyPage.getAllocationComputationStrategy());
}
public static class AllocationComputationStrategySelectionPage extends WizardPage {
private static final String title =
"Select an allocation computation strategy";
private static final String description =
"The selected strategy is used to compute an allocation";
private static final String invalidSelection =
"Please select an allocation computation strategy";
private ListViewer listViewer;
private IStructuredSelection structuredSelection;
private Map<String, IAllocationComputationStrategy<?>> strategyCache;
private AllocationComputationStrategyConfigurationPage configPage;
public AllocationComputationStrategySelectionPage(String pageName, AllocationComputationStrategyConfigurationPage configPage) {
super(pageName);
setTitle(title);
setDescription(description);
strategyCache = new HashMap<String, IAllocationComputationStrategy<?>>();
this.configPage = configPage;
}
@Override
public void createControl(Composite parent) {
Composite composite = new Composite(parent, SWT.NONE);
GridLayout layout = new GridLayout();
layout.numColumns = 1;
composite.setLayout(layout);
setControl(composite);
listViewer = new ListViewer(composite);
listViewer.getControl().setLayoutData(
new GridData(GridData.FILL_HORIZONTAL));
listViewer.setContentProvider(new ArrayContentProvider());
listViewer.setLabelProvider(new LabelProvider() {
@Override
public String getText(Object object) {
if (object instanceof AllocationComputationStrategyDescription) {
return ((AllocationComputationStrategyDescription) object)
.getName();
}
return "";
}
});
final Label label = new Label(composite, SWT.LEFT);
label.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
ISelectionChangedListener strategyListener = new ISelectionChangedListener() {
@Override
public void selectionChanged(SelectionChangedEvent event) {
if (event.getSelection() instanceof IStructuredSelection) {
IStructuredSelection ssel = (IStructuredSelection) event.getSelection();
structuredSelection = ssel;
if (ssel.getFirstElement() instanceof AllocationComputationStrategyDescription) {
String text = ((AllocationComputationStrategyDescription) ssel.getFirstElement())
.getDescription();
label.setText(text);
}
validatePage();
}
}
};
listViewer.addSelectionChangedListener(strategyListener);
}
@Override
public void setVisible(boolean visible) {
super.setVisible(visible);
if (visible) {
AllocationComputationStrategyDescription[] descriptions =
AllocationComputationStrategyExtension.getDescriptions();
listViewer.setInput(descriptions);
if (descriptions.length > 0 && structuredSelection == null) {
structuredSelection = new StructuredSelection(
descriptions[0]);
}
listViewer.setSelection(structuredSelection, true);
}
}
@Override
public IWizardPage getNextPage() {
if (isValid()) {
IAllocationComputationStrategy<?> strategy = getAllocationComputationStrategy();
Object configuration = strategy.getConfiguration();
if (!(configuration instanceof EObject)) {
// cannot handle this => no configuration wizard page
return null;
}
configPage.setConfiguration((EObject) configuration);
return configPage;
}
return null;
}
private boolean isValid() {
return structuredSelection.getFirstElement() instanceof AllocationComputationStrategyDescription;
}
protected boolean validatePage() {
boolean isValid = isValid();
setPageComplete(isValid);
if (!isValid) {
setErrorMessage(invalidSelection);
}
return isValid;
}
@NonNull
public IAllocationComputationStrategy<?> getAllocationComputationStrategy() {
// the wildcard return type is OK, because usually the caller does not
// need fiddle with config object, because setting up the config object
// is the job of this wizard
if (structuredSelection == null) {
throw new IllegalStateException("structuredSelection is null (should not happen");
}
// assumption: two different strategies have different names
// (IMHO, a reasonable assumption...)
AllocationComputationStrategyDescription description =
((AllocationComputationStrategyDescription) structuredSelection.getFirstElement());
String key = description.getName();
IAllocationComputationStrategy<?> strategy = strategyCache
.get(key);
if (strategy == null) {
try {
strategy = ((AllocationComputationStrategyDescription) structuredSelection
.getFirstElement()).getAllocationComputationStrategy();
strategyCache.put(key, strategy);
} catch (CoreException e) {
throw new IllegalStateException("Failed to create strategy", e);
}
}
return strategy;
}
}
public static class AllocationComputationStrategyConfigurationPage extends PropertyEditorWizardPage {
// inspired by/stolen from de.uni_paderborn.fujaba.muml.verification.uppaal.ui.OptionsWizardPage
private static final String tabId = "de.uni_paderborn.fujaba.muml.allocation.algorithm.ilp.opt4j.config";
private static final String title = "Configuration options for the Opt4j EA";
private static final String description = "Configure the Opt4j evolutionary algorithm";
public AllocationComputationStrategyConfigurationPage() {
super(new ObjectPropertyEditor(tabId, null, "Options", true));
setTitle(title);
setDescription(description);
}
public void setConfiguration(EObject configuration) {
// create dummy resource unless the configuration object is already contained
// in a resource
if (configuration.eResource() == null) {
ResourceSet resSet = new ResourceSetImpl();
Resource resource = resSet.createResource(
URI.createURI("dummy://dummy.ecore"));
resource.getContents().add(configuration);
// just to make APE happy (otherwise APE will not modify the object
// (see de.uni_paderborn.fujaba.properties.runtime.editors.AbstractStructuralFeaturePropertyEditor.setValue))
TransactionalEditingDomain.Factory.INSTANCE.createEditingDomain(resSet);
}
setInput(configuration);
}
}
}
| [Renaming] [Migration] Textual replacement of references to org.muml.ape.runtime.
| plugins/org.muml.psm.allocation.algorithm.ui/src/org/muml/psm/allocation/algorithm/ui/wizard/AllocationWizard.java | [Renaming] [Migration] Textual replacement of references to org.muml.ape.runtime. | <ide><path>lugins/org.muml.psm.allocation.algorithm.ui/src/org/muml/psm/allocation/algorithm/ui/wizard/AllocationWizard.java
<ide> URI.createURI("dummy://dummy.ecore"));
<ide> resource.getContents().add(configuration);
<ide> // just to make APE happy (otherwise APE will not modify the object
<del> // (see de.uni_paderborn.fujaba.properties.runtime.editors.AbstractStructuralFeaturePropertyEditor.setValue))
<add> // (see org.muml.ape.runtime.editors.AbstractStructuralFeaturePropertyEditor.setValue))
<ide> TransactionalEditingDomain.Factory.INSTANCE.createEditingDomain(resSet);
<ide> }
<ide> setInput(configuration); |
|
Java | apache-2.0 | 4fe7966fa957450a1df6e312c714b46b11e4f03c | 0 | apache/tomcat,apache/tomcat,apache/tomcat,apache/tomcat,apache/tomcat | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jasper.compiler;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Map;
import java.util.StringTokenizer;
import org.apache.jasper.Constants;
import org.apache.jasper.JasperException;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.DefaultLogger;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Javac;
import org.apache.tools.ant.types.Path;
import org.apache.tools.ant.types.PatternSet;
/**
* Main JSP compiler class. This class uses Ant for compiling.
*
* @author Anil K. Vijendran
* @author Mandar Raje
* @author Pierre Delisle
* @author Kin-man Chung
* @author Remy Maucherat
* @author Mark Roth
*/
public class AntCompiler extends Compiler {
private final Log log = LogFactory.getLog(AntCompiler.class); // must not be static
protected static final Object javacLock = new Object();
static {
System.setErr(new SystemLogHandler(System.err));
}
// ----------------------------------------------------- Instance Variables
protected Project project = null;
protected JasperAntLogger logger;
// ------------------------------------------------------------ Constructor
// Lazy eval - if we don't need to compile we probably don't need the project
protected Project getProject() {
if (project != null)
return project;
// Initializing project
project = new Project();
logger = new JasperAntLogger();
logger.setOutputPrintStream(System.out);
logger.setErrorPrintStream(System.err);
logger.setMessageOutputLevel(Project.MSG_INFO);
project.addBuildListener( logger);
if (System.getProperty(Constants.CATALINA_HOME_PROP) != null) {
project.setBasedir(System.getProperty(Constants.CATALINA_HOME_PROP));
}
if( options.getCompiler() != null ) {
if( log.isDebugEnabled() )
log.debug("Compiler " + options.getCompiler() );
project.setProperty("build.compiler", options.getCompiler() );
}
project.init();
return project;
}
public static class JasperAntLogger extends DefaultLogger {
protected final StringBuilder reportBuf = new StringBuilder();
@Override
protected void printMessage(final String message,
final PrintStream stream,
final int priority) {
}
@Override
protected void log(String message) {
reportBuf.append(message);
reportBuf.append(System.lineSeparator());
}
protected String getReport() {
String report = reportBuf.toString();
reportBuf.setLength(0);
return report;
}
}
// --------------------------------------------------------- Public Methods
/**
* Compile the servlet from .java file to .class file
*/
@Override
protected void generateClass(Map<String,SmapStratum> smaps)
throws FileNotFoundException, JasperException, Exception {
long t1 = 0;
if (log.isDebugEnabled()) {
t1 = System.currentTimeMillis();
}
String javaEncoding = ctxt.getOptions().getJavaEncoding();
String javaFileName = ctxt.getServletJavaFileName();
String classpath = ctxt.getClassPath();
StringBuilder errorReport = new StringBuilder();
StringBuilder info=new StringBuilder();
info.append("Compile: javaFileName=" + javaFileName + "\n" );
info.append(" classpath=" + classpath + "\n" );
// Start capturing the System.err output for this thread
SystemLogHandler.setThread();
// Initializing javac task
getProject();
Javac javac = (Javac) project.createTask("javac");
// Initializing classpath
Path path = new Path(project);
path.setPath(System.getProperty("java.class.path"));
info.append(" cp=" + System.getProperty("java.class.path") + "\n");
StringTokenizer tokenizer = new StringTokenizer(classpath, File.pathSeparator);
while (tokenizer.hasMoreElements()) {
String pathElement = tokenizer.nextToken();
File repository = new File(pathElement);
path.setLocation(repository);
info.append(" cp=" + repository + "\n");
}
if (log.isDebugEnabled()) {
log.debug( "Using classpath: " + System.getProperty("java.class.path") +
File.pathSeparator + classpath);
}
// Initializing sourcepath
Path srcPath = new Path(project);
srcPath.setLocation(options.getScratchDir());
info.append(" work dir=" + options.getScratchDir() + "\n");
// Initialize and set java extensions
String exts = System.getProperty("java.ext.dirs");
if (exts != null) {
Path extdirs = new Path(project);
extdirs.setPath(exts);
javac.setExtdirs(extdirs);
info.append(" extension dir=" + exts + "\n");
}
// Add endorsed directories if any are specified and we're forking
// See Bugzilla 31257
if(ctxt.getOptions().getFork()) {
String endorsed = System.getProperty("java.endorsed.dirs");
if(endorsed != null) {
Javac.ImplementationSpecificArgument endorsedArg =
javac.createCompilerArg();
endorsedArg.setLine("-J-Djava.endorsed.dirs=" +
quotePathList(endorsed));
info.append(" endorsed dir=" + quotePathList(endorsed) +
"\n");
} else {
info.append(" no endorsed dirs specified\n");
}
}
// Configure the compiler object
javac.setEncoding(javaEncoding);
javac.setClasspath(path);
javac.setDebug(ctxt.getOptions().getClassDebugInfo());
javac.setSrcdir(srcPath);
javac.setTempdir(options.getScratchDir());
javac.setFork(ctxt.getOptions().getFork());
info.append(" srcDir=" + srcPath + "\n" );
// Set the Java compiler to use
if (options.getCompiler() != null) {
javac.setCompiler(options.getCompiler());
info.append(" compiler=" + options.getCompiler() + "\n");
}
if (options.getCompilerTargetVM() != null) {
javac.setTarget(options.getCompilerTargetVM());
info.append(" compilerTargetVM=" + options.getCompilerTargetVM() + "\n");
}
if (options.getCompilerSourceVM() != null) {
javac.setSource(options.getCompilerSourceVM());
info.append(" compilerSourceVM=" + options.getCompilerSourceVM() + "\n");
}
// Build includes path
PatternSet.NameEntry includes = javac.createInclude();
includes.setName(ctxt.getJavaPath());
info.append(" include="+ ctxt.getJavaPath() + "\n" );
BuildException be = null;
try {
if (ctxt.getOptions().getFork()) {
javac.execute();
} else {
synchronized(javacLock) {
javac.execute();
}
}
} catch (BuildException e) {
be = e;
log.error(Localizer.getMessage("jsp.error.javac"), e);
log.error(Localizer.getMessage("jsp.error.javac.env") + info.toString());
}
errorReport.append(logger.getReport());
// Stop capturing the System.err output for this thread
String errorCapture = SystemLogHandler.unsetThread();
if (errorCapture != null) {
errorReport.append(System.lineSeparator());
errorReport.append(errorCapture);
}
if (!ctxt.keepGenerated()) {
File javaFile = new File(javaFileName);
if (!javaFile.delete()) {
throw new JasperException(Localizer.getMessage(
"jsp.warning.compiler.javafile.delete.fail", javaFile));
}
}
if (be != null) {
String errorReportString = errorReport.toString();
log.error(Localizer.getMessage("jsp.error.compilation", javaFileName, errorReportString));
JavacErrorDetail[] javacErrors = ErrorDispatcher.parseJavacErrors(
errorReportString, javaFileName, pageNodes);
if (javacErrors != null) {
errDispatcher.javacError(javacErrors);
} else {
errDispatcher.javacError(errorReportString, be);
}
}
if( log.isDebugEnabled() ) {
long t2 = System.currentTimeMillis();
log.debug("Compiled " + ctxt.getServletJavaFileName() + " "
+ (t2-t1) + "ms");
}
logger = null;
project = null;
if (ctxt.isPrototypeMode()) {
return;
}
// JSR45 Support
if (!options.isSmapSuppressed()) {
SmapUtil.installSmap(smaps);
}
}
private String quotePathList(String list) {
StringBuilder result = new StringBuilder(list.length() + 10);
StringTokenizer st = new StringTokenizer(list, File.pathSeparator);
while (st.hasMoreTokens()) {
String token = st.nextToken();
if (token.indexOf(' ') == -1) {
result.append(token);
} else {
result.append('\"');
result.append(token);
result.append('\"');
}
if (st.hasMoreTokens()) {
result.append(File.pathSeparatorChar);
}
}
return result.toString();
}
protected static class SystemLogHandler extends PrintStream {
// ----------------------------------------------------------- Constructors
/**
* Construct the handler to capture the output of the given steam.
* @param wrapped The wrapped stream
*/
public SystemLogHandler(PrintStream wrapped) {
super(wrapped);
this.wrapped = wrapped;
}
// ----------------------------------------------------- Instance Variables
/**
* Wrapped PrintStream.
*/
protected final PrintStream wrapped;
/**
* Thread <-> PrintStream associations.
*/
protected static final ThreadLocal<PrintStream> streams =
new ThreadLocal<>();
/**
* Thread <-> ByteArrayOutputStream associations.
*/
protected static final ThreadLocal<ByteArrayOutputStream> data =
new ThreadLocal<>();
// --------------------------------------------------------- Public Methods
/**
* Start capturing thread's output.
*/
public static void setThread() {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
data.set(baos);
streams.set(new PrintStream(baos));
}
/**
* Stop capturing thread's output and return captured data as a String.
* @return the captured output
*/
public static String unsetThread() {
ByteArrayOutputStream baos = data.get();
if (baos == null) {
return null;
}
streams.set(null);
data.set(null);
return baos.toString();
}
// ------------------------------------------------------ Protected Methods
/**
* Find PrintStream to which the output must be written to.
* @return the current stream
*/
protected PrintStream findStream() {
PrintStream ps = streams.get();
if (ps == null) {
ps = wrapped;
}
return ps;
}
// ---------------------------------------------------- PrintStream Methods
@Override
public void flush() {
findStream().flush();
}
@Override
public void close() {
findStream().close();
}
@Override
public boolean checkError() {
return findStream().checkError();
}
@Override
protected void setError() {
//findStream().setError();
}
@Override
public void write(int b) {
findStream().write(b);
}
@Override
public void write(byte[] b)
throws IOException {
findStream().write(b);
}
@Override
public void write(byte[] buf, int off, int len) {
findStream().write(buf, off, len);
}
@Override
public void print(boolean b) {
findStream().print(b);
}
@Override
public void print(char c) {
findStream().print(c);
}
@Override
public void print(int i) {
findStream().print(i);
}
@Override
public void print(long l) {
findStream().print(l);
}
@Override
public void print(float f) {
findStream().print(f);
}
@Override
public void print(double d) {
findStream().print(d);
}
@Override
public void print(char[] s) {
findStream().print(s);
}
@Override
public void print(String s) {
findStream().print(s);
}
@Override
public void print(Object obj) {
findStream().print(obj);
}
@Override
public void println() {
findStream().println();
}
@Override
public void println(boolean x) {
findStream().println(x);
}
@Override
public void println(char x) {
findStream().println(x);
}
@Override
public void println(int x) {
findStream().println(x);
}
@Override
public void println(long x) {
findStream().println(x);
}
@Override
public void println(float x) {
findStream().println(x);
}
@Override
public void println(double x) {
findStream().println(x);
}
@Override
public void println(char[] x) {
findStream().println(x);
}
@Override
public void println(String x) {
findStream().println(x);
}
@Override
public void println(Object x) {
findStream().println(x);
}
}
}
| java/org/apache/jasper/compiler/AntCompiler.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jasper.compiler;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Map;
import java.util.StringTokenizer;
import org.apache.jasper.Constants;
import org.apache.jasper.JasperException;
import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.DefaultLogger;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Javac;
import org.apache.tools.ant.types.Path;
import org.apache.tools.ant.types.PatternSet;
/**
* Main JSP compiler class. This class uses Ant for compiling.
*
* @author Anil K. Vijendran
* @author Mandar Raje
* @author Pierre Delisle
* @author Kin-man Chung
* @author Remy Maucherat
* @author Mark Roth
*/
public class AntCompiler extends Compiler {
private final Log log = LogFactory.getLog(AntCompiler.class); // must not be static
protected static final Object javacLock = new Object();
static {
System.setErr(new SystemLogHandler(System.err));
}
// ----------------------------------------------------- Instance Variables
protected Project project = null;
protected JasperAntLogger logger;
// ------------------------------------------------------------ Constructor
// Lazy eval - if we don't need to compile we probably don't need the project
protected Project getProject() {
if (project != null)
return project;
// Initializing project
project = new Project();
logger = new JasperAntLogger();
logger.setOutputPrintStream(System.out);
logger.setErrorPrintStream(System.err);
logger.setMessageOutputLevel(Project.MSG_INFO);
project.addBuildListener( logger);
if (System.getProperty(Constants.CATALINA_HOME_PROP) != null) {
project.setBasedir(System.getProperty(Constants.CATALINA_HOME_PROP));
}
if( options.getCompiler() != null ) {
if( log.isDebugEnabled() )
log.debug("Compiler " + options.getCompiler() );
project.setProperty("build.compiler", options.getCompiler() );
}
project.init();
return project;
}
public static class JasperAntLogger extends DefaultLogger {
protected final StringBuilder reportBuf = new StringBuilder();
@Override
protected void printMessage(final String message,
final PrintStream stream,
final int priority) {
}
@Override
protected void log(String message) {
reportBuf.append(message);
reportBuf.append(System.lineSeparator());
}
protected String getReport() {
String report = reportBuf.toString();
reportBuf.setLength(0);
return report;
}
}
// --------------------------------------------------------- Public Methods
/**
* Compile the servlet from .java file to .class file
*/
@Override
protected void generateClass(Map<String,SmapStratum> smaps)
throws FileNotFoundException, JasperException, Exception {
long t1 = 0;
if (log.isDebugEnabled()) {
t1 = System.currentTimeMillis();
}
String javaEncoding = ctxt.getOptions().getJavaEncoding();
String javaFileName = ctxt.getServletJavaFileName();
String classpath = ctxt.getClassPath();
StringBuilder errorReport = new StringBuilder();
StringBuilder info=new StringBuilder();
info.append("Compile: javaFileName=" + javaFileName + "\n" );
info.append(" classpath=" + classpath + "\n" );
// Start capturing the System.err output for this thread
SystemLogHandler.setThread();
// Initializing javac task
getProject();
Javac javac = (Javac) project.createTask("javac");
// Initializing classpath
Path path = new Path(project);
path.setPath(System.getProperty("java.class.path"));
info.append(" cp=" + System.getProperty("java.class.path") + "\n");
StringTokenizer tokenizer = new StringTokenizer(classpath, File.pathSeparator);
while (tokenizer.hasMoreElements()) {
String pathElement = tokenizer.nextToken();
File repository = new File(pathElement);
path.setLocation(repository);
info.append(" cp=" + repository + "\n");
}
if (log.isDebugEnabled()) {
log.debug( "Using classpath: " + System.getProperty("java.class.path") +
File.pathSeparator + classpath);
}
// Initializing sourcepath
Path srcPath = new Path(project);
srcPath.setLocation(options.getScratchDir());
info.append(" work dir=" + options.getScratchDir() + "\n");
// Initialize and set java extensions
String exts = System.getProperty("java.ext.dirs");
if (exts != null) {
Path extdirs = new Path(project);
extdirs.setPath(exts);
javac.setExtdirs(extdirs);
info.append(" extension dir=" + exts + "\n");
}
// Add endorsed directories if any are specified and we're forking
// See Bugzilla 31257
if(ctxt.getOptions().getFork()) {
String endorsed = System.getProperty("java.endorsed.dirs");
if(endorsed != null) {
Javac.ImplementationSpecificArgument endorsedArg =
javac.createCompilerArg();
endorsedArg.setLine("-J-Djava.endorsed.dirs=" +
quotePathList(endorsed));
info.append(" endorsed dir=" + quotePathList(endorsed) +
"\n");
} else {
info.append(" no endorsed dirs specified\n");
}
}
// Configure the compiler object
javac.setEncoding(javaEncoding);
javac.setClasspath(path);
javac.setDebug(ctxt.getOptions().getClassDebugInfo());
javac.setSrcdir(srcPath);
javac.setTempdir(options.getScratchDir());
javac.setOptimize(! ctxt.getOptions().getClassDebugInfo() );
javac.setFork(ctxt.getOptions().getFork());
info.append(" srcDir=" + srcPath + "\n" );
// Set the Java compiler to use
if (options.getCompiler() != null) {
javac.setCompiler(options.getCompiler());
info.append(" compiler=" + options.getCompiler() + "\n");
}
if (options.getCompilerTargetVM() != null) {
javac.setTarget(options.getCompilerTargetVM());
info.append(" compilerTargetVM=" + options.getCompilerTargetVM() + "\n");
}
if (options.getCompilerSourceVM() != null) {
javac.setSource(options.getCompilerSourceVM());
info.append(" compilerSourceVM=" + options.getCompilerSourceVM() + "\n");
}
// Build includes path
PatternSet.NameEntry includes = javac.createInclude();
includes.setName(ctxt.getJavaPath());
info.append(" include="+ ctxt.getJavaPath() + "\n" );
BuildException be = null;
try {
if (ctxt.getOptions().getFork()) {
javac.execute();
} else {
synchronized(javacLock) {
javac.execute();
}
}
} catch (BuildException e) {
be = e;
log.error(Localizer.getMessage("jsp.error.javac"), e);
log.error(Localizer.getMessage("jsp.error.javac.env") + info.toString());
}
errorReport.append(logger.getReport());
// Stop capturing the System.err output for this thread
String errorCapture = SystemLogHandler.unsetThread();
if (errorCapture != null) {
errorReport.append(System.lineSeparator());
errorReport.append(errorCapture);
}
if (!ctxt.keepGenerated()) {
File javaFile = new File(javaFileName);
if (!javaFile.delete()) {
throw new JasperException(Localizer.getMessage(
"jsp.warning.compiler.javafile.delete.fail", javaFile));
}
}
if (be != null) {
String errorReportString = errorReport.toString();
log.error(Localizer.getMessage("jsp.error.compilation", javaFileName, errorReportString));
JavacErrorDetail[] javacErrors = ErrorDispatcher.parseJavacErrors(
errorReportString, javaFileName, pageNodes);
if (javacErrors != null) {
errDispatcher.javacError(javacErrors);
} else {
errDispatcher.javacError(errorReportString, be);
}
}
if( log.isDebugEnabled() ) {
long t2 = System.currentTimeMillis();
log.debug("Compiled " + ctxt.getServletJavaFileName() + " "
+ (t2-t1) + "ms");
}
logger = null;
project = null;
if (ctxt.isPrototypeMode()) {
return;
}
// JSR45 Support
if (!options.isSmapSuppressed()) {
SmapUtil.installSmap(smaps);
}
}
private String quotePathList(String list) {
StringBuilder result = new StringBuilder(list.length() + 10);
StringTokenizer st = new StringTokenizer(list, File.pathSeparator);
while (st.hasMoreTokens()) {
String token = st.nextToken();
if (token.indexOf(' ') == -1) {
result.append(token);
} else {
result.append('\"');
result.append(token);
result.append('\"');
}
if (st.hasMoreTokens()) {
result.append(File.pathSeparatorChar);
}
}
return result.toString();
}
protected static class SystemLogHandler extends PrintStream {
// ----------------------------------------------------------- Constructors
/**
* Construct the handler to capture the output of the given steam.
* @param wrapped The wrapped stream
*/
public SystemLogHandler(PrintStream wrapped) {
super(wrapped);
this.wrapped = wrapped;
}
// ----------------------------------------------------- Instance Variables
/**
* Wrapped PrintStream.
*/
protected final PrintStream wrapped;
/**
* Thread <-> PrintStream associations.
*/
protected static final ThreadLocal<PrintStream> streams =
new ThreadLocal<>();
/**
* Thread <-> ByteArrayOutputStream associations.
*/
protected static final ThreadLocal<ByteArrayOutputStream> data =
new ThreadLocal<>();
// --------------------------------------------------------- Public Methods
/**
* Start capturing thread's output.
*/
public static void setThread() {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
data.set(baos);
streams.set(new PrintStream(baos));
}
/**
* Stop capturing thread's output and return captured data as a String.
* @return the captured output
*/
public static String unsetThread() {
ByteArrayOutputStream baos = data.get();
if (baos == null) {
return null;
}
streams.set(null);
data.set(null);
return baos.toString();
}
// ------------------------------------------------------ Protected Methods
/**
* Find PrintStream to which the output must be written to.
* @return the current stream
*/
protected PrintStream findStream() {
PrintStream ps = streams.get();
if (ps == null) {
ps = wrapped;
}
return ps;
}
// ---------------------------------------------------- PrintStream Methods
@Override
public void flush() {
findStream().flush();
}
@Override
public void close() {
findStream().close();
}
@Override
public boolean checkError() {
return findStream().checkError();
}
@Override
protected void setError() {
//findStream().setError();
}
@Override
public void write(int b) {
findStream().write(b);
}
@Override
public void write(byte[] b)
throws IOException {
findStream().write(b);
}
@Override
public void write(byte[] buf, int off, int len) {
findStream().write(buf, off, len);
}
@Override
public void print(boolean b) {
findStream().print(b);
}
@Override
public void print(char c) {
findStream().print(c);
}
@Override
public void print(int i) {
findStream().print(i);
}
@Override
public void print(long l) {
findStream().print(l);
}
@Override
public void print(float f) {
findStream().print(f);
}
@Override
public void print(double d) {
findStream().print(d);
}
@Override
public void print(char[] s) {
findStream().print(s);
}
@Override
public void print(String s) {
findStream().print(s);
}
@Override
public void print(Object obj) {
findStream().print(obj);
}
@Override
public void println() {
findStream().println();
}
@Override
public void println(boolean x) {
findStream().println(x);
}
@Override
public void println(char x) {
findStream().println(x);
}
@Override
public void println(int x) {
findStream().println(x);
}
@Override
public void println(long x) {
findStream().println(x);
}
@Override
public void println(float x) {
findStream().println(x);
}
@Override
public void println(double x) {
findStream().println(x);
}
@Override
public void println(char[] x) {
findStream().println(x);
}
@Override
public void println(String x) {
findStream().println(x);
}
@Override
public void println(Object x) {
findStream().println(x);
}
}
}
| No longer set the 'optimize' option when compiling the JSPs with Ant (ignored since Java 1.3)
git-svn-id: 79cef5a5a257cc9dbe40a45ac190115b4780e2d0@1828385 13f79535-47bb-0310-9956-ffa450edef68
| java/org/apache/jasper/compiler/AntCompiler.java | No longer set the 'optimize' option when compiling the JSPs with Ant (ignored since Java 1.3) | <ide><path>ava/org/apache/jasper/compiler/AntCompiler.java
<ide> javac.setDebug(ctxt.getOptions().getClassDebugInfo());
<ide> javac.setSrcdir(srcPath);
<ide> javac.setTempdir(options.getScratchDir());
<del> javac.setOptimize(! ctxt.getOptions().getClassDebugInfo() );
<ide> javac.setFork(ctxt.getOptions().getFork());
<ide> info.append(" srcDir=" + srcPath + "\n" );
<ide> |
|
Java | apache-2.0 | c5d632704f3d4306e0381d8d81e0e32670c2088e | 0 | jwillia/kc-rice1,UniversityOfHawaiiORS/rice,smith750/rice,ewestfal/rice,cniesen/rice,shahess/rice,jwillia/kc-rice1,shahess/rice,gathreya/rice-kc,bsmith83/rice-1,ewestfal/rice,ewestfal/rice-svn2git-test,bhutchinson/rice,kuali/kc-rice,geothomasp/kualico-rice-kc,sonamuthu/rice-1,UniversityOfHawaiiORS/rice,smith750/rice,smith750/rice,ewestfal/rice,ewestfal/rice,sonamuthu/rice-1,kuali/kc-rice,rojlarge/rice-kc,bhutchinson/rice,UniversityOfHawaiiORS/rice,bsmith83/rice-1,geothomasp/kualico-rice-kc,kuali/kc-rice,gathreya/rice-kc,bsmith83/rice-1,jwillia/kc-rice1,jwillia/kc-rice1,ewestfal/rice,kuali/kc-rice,shahess/rice,UniversityOfHawaiiORS/rice,bhutchinson/rice,geothomasp/kualico-rice-kc,gathreya/rice-kc,rojlarge/rice-kc,cniesen/rice,cniesen/rice,kuali/kc-rice,jwillia/kc-rice1,geothomasp/kualico-rice-kc,ewestfal/rice-svn2git-test,ewestfal/rice-svn2git-test,rojlarge/rice-kc,shahess/rice,bhutchinson/rice,bsmith83/rice-1,gathreya/rice-kc,gathreya/rice-kc,ewestfal/rice-svn2git-test,geothomasp/kualico-rice-kc,sonamuthu/rice-1,cniesen/rice,shahess/rice,UniversityOfHawaiiORS/rice,smith750/rice,rojlarge/rice-kc,rojlarge/rice-kc,sonamuthu/rice-1,bhutchinson/rice,cniesen/rice,smith750/rice | /*
* Copyright 2007 The Kuali Foundation
*
* Licensed under the Educational Community License, Version 1.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl1.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.rice.core.jpa.criteria;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.persistence.Query;
import org.kuali.rice.core.jpa.criteria.QueryByCriteria.QueryByCriteriaType;
/**
* A criteria builder for JPQL Query objects.
*
* TODO: Rewrite this class with a better criteria building algorithm.
*
* @author Kuali Rice Team ([email protected])
*/
@SuppressWarnings("unchecked")
public class Criteria {
private Integer searchLimit;
private String entityName;
private String alias;
private int bindParamCount;
protected List tokens = new ArrayList();
private List orderByTokens = new ArrayList();
protected Map<String, Object> params = new LinkedHashMap<String, Object>();
public Criteria(String entityName) {
this(entityName, "a");
}
public Criteria(String entityName, String alias) {
this.entityName = entityName;
this.alias = alias;
}
public void between(String attribute, Object value1, Object value2) {
tokens.add(" (" + alias + "." + attribute + " BETWEEN :" + attribute + "-b1 AND :" + attribute + "-b2) ");
params.put(attribute, value1);
params.put(attribute, value2);
}
public void eq(String attribute, Object value) {
tokens.add(alias + "." + attribute + " = :" + attribute + " ");
params.put(attribute, value);
}
public void gt(String attribute, Object value) {
tokens.add(alias + "." + attribute + " > :" + attribute + " ");
params.put(attribute, value);
}
public void gte(String attribute, Object value) {
tokens.add(alias + "." + attribute + " >= :" + attribute + " ");
params.put(attribute, value);
}
public void like(String attribute, Object value) {
if (attribute.contains("__JPA_ALIAS__")) {
String bind = "BIND_PARAM_" + (++bindParamCount);
tokens.add(attribute + " LIKE :" + bind + " ");
params.put(bind, value);
} else {
tokens.add(alias + "." + attribute + " LIKE :" + attribute + " ");
params.put(attribute, value);
}
}
public void notLike(String attribute, Object value) {
tokens.add(alias + "." + attribute + " NOT LIKE :" + attribute + " ");
params.put(attribute, value);
}
public void lt(String attribute, Object value) {
tokens.add(alias + "." + attribute + " < :" + attribute + " ");
params.put(attribute, value);
}
public void lte(String attribute, Object value) {
tokens.add(alias + "." + attribute + " <= :" + attribute + " ");
params.put(attribute, value);
}
public void ne(String attribute, Object value) {
tokens.add(alias + "." + attribute + " != :" + attribute + " ");
params.put(attribute, value);
}
public void isNull(String attribute) {
tokens.add(alias + "." + attribute + " IS NULL ");
}
public void rawJpql(String jpql) {
tokens.add(" " + jpql + " ");
}
public void in(String attribute, List values) {
String in = "";
for (Object object : values) {
in += object + ",";
}
if (!"".equals(in)) {
in = in.substring(0, in.length()-1);
}
tokens.add(alias + "." + attribute + " IN (" + in + ") ");
}
public void notIn(String attribute, List values) {
String in = "";
for (Object object : values) {
in += object + ",";
}
if (!"".equals(in)) {
in = in.substring(in.length()-1);
}
tokens.add(alias + "." + attribute + " NOT IN (" + in + ") ");
}
public void orderBy(String attribute, boolean sortAscending) {
String sort = (sortAscending ? "ASC" : "DESC");
orderByTokens.add(alias + "." + attribute + " " + sort + " ");
}
public void and(Criteria and) {
tokens.add(new AndCriteria(and));
}
public void or(Criteria or) {
tokens.add(new OrCriteria(or));
}
public String toQuery(QueryByCriteriaType type) {
String queryType = type.toString();
if (type.equals(QueryByCriteriaType.SELECT)) {
queryType += " " + alias;
}
String queryString = queryType + " FROM " + entityName + " AS " + alias;
if (!tokens.isEmpty()) {
queryString += " WHERE " + buildWhere();
}
if (!orderByTokens.isEmpty()) {
queryString += " ORDER BY ";
int count = 0;
for (Iterator iterator = orderByTokens.iterator(); iterator.hasNext();) {
Object token = (Object) iterator.next();
if (count == 0) {
count++;
} else {
queryString += ", ";
}
queryString += (String) token;
}
}
return fix(queryString);
}
public String toCountQuery() {
String queryString = "SELECT COUNT(*) FROM " + entityName + " AS " + alias;
if (!tokens.isEmpty()) {
queryString += " WHERE " + buildWhere();
}
return fix(queryString);
}
private String fix(String queryString) {
queryString = queryString.replaceAll("__JPA_ALIAS__", alias);
return queryString;
}
private String buildWhere() {
String queryString = "";
int i = 0;
for (Iterator iterator = tokens.iterator(); iterator.hasNext();) {
Object token = (Object) iterator.next();
if (token instanceof Criteria) {
String logic = "";
if (i>0 && token instanceof AndCriteria) {
logic = " AND ";
} else if (i>0 && token instanceof OrCriteria) {
logic = " OR ";
}
queryString += logic + " (" + ((Criteria) token).buildWhere() + ") ";
} else {
if(i>0){
queryString += " AND " + (String) token;
}else{
queryString += (String) token;
}
}
i++;
}
return queryString;
}
// Keep this package access so the QueryByCriteria can call it from this package.
void prepareParameters(Query query) {
prepareParameters(query, tokens, params);
}
void prepareParameters(Query query, List tokens, Map<String, Object> params) {
for (Map.Entry<String, Object> param : params.entrySet()) {
Object value = param.getValue();
if (value instanceof BigDecimal) {
value = new Long(((BigDecimal)value).longValue());
}
if (value instanceof String) {
value = ((String)value).replaceAll("\\*", "%");
}
query.setParameter(param.getKey(), value);
}
for (Iterator iterator = tokens.iterator(); iterator.hasNext();) {
Object token = (Object) iterator.next();
if (token instanceof Criteria) {
prepareParameters(query, ((Criteria)token).tokens, ((Criteria)token).params);
}
}
}
private class AndCriteria extends Criteria {
public AndCriteria(Criteria and) {
super(and.entityName, and.alias);
this.tokens = new ArrayList(and.tokens);
this.params = new HashMap(and.params);
}
}
private class OrCriteria extends Criteria {
public OrCriteria(Criteria or) {
super(or.entityName, or.alias);
this.tokens = new ArrayList(or.tokens);
this.params = new HashMap(or.params);
}
}
public Integer getSearchLimit() {
return this.searchLimit;
}
public void setSearchLimit(Integer searchLimit) {
this.searchLimit = searchLimit;
}
public void notNull(String attribute) {
tokens.add(alias + "." + attribute + " IS NOT NULL ");
}
/**
* This method ...
*
* @param string
* @param timestamp
* @param timestamp2
*/
public void notBetween(String attribute, Object value1,
Object value2) {
tokens.add(" (" + alias + "." + attribute + " NOT BETWEEN :" + attribute + "-b1 AND :" + attribute + "-b2) ");
params.put(attribute, value1);
params.put(attribute, value2);
}
}
| impl/src/main/java/org/kuali/rice/core/jpa/criteria/Criteria.java | /*
* Copyright 2007 The Kuali Foundation
*
* Licensed under the Educational Community License, Version 1.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl1.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.rice.core.jpa.criteria;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.persistence.Query;
import org.kuali.rice.core.jpa.criteria.QueryByCriteria.QueryByCriteriaType;
/**
* A criteria builder for JPQL Query objects.
*
* TODO: Rewrite this class with a better criteria building algorithm.
*
* @author Kuali Rice Team ([email protected])
*/
@SuppressWarnings("unchecked")
public class Criteria {
private Integer searchLimit;
private String entityName;
private String alias;
private int bindParamCount;
private List tokens = new ArrayList();
private List orderByTokens = new ArrayList();
private Map<String, Object> params = new LinkedHashMap<String, Object>();
public Criteria(String entityName) {
this(entityName, "a");
}
public Criteria(String entityName, String alias) {
this.entityName = entityName;
this.alias = alias;
}
public void between(String attribute, Object value1, Object value2) {
tokens.add(" (" + alias + "." + attribute + " BETWEEN :" + attribute + "-b1 AND :" + attribute + "-b2) ");
params.put(attribute, value1);
params.put(attribute, value2);
}
public void eq(String attribute, Object value) {
tokens.add(alias + "." + attribute + " = :" + attribute + " ");
params.put(attribute, value);
}
public void gt(String attribute, Object value) {
tokens.add(alias + "." + attribute + " > :" + attribute + " ");
params.put(attribute, value);
}
public void gte(String attribute, Object value) {
tokens.add(alias + "." + attribute + " >= :" + attribute + " ");
params.put(attribute, value);
}
public void like(String attribute, Object value) {
if (attribute.contains("__JPA_ALIAS__")) {
String bind = "BIND_PARAM_" + (++bindParamCount);
tokens.add(attribute + " LIKE :" + bind + " ");
params.put(bind, value);
} else {
tokens.add(alias + "." + attribute + " LIKE :" + attribute + " ");
params.put(attribute, value);
}
}
public void notLike(String attribute, Object value) {
tokens.add(alias + "." + attribute + " NOT LIKE :" + attribute + " ");
params.put(attribute, value);
}
public void lt(String attribute, Object value) {
tokens.add(alias + "." + attribute + " < :" + attribute + " ");
params.put(attribute, value);
}
public void lte(String attribute, Object value) {
tokens.add(alias + "." + attribute + " <= :" + attribute + " ");
params.put(attribute, value);
}
public void ne(String attribute, Object value) {
tokens.add(alias + "." + attribute + " != :" + attribute + " ");
params.put(attribute, value);
}
public void isNull(String attribute) {
tokens.add(alias + "." + attribute + " IS NULL ");
}
public void rawJpql(String jpql) {
tokens.add(" " + jpql + " ");
}
public void in(String attribute, List values) {
String in = "";
for (Object object : values) {
in += object + ",";
}
if (!"".equals(in)) {
in = in.substring(0, in.length()-1);
}
tokens.add(alias + "." + attribute + " IN (" + in + ") ");
}
public void notIn(String attribute, List values) {
String in = "";
for (Object object : values) {
in += object + ",";
}
if (!"".equals(in)) {
in = in.substring(in.length()-1);
}
tokens.add(alias + "." + attribute + " NOT IN (" + in + ") ");
}
public void orderBy(String attribute, boolean sortAscending) {
String sort = (sortAscending ? "ASC" : "DESC");
orderByTokens.add(alias + "." + attribute + " " + sort + " ");
}
public void and(Criteria and) {
tokens.add(new AndCriteria(and));
}
public void or(Criteria or) {
tokens.add(new OrCriteria(or));
}
public String toQuery(QueryByCriteriaType type) {
String queryType = type.toString();
if (type.equals(QueryByCriteriaType.SELECT)) {
queryType += " " + alias;
}
String queryString = queryType + " FROM " + entityName + " AS " + alias;
if (!tokens.isEmpty()) {
queryString += " WHERE 1 = 1 " + buildWhere();
}
if (!orderByTokens.isEmpty()) {
queryString += " ORDER BY ";
int count = 0;
for (Iterator iterator = orderByTokens.iterator(); iterator.hasNext();) {
Object token = (Object) iterator.next();
if (count == 0) {
count++;
} else {
queryString += ", ";
}
queryString += (String) token;
}
}
return fix(queryString);
}
public String toCountQuery() {
String queryString = "SELECT COUNT(*) FROM " + entityName + " AS " + alias;
if (!tokens.isEmpty()) {
queryString += " WHERE 1 = 1 " + buildWhere();
}
return fix(queryString);
}
private String fix(String queryString) {
queryString = queryString.replaceAll("__JPA_ALIAS__", alias);
return queryString;
}
private String buildWhere() {
String queryString = "";
for (Iterator iterator = tokens.iterator(); iterator.hasNext();) {
Object token = (Object) iterator.next();
if (token instanceof Criteria) {
String logic = null;
if (token instanceof AndCriteria) {
logic = " AND ";
} else if (token instanceof OrCriteria) {
logic = " OR ";
}
queryString += logic + " (" + ((Criteria) token).buildWhere() + ") ";
} else {
queryString += " AND " + (String) token;
}
}
return queryString;
}
// Keep this package access so the QueryByCriteria can call it from this package.
void prepareParameters(Query query) {
for (Map.Entry<String, Object> param : params.entrySet()) {
Object value = param.getValue();
if (value instanceof BigDecimal) {
value = new Long(((BigDecimal)value).longValue());
}
if (value instanceof String) {
value = ((String)value).replaceAll("\\*", "%");
}
query.setParameter(param.getKey(), value);
}
for (Iterator iterator = tokens.iterator(); iterator.hasNext();) {
Object token = (Object) iterator.next();
if (token instanceof Criteria) {
prepareParameters(query);
}
}
}
private class AndCriteria extends Criteria {
public AndCriteria(Criteria and) {
super(and.entityName, and.alias);
}
}
private class OrCriteria extends Criteria {
public OrCriteria(Criteria or) {
super(or.entityName, or.alias);
}
}
public Integer getSearchLimit() {
return this.searchLimit;
}
public void setSearchLimit(Integer searchLimit) {
this.searchLimit = searchLimit;
}
}
| Added some logic methods, fixed ANDs and ORs appearing as prefixes for single expressions, fixed endless recursion for parameter binding when token is a criteria.
| impl/src/main/java/org/kuali/rice/core/jpa/criteria/Criteria.java | Added some logic methods, fixed ANDs and ORs appearing as prefixes for single expressions, fixed endless recursion for parameter binding when token is a criteria. | <ide><path>mpl/src/main/java/org/kuali/rice/core/jpa/criteria/Criteria.java
<ide>
<ide> import java.math.BigDecimal;
<ide> import java.util.ArrayList;
<add>import java.util.HashMap;
<ide> import java.util.Iterator;
<ide> import java.util.LinkedHashMap;
<ide> import java.util.List;
<ide>
<ide> private int bindParamCount;
<ide>
<del> private List tokens = new ArrayList();
<add> protected List tokens = new ArrayList();
<ide>
<ide> private List orderByTokens = new ArrayList();
<ide>
<del> private Map<String, Object> params = new LinkedHashMap<String, Object>();
<add> protected Map<String, Object> params = new LinkedHashMap<String, Object>();
<ide>
<ide> public Criteria(String entityName) {
<ide> this(entityName, "a");
<ide> }
<ide> String queryString = queryType + " FROM " + entityName + " AS " + alias;
<ide> if (!tokens.isEmpty()) {
<del> queryString += " WHERE 1 = 1 " + buildWhere();
<add> queryString += " WHERE " + buildWhere();
<ide> }
<ide> if (!orderByTokens.isEmpty()) {
<ide> queryString += " ORDER BY ";
<ide> public String toCountQuery() {
<ide> String queryString = "SELECT COUNT(*) FROM " + entityName + " AS " + alias;
<ide> if (!tokens.isEmpty()) {
<del> queryString += " WHERE 1 = 1 " + buildWhere();
<add> queryString += " WHERE " + buildWhere();
<ide> }
<ide> return fix(queryString);
<ide> }
<ide>
<ide> private String buildWhere() {
<ide> String queryString = "";
<add> int i = 0;
<ide> for (Iterator iterator = tokens.iterator(); iterator.hasNext();) {
<ide> Object token = (Object) iterator.next();
<ide> if (token instanceof Criteria) {
<del> String logic = null;
<del> if (token instanceof AndCriteria) {
<add> String logic = "";
<add> if (i>0 && token instanceof AndCriteria) {
<ide> logic = " AND ";
<del> } else if (token instanceof OrCriteria) {
<add> } else if (i>0 && token instanceof OrCriteria) {
<ide> logic = " OR ";
<ide> }
<ide> queryString += logic + " (" + ((Criteria) token).buildWhere() + ") ";
<ide> } else {
<del> queryString += " AND " + (String) token;
<del> }
<add> if(i>0){
<add> queryString += " AND " + (String) token;
<add> }else{
<add> queryString += (String) token;
<add> }
<add> }
<add> i++;
<ide> }
<ide> return queryString;
<ide> }
<ide>
<ide> // Keep this package access so the QueryByCriteria can call it from this package.
<ide> void prepareParameters(Query query) {
<add> prepareParameters(query, tokens, params);
<add> }
<add>
<add> void prepareParameters(Query query, List tokens, Map<String, Object> params) {
<ide> for (Map.Entry<String, Object> param : params.entrySet()) {
<ide> Object value = param.getValue();
<ide> if (value instanceof BigDecimal) {
<ide> for (Iterator iterator = tokens.iterator(); iterator.hasNext();) {
<ide> Object token = (Object) iterator.next();
<ide> if (token instanceof Criteria) {
<del> prepareParameters(query);
<add> prepareParameters(query, ((Criteria)token).tokens, ((Criteria)token).params);
<ide> }
<ide> }
<ide> }
<ide> private class AndCriteria extends Criteria {
<ide> public AndCriteria(Criteria and) {
<ide> super(and.entityName, and.alias);
<add> this.tokens = new ArrayList(and.tokens);
<add> this.params = new HashMap(and.params);
<ide> }
<ide> }
<ide>
<ide> private class OrCriteria extends Criteria {
<ide> public OrCriteria(Criteria or) {
<ide> super(or.entityName, or.alias);
<add> this.tokens = new ArrayList(or.tokens);
<add> this.params = new HashMap(or.params);
<ide> }
<ide> }
<ide>
<ide> public void setSearchLimit(Integer searchLimit) {
<ide> this.searchLimit = searchLimit;
<ide> }
<add>
<add>
<add> public void notNull(String attribute) {
<add> tokens.add(alias + "." + attribute + " IS NOT NULL ");
<add> }
<add>
<add> /**
<add> * This method ...
<add> *
<add> * @param string
<add> * @param timestamp
<add> * @param timestamp2
<add> */
<add> public void notBetween(String attribute, Object value1,
<add> Object value2) {
<add> tokens.add(" (" + alias + "." + attribute + " NOT BETWEEN :" + attribute + "-b1 AND :" + attribute + "-b2) ");
<add> params.put(attribute, value1);
<add> params.put(attribute, value2);
<add> }
<ide> } |
|
JavaScript | apache-2.0 | e01db54b893255b22907fb2a154b8c9851e06147 | 0 | jclark118/mage-server,newmanw/mage-server,newmanw/mage-server,ngageoint/mage-server,jclark118/mage-server,ngageoint/mage-server,ngageoint/mage-server,newmanw/mage-server,jclark118/mage-server,ngageoint/mage-server | var mongoose = require('mongoose')
, async = require('async')
, moment = require('moment')
, Layer = require('../models/layer');
var Schema = mongoose.Schema;
var StateSchema = new Schema({
name: { type: String, required: true },
userId: { type: Schema.Types.ObjectId, ref: 'User' }
});
var AttachmentSchema = new Schema({
lastModified: {type: Date, required: false},
contentType: { type: String, required: false },
size: { type: Number, required: false },
name: { type: String, required: false },
relativePath: { type: String, required: true },
width: { type: Number, required: false },
height: { type: Number, required: false },
oriented: {type: Boolean, required: true, default: false },
thumbnails: [ThumbnailSchema]
},{
strict: false
});
var ThumbnailSchema = new Schema({
contentType: { type: String, required: false },
size: { type: Number, required: false },
name: { type: String, required: false },
relativePath: { type: String, required: true },
minDimension: { type: Number, required: true },
width: { type: Number, required: false },
height: { type: Number, required: false}
},{
strict: false
});
// Creates the Schema for the Attachments object
var FeatureSchema = new Schema({
type: {type: String, required: true},
lastModified: {type: Date, required: false},
userId: {type: Schema.Types.ObjectId, required: false, sparse: true},
deviceId: {type: Schema.Types.ObjectId, required: false, sparse: true},
geometry: Schema.Types.Mixed,
properties: Schema.Types.Mixed,
attachments: [AttachmentSchema],
states: [StateSchema]
},{
strict: false
});
FeatureSchema.index({geometry: "2dsphere"});
FeatureSchema.index({'lastModified': 1});
FeatureSchema.index({'attachments.lastModified': 1});
FeatureSchema.index({'userId': 1});
FeatureSchema.index({'deviceId': 1});
FeatureSchema.index({'properties.type': 1});
FeatureSchema.index({'properties.timestamp': 1});
FeatureSchema.index({'states.name': 1});
FeatureSchema.index({'attachments.oriented': 1});
FeatureSchema.index({'attachments.contentType': 1});
FeatureSchema.index({'attachments.thumbnails.minDimension': 1});
var models = {};
var Attachment = mongoose.model('Attachment', AttachmentSchema);
var Thumbnail = mongoose.model('Thumbnail', ThumbnailSchema);
var State = mongoose.model('State', StateSchema);
// return a string for each property
var convertFieldForQuery = function(field, keys, fields) {
keys = keys || [];
fields = fields || {};
for (var childField in field) {
keys.push(childField);
if (Object(field[childField]) === field[childField]) {
convertFieldForQuery(field[childField], keys, fields);
} else {
var key = keys.join(".");
if (field[childField]) fields[key] = field[childField];
keys.pop();
}
}
return fields;
}
var parseFields = function(fields) {
if (fields) {
var state = fields.state ? true : false;
delete fields.state;
fields = convertFieldForQuery(fields);
if (fields.id === undefined) fields.id = true; // default is to return id if not specified
if (fields.type === undefined) fields.type = true; // default is to return type if not specified
if (state) {
fields.states = {$slice: 1};
}
return fields;
} else {
return { states: {$slice: 1}};
}
}
var featureModel = function(layer) {
var name = layer.collectionName;
var model = models[name];
if (!model) {
// Creates the Model for the Features Schema
var model = mongoose.model(name, FeatureSchema, name);
models[name] = model;
}
return model;
}
exports.featureModel = featureModel;
exports.getFeatures = function(layer, o, callback) {
var conditions = {};
var fields = parseFields(o.fields);
var query = featureModel(layer).find(conditions, fields);
var filter = o.filter || {};
// Filter by geometry
if (filter.geometry) {
query.where('geometry').intersects.geometry(filter.geometry);
}
if (filter.startDate) {
query.where('lastModified').gte(filter.startDate);
}
if (filter.endDate) {
query.where('lastModified').lt(filter.endDate);
}
if (filter.states) {
query.where('states.0.name').in(filter.states);
}
if (o.sort) {
console.log('sort on ', o.sort);
query.sort(o.sort);
}
query.lean().exec(function (err, features) {
if (err) {
console.log("Error finding features in mongo: " + err);
}
callback(features);
});
}
exports.getFeatureById = function(layer, featureId, options, callback) {
var fields = parseFields(options.fields);
featureModel(layer).findById(featureId, fields, function(err, feature) {
if (err) {
console.log("Error finding feature in mongo: " + err);
}
callback(feature);
});
}
exports.createFeature = function(layer, feature, callback) {
feature.lastModified = moment.utc().toDate();
featureModel(layer).create(feature, function(err, newFeature) {
if (err) {
console.log(JSON.stringify(err));
}
callback(newFeature);
});
}
exports.createFeatures = function(layer, features, callback) {
features.forEach(function(feature) {
feature.properties = feature.properties || {};
});
featureModel(layer).create(features, function(err) {
callback(err, features);
});
}
exports.createGeoJsonFeature = function(layer, feature, callback) {
var properties = feature.properties ? feature.properties : {};
featureModel(layer).create(feature, function(err, newFeature) {
if (err) {
console.log('Error creating feature', err);
console.log('feature is: ', feature);
}
callback(err, newFeature);
});
}
exports.updateFeature = function(layer, featureId, feature, callback) {
feature.lastModified = moment.utc().toDate();
featureModel(layer).findByIdAndUpdate(featureId, feature, {new: true}, function (err, updatedFeature) {
if (err) {
console.log('Could not update feature', err);
}
callback(err, updatedFeature);
});
}
exports.removeFeature = function(layer, featureId, callback) {
featureModel(layer).findByIdAndRemove(featureId, function (err, feature) {
if (err) {
console.log('Could not remove feature', err);
}
callback(err, feature);
});
}
exports.removeUser = function(user, callback) {
var condition = { userId: user._id };
var update = { '$unset': { userId: true } };
var options = { multi: true };
Layer.getLayers({type: 'Feature'}, function(err, layers) {
async.each(layers, function(layer, done) {
featureModel(layer).update(condition, update, options, function(err, numberAffected) {
console.log('Remove deleted user from ' + numberAffected + ' documents for layer ' + layer.name);
done();
});
},
function(err){
callback();
});
});
}
exports.removeDevice = function(device, callback) {
var condition = { deviceId: device._id };
var update = { '$unset': { deviceId: true } };
var options = { multi: true };
Layer.getLayers({type: 'Feature'}, function(err, layers) {
async.each(layers, function(layer, done) {
featureModel(layer).update(condition, update, options, function(err, numberAffected) {
console.log('Remove deleted device from ' + numberAffected + ' documents for layer ' + layer.name);
done();
});
},
function(err){
callback();
});
});
}
exports.addState = function(layer, id, state, callback) {
var condition = {_id: mongoose.Types.ObjectId(id), 'states.0.name': {'$ne': state.name}};
state._id = mongoose.Types.ObjectId();
var update = {
'$push': {
states: {
'$each': [state],
'$position': 0
}
},
'$set': {
lastModified: moment.utc().toDate()
}
};
featureModel(layer).collection.update(condition, update, {upsert: true}, function(err) {
callback(err, state);
});
}
exports.getAttachments = function(layer, id, callback) {
var query = {};
query[id.field] = id.id;
var fields = {attachments: 1};
featureModel(layer).findOne(query, fields, function(err, feature) {
callback(feature.attachments);
});
}
exports.getAttachment = function(layer, featureId, attachmentId, callback) {
var id = {_id: featureId};
var attachment = {"attachments": {"$elemMatch": {_id: attachmentId}}};
var fields = {attachments: true};
featureModel(layer).findOne(id, attachment, fields, function(err, feature) {
var attachment = feature.attachments.length ? feature.attachments[0] : null;
callback(attachment);
});
}
exports.addAttachment = function(layer, id, file, callback) {
if (id !== Object(id)) {
id = {id: id, field: '_id'};
}
var condition = {};
condition[id.field] = id.id;
var attachment = new Attachment({
contentType: file.headers['content-type'],
size: file.size,
name: file.name,
relativePath: file.relativePath,
lastModified: new Date()
});
var update = {'$push': { attachments: attachment }, 'lastModified': new Date()};
featureModel(layer).update(condition, update, function(err, feature) {
if (err) {
console.log('Error updating attachments from DB', err);
}
callback(err, attachment);
});
}
exports.updateAttachment = function(layer, featureId, attachmentId, file, callback) {
var condition = {_id: featureId, 'attachments._id': attachmentId};
var set = {};
if (file.name) set['attachments.$.name'] = file.name;
if (file.type) set['attachments.$.type'] = file.type;
if (file.size) set['attachments.$.size'] = file.size;
if (file.width) set['attachments.$.width'] = file.width;
if (file.height) set['attachments.$.height'] = file.height;
if (file.oriented) set['attachments.$.oriented'] = file.oriented;
set['attachments.$.lastModified'] = new Date();
var update = { '$set': set };
featureModel(layer).update(condition, update, function(err, feature) {
if (err) {
console.log('Error updating attachments from DB', err);
}
callback(err);
});
}
exports.removeAttachment = function(feature, id, callback) {
var attachments = {};
attachments[id.field] = id.id;
feature.update({'$pull': {attachments: attachments}}, function(err, number, raw) {
if (err) {
console.log('Error pulling attachments from DB', err);
}
callback(err);
});
}
exports.addAttachmentThumbnail = function(layer, featureId, attachmentId, thumbnail, callback) {
var condition = {_id: featureId, 'attachments._id': attachmentId};
var update = {'$push': { 'attachments.$.thumbnails': thumbnail }};
featureModel(layer).update(condition, update, function(err, feature) {
if (err) {
console.log('Error updating thumbnails to DB', err);
}
callback(err);
});
}
| models/feature.js | var mongoose = require('mongoose')
, async = require('async')
, moment = require('moment')
, Layer = require('../models/layer');
var Schema = mongoose.Schema;
var StateSchema = new Schema({
name: { type: String, required: true },
userId: { type: Schema.Types.ObjectId, ref: 'User' }
});
var AttachmentSchema = new Schema({
lastModified: {type: Date, required: false},
contentType: { type: String, required: false },
size: { type: Number, required: false },
name: { type: String, required: false },
relativePath: { type: String, required: true },
width: { type: Number, required: false },
height: { type: Number, required: false },
oriented: {type: Boolean, required: true, default: false },
thumbnails: [ThumbnailSchema]
},{
strict: false
});
var ThumbnailSchema = new Schema({
contentType: { type: String, required: false },
size: { type: Number, required: false },
name: { type: String, required: false },
relativePath: { type: String, required: true },
minDimension: { type: Number, required: true },
width: { type: Number, required: false },
height: { type: Number, required: false}
},{
strict: false
});
// Creates the Schema for the Attachments object
var FeatureSchema = new Schema({
type: {type: String, required: true},
lastModified: {type: Date, required: false},
userId: {type: Schema.Types.ObjectId, required: false, sparse: true},
deviceId: {type: Schema.Types.ObjectId, required: false, sparse: true},
geometry: Schema.Types.Mixed,
properties: Schema.Types.Mixed,
attachments: [AttachmentSchema],
states: [StateSchema]
},{
strict: false
});
FeatureSchema.index({geometry: "2dsphere"});
FeatureSchema.index({'lastModified': 1});
FeatureSchema.index({'attachments.lastModified': 1});
FeatureSchema.index({'userId': 1});
FeatureSchema.index({'deviceId': 1});
FeatureSchema.index({'properties.type': 1});
FeatureSchema.index({'properties.timestamp': 1});
FeatureSchema.index({'states.name': 1});
FeatureSchema.index({'attachments.oriented': 1});
FeatureSchema.index({'attachments.contentType': 1});
FeatureSchema.index({'attachments.thumbnails.minDimension': 1});
var models = {};
var Attachment = mongoose.model('Attachment', AttachmentSchema);
var Thumbnail = mongoose.model('Thumbnail', ThumbnailSchema);
var State = mongoose.model('State', StateSchema);
// return a string for each property
var convertFieldForQuery = function(field, keys, fields) {
keys = keys || [];
fields = fields || {};
for (var childField in field) {
keys.push(childField);
if (Object(field[childField]) === field[childField]) {
convertFieldForQuery(field[childField], keys, fields);
} else {
var key = keys.join(".");
if (field[childField]) fields[key] = field[childField];
keys.pop();
}
}
return fields;
}
var parseFields = function(fields) {
if (fields) {
var state = fields.state ? true : false;
delete fields.state;
fields = convertFieldForQuery(fields);
if (fields.id === undefined) fields.id = true; // default is to return id if not specified
if (fields.type === undefined) fields.type = true; // default is to return type if not specified
if (state) {
fields.states = {$slice: 1};
}
return fields;
} else {
return { states: {$slice: 1}};
}
}
var featureModel = function(layer) {
var name = layer.collectionName;
var model = models[name];
if (!model) {
// Creates the Model for the Features Schema
var model = mongoose.model(name, FeatureSchema, name);
models[name] = model;
}
return model;
}
exports.featureModel = featureModel;
exports.getFeatures = function(layer, o, callback) {
var conditions = {};
var fields = parseFields(o.fields);
var query = featureModel(layer).find(conditions, fields);
var filter = o.filter || {};
// Filter by geometry
if (filter.geometry) {
query.where('geometry').intersects.geometry(filter.geometry);
}
if (filter.startDate) {
query.where('lastModified').gte(filter.startDate);
}
if (filter.endDate) {
query.where('lastModified').lt(filter.endDate);
}
if (filter.states) {
query.where('states.0.name').in(filter.states);
}
if (o.sort) {
console.log('sort on ', o.sort);
query.sort(o.sort);
}
query.lean().exec(function (err, features) {
if (err) {
console.log("Error finding features in mongo: " + err);
}
callback(features);
});
}
exports.getFeatureById = function(layer, featureId, options, callback) {
var fields = parseFields(options.fields);
featureModel(layer).findById(featureId, fields, function(err, feature) {
if (err) {
console.log("Error finding feature in mongo: " + err);
}
callback(feature);
});
}
exports.createFeature = function(layer, feature, callback) {
feature.lastModified = moment.utc().toDate();
featureModel(layer).create(feature, function(err, newFeature) {
if (err) {
console.log(JSON.stringify(err));
}
callback(newFeature);
});
}
exports.createFeatures = function(layer, features, callback) {
features.forEach(function(feature) {
feature.properties = feature.properties || {};
});
featureModel(layer).create(features, function(err) {
callback(err, features);
});
}
exports.createGeoJsonFeature = function(layer, feature, callback) {
var properties = feature.properties ? feature.properties : {};
featureModel(layer).create(feature, function(err, newFeature) {
if (err) {
console.log('Error creating feature', err);
console.log('feature is: ', feature);
}
callback(err, newFeature);
});
}
exports.updateFeature = function(layer, featureId, feature, callback) {
feature.lastModified = moment.utc().toDate();
featureModel(layer).findByIdAndUpdate(featureId, feature, {new: true}, function (err, updatedFeature) {
if (err) {
console.log('Could not update feature', err);
}
callback(err, updatedFeature);
});
}
exports.removeFeature = function(layer, featureId, callback) {
featureModel(layer).findByIdAndRemove(featureId, function (err, feature) {
if (err) {
console.log('Could not remove feature', err);
}
callback(err, feature);
});
}
exports.removeUser = function(user, callback) {
var condition = { userId: user._id };
var update = { '$unset': { userId: true } };
var options = { multi: true };
Layer.getLayers({type: 'Feature'}, function(err, layers) {
async.each(layers, function(layer, done) {
featureModel(layer).update(condition, update, options, function(err, numberAffected) {
console.log('Remove deleted user from ' + numberAffected + ' documents for layer ' + layer.name);
done();
});
},
function(err){
callback();
});
});
}
exports.removeDevice = function(device, callback) {
var condition = { deviceId: device._id };
var update = { '$unset': { deviceId: true } };
var options = { multi: true };
Layer.getLayers({type: 'Feature'}, function(err, layers) {
async.each(layers, function(layer, done) {
featureModel(layer).update(condition, update, options, function(err, numberAffected) {
console.log('Remove deleted device from ' + numberAffected + ' documents for layer ' + layer.name);
done();
});
},
function(err){
callback();
});
});
}
// IMPORTANT:
// This is a complete hack to get the new state to insert into
// the beginning of the array. Once mongo 2.6 is released
// we can use the $push -> $each -> $position operator
exports.addState = function(layer, id, state, callback) {
var condition = {_id: mongoose.Types.ObjectId(id), 'states.0.name': {'$ne': state.name}};
state._id = mongoose.Types.ObjectId();
var update = {
'$set': {
'states.-1': state,
lastModified: moment.utc().toDate()
}
};
featureModel(layer).collection.update(condition, update, {upsert: true}, function(err) {
callback(err, state);
});
}
exports.getAttachments = function(layer, id, callback) {
var query = {};
query[id.field] = id.id;
var fields = {attachments: 1};
featureModel(layer).findOne(query, fields, function(err, feature) {
callback(feature.attachments);
});
}
exports.getAttachment = function(layer, featureId, attachmentId, callback) {
var id = {_id: featureId};
var attachment = {"attachments": {"$elemMatch": {_id: attachmentId}}};
var fields = {attachments: true};
featureModel(layer).findOne(id, attachment, fields, function(err, feature) {
var attachment = feature.attachments.length ? feature.attachments[0] : null;
callback(attachment);
});
}
exports.addAttachment = function(layer, id, file, callback) {
if (id !== Object(id)) {
id = {id: id, field: '_id'};
}
var condition = {};
condition[id.field] = id.id;
var attachment = new Attachment({
contentType: file.headers['content-type'],
size: file.size,
name: file.name,
relativePath: file.relativePath,
lastModified: new Date()
});
var update = {'$push': { attachments: attachment }, 'lastModified': new Date()};
featureModel(layer).update(condition, update, function(err, feature) {
if (err) {
console.log('Error updating attachments from DB', err);
}
callback(err, attachment);
});
}
exports.updateAttachment = function(layer, featureId, attachmentId, file, callback) {
var condition = {_id: featureId, 'attachments._id': attachmentId};
var set = {};
if (file.name) set['attachments.$.name'] = file.name;
if (file.type) set['attachments.$.type'] = file.type;
if (file.size) set['attachments.$.size'] = file.size;
if (file.width) set['attachments.$.width'] = file.width;
if (file.height) set['attachments.$.height'] = file.height;
if (file.oriented) set['attachments.$.oriented'] = file.oriented;
set['attachments.$.lastModified'] = new Date();
var update = { '$set': set };
featureModel(layer).update(condition, update, function(err, feature) {
if (err) {
console.log('Error updating attachments from DB', err);
}
callback(err);
});
}
exports.removeAttachment = function(feature, id, callback) {
var attachments = {};
attachments[id.field] = id.id;
feature.update({'$pull': {attachments: attachments}}, function(err, number, raw) {
if (err) {
console.log('Error pulling attachments from DB', err);
}
callback(err);
});
}
exports.addAttachmentThumbnail = function(layer, featureId, attachmentId, thumbnail, callback) {
var condition = {_id: featureId, 'attachments._id': attachmentId};
var update = {'$push': { 'attachments.$.thumbnails': thumbnail }};
featureModel(layer).update(condition, update, function(err, feature) {
if (err) {
console.log('Error updating thumbnails to DB', err);
}
callback(err);
});
}
| fixed inserting states for mongo 2.6
| models/feature.js | fixed inserting states for mongo 2.6 | <ide><path>odels/feature.js
<ide> });
<ide> }
<ide>
<del>// IMPORTANT:
<del>// This is a complete hack to get the new state to insert into
<del>// the beginning of the array. Once mongo 2.6 is released
<del>// we can use the $push -> $each -> $position operator
<ide> exports.addState = function(layer, id, state, callback) {
<ide> var condition = {_id: mongoose.Types.ObjectId(id), 'states.0.name': {'$ne': state.name}};
<ide>
<ide> state._id = mongoose.Types.ObjectId();
<ide> var update = {
<add> '$push': {
<add> states: {
<add> '$each': [state],
<add> '$position': 0
<add> }
<add> },
<ide> '$set': {
<del> 'states.-1': state,
<ide> lastModified: moment.utc().toDate()
<ide> }
<ide> }; |
|
Java | bsd-3-clause | f450c9f60c33eb4d394b483e9960535a7fa462af | 0 | NCIP/catissue-advanced-query,NCIP/catissue-advanced-query | package edu.wustl.query.action;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.hibernate.HibernateException;
import edu.wustl.cider.util.CiderUtility;
import edu.wustl.common.beans.NameValueBean;
import edu.wustl.common.beans.SessionDataBean;
import edu.wustl.common.querysuite.queryobject.IParameterizedQuery;
import edu.wustl.common.util.Utility;
import edu.wustl.common.util.dbManager.HibernateUtility;
import edu.wustl.common.util.global.ApplicationProperties;
import edu.wustl.query.actionForm.SaveQueryForm;
import edu.wustl.query.domain.Workflow;
import edu.wustl.query.flex.dag.DAGConstant;
import edu.wustl.query.util.global.Constants;
import edu.wustl.query.util.global.Variables;
import edu.wustl.query.util.querysuite.CsmUtility;
import gov.nih.nci.security.exceptions.CSException;
import gov.nih.nci.security.exceptions.CSObjectNotFoundException;
/**
* @author chetan_patil
* @created September 12, 2007, 10:24:05 PM
*/
public class RetrieveQueryAction extends Action
{
@Override
public ActionForward execute(ActionMapping actionMapping, ActionForm actionForm,
HttpServletRequest request, HttpServletResponse response) throws Exception
{
ActionForward actionForward = null;
try
{
HttpSession session = request.getSession();
removeAttributesFromSession(session);
SaveQueryForm saveQueryForm = (SaveQueryForm) actionForm;
Collection<IParameterizedQuery> authorizedQueryCollection = new ArrayList<IParameterizedQuery>();
Collection<IParameterizedQuery> sharedQueryCollection = new ArrayList<IParameterizedQuery>();
initializeParameterizeQueryCollection(request, saveQueryForm,
authorizedQueryCollection,
sharedQueryCollection);
//user in workflow popup
request.setAttribute(Constants.PAGE_OF, request.getParameter(Constants.PAGE_OF));
request.setAttribute(Constants.MY_QUERIES_COUNT, authorizedQueryCollection.size());
request.setAttribute(Constants.SHARED_QUERIES_COUNT, sharedQueryCollection.size());
actionForward = setActionForward(actionMapping, request.getParameter("pageOf"));
}
catch (HibernateException hibernateException)
{
actionForward = actionMapping.findForward(Constants.FAILURE);
}
request.setAttribute(Constants.POPUP_MESSAGE, ApplicationProperties
.getValue("query.confirmBox.message"));
if(request.getParameter("pageOf")!=null)
{
request.setAttribute(Constants.PAGE_OF, request.getParameter("pageOf"));
}
return actionForward;
}
/**
* return my queries collection Count
* @param dataBean
* @return
* @throws CSObjectNotFoundException
* @throws CSException
*/
public int setMyQueryCount(SessionDataBean dataBean) throws CSObjectNotFoundException, CSException
{
Collection<IParameterizedQuery> authorizedQueryCollection = new ArrayList<IParameterizedQuery>();
Collection<IParameterizedQuery> sharedQueryCollection = new ArrayList<IParameterizedQuery>();
CsmUtility csmUtility=getDefaultCsmUtility();
csmUtility.checkExecuteQueryPrivilege(authorizedQueryCollection, sharedQueryCollection,dataBean);
if(authorizedQueryCollection!=null)
{
return authorizedQueryCollection.size();
}
return 0;
}
/**
* return shared query Collection Count
* @param dataBean
* @return
* @throws CSObjectNotFoundException
* @throws CSException
*/
public int setSharedQueryCount(SessionDataBean dataBean) throws CSObjectNotFoundException, CSException
{
Collection<IParameterizedQuery> authorizedQueryCollection = new ArrayList<IParameterizedQuery>();
Collection<IParameterizedQuery> sharedQueryCollection = new ArrayList<IParameterizedQuery>();
CsmUtility csmUtility=getDefaultCsmUtility();
csmUtility.checkExecuteQueryPrivilege( authorizedQueryCollection, sharedQueryCollection,dataBean);
if(sharedQueryCollection!=null)
{
return sharedQueryCollection.size();
}
return 0;
}
private void initializeParameterizeQueryCollection(HttpServletRequest request,
SaveQueryForm saveQueryForm,
Collection<IParameterizedQuery> authorizedQueryCollection,
Collection<IParameterizedQuery> sharedQueryCollection) throws CSException,
CSObjectNotFoundException
{
Collection<IParameterizedQuery> finalQueries= null;
CsmUtility csmUtility=getDefaultCsmUtility();
csmUtility.checkExecuteQueryPrivilege( authorizedQueryCollection, sharedQueryCollection,(SessionDataBean) request.getSession().getAttribute(Constants.SESSION_DATA));
setQueryCollectionToSaveQueryForm(saveQueryForm, (String) request.getAttribute("pageOf"), authorizedQueryCollection,
sharedQueryCollection);
if(request.getParameter("pageOf")!=null&&
(Constants.MY_QUERIES_FOR_MAIN_MENU.equals(request.getParameter("pageOf"))||
Constants.MY_QUERIES.equals(request.getParameter("pageOf"))||
Constants.MY_QUERIES_FOR_WORKFLOW.equals(request.getParameter("pageOf"))
)
)
{
finalQueries = authorizedQueryCollection;
saveQueryForm.setParameterizedQueryCollection(authorizedQueryCollection);
saveQueryForm=
setPagiantion(request,request.getParameter("requestFor"),saveQueryForm);
}
if(request.getParameter("pageOf")!=null&&
(Constants.SHARED_QUERIES_FOR_MAIN_MENU.equals(request.getParameter("pageOf"))||
Constants.SAHRED_QUERIES.equals(request.getParameter("pageOf"))||
Constants.SAHRED_QUERIES_FOR_WORKFLOW.equals(request.getParameter("pageOf"))
))
{
finalQueries = sharedQueryCollection;
saveQueryForm.setParameterizedQueryCollection(sharedQueryCollection);
}
setPagiantion(request,request.getParameter("requestFor"),saveQueryForm);
saveQueryForm.setParameterizedQueryCollection(getMaxRecord(finalQueries,request));
populateGrid(request,saveQueryForm.getParameterizedQueryCollection());
}
private SaveQueryForm setPagiantion(HttpServletRequest request, String requestFor,
SaveQueryForm saveQueryForm)
{
int totalRecords=0;
if(saveQueryForm.getParameterizedQueryCollection()!=null)
{
totalRecords=saveQueryForm.getParameterizedQueryCollection().size();
}
int startIndex = 0;
int pageNum = getPageNumber(request, requestFor);
int maxRecords = getRecordsPerPage(request, requestFor);
request.getSession().setAttribute(Constants.RESULTS_PER_PAGE,maxRecords );
request.getSession().setAttribute(Constants.PAGE_NUMBER,pageNum );
startIndex = maxRecords * (pageNum - 1);
totalRecords=getTotalRecords(request,requestFor,totalRecords);
int totalPages = getTotalPages(maxRecords, totalRecords);
request.getSession().setAttribute("totalPages",totalPages);
request.getSession().setAttribute(Constants.TOTAL_RESULTS, totalRecords);
request.getSession().setAttribute("startIndex",startIndex);
List<NameValueBean> resultsPerPageOptions=new ArrayList<NameValueBean>();
resultsPerPageOptions.add(new NameValueBean("5","5"));
resultsPerPageOptions.add(new NameValueBean("10","10"));
resultsPerPageOptions.add(new NameValueBean("15","15"));
request.setAttribute("resultsPerPageOptions", resultsPerPageOptions);
int firstPageNo = 1, currentPageNo;
currentPageNo = (Integer) (request.getSession().getAttribute("pageNum"));
if (request.getParameter("firstPageNum") != null)
{
firstPageNo = Integer.parseInt(request.getParameter("firstPageNum"));
}
else
{
if (currentPageNo % 5 == 0)
{
firstPageNo = currentPageNo - 4;
}
else
{
firstPageNo = currentPageNo - (currentPageNo % 5 - 1);
}
}
if (firstPageNo < 5)
{
firstPageNo = 1;
}
request.setAttribute("firstPageNum", firstPageNo);
request.setAttribute("numOfPageNums", 5);
if ((firstPageNo + 4) > (Integer) (request.getSession().getAttribute("totalPages")))
{
request.setAttribute("lastPageNum", (Integer) (request.getSession()
.getAttribute("totalPages")));
}
else
{
request.setAttribute("lastPageNum", firstPageNo + 4);
}
return saveQueryForm;
}
/**
* @param maxRecords
* @param totalRecords
* @return
*/
private int getTotalPages(int maxRecords,
int totalRecords)
{
int totalPages=0;
totalPages = totalRecords % maxRecords == 0
? totalRecords / maxRecords
: (totalRecords / maxRecords) + 1;
return totalPages;
}
private int getTotalRecords(HttpServletRequest request, String requestFor, int matchingUsersCount)
{
int totalRecords=0;
if(requestFor!=null && request.getSession().getAttribute(Constants.TOTAL_RESULTS)!=null)
{
totalRecords=(Integer)request.getSession().getAttribute(Constants.TOTAL_RESULTS);
}
else
{
totalRecords=matchingUsersCount;
}
return totalRecords;
}
private ActionForward setActionForward(ActionMapping actionMapping, String pageOf)
{
ActionForward actionForward;
actionForward = actionMapping.findForward(Constants.SUCCESS);
if(pageOf!=null)
{
actionForward = actionMapping.findForward(pageOf);
}
return actionForward;
}
private void removeAttributesFromSession(HttpSession session)
{
session.removeAttribute(Constants.SELECTED_COLUMN_META_DATA);
session.removeAttribute(Constants.SAVE_GENERATED_SQL);
session.removeAttribute(Constants.SAVE_TREE_NODE_LIST);
session.removeAttribute(Constants.ID_NODES_MAP);
session.removeAttribute(Constants.MAIN_ENTITY_MAP);
session.removeAttribute(Constants.EXPORT_DATA_LIST);
session.removeAttribute(Constants.ENTITY_IDS_MAP);
session.removeAttribute(DAGConstant.TQUIMap);
}
private void setQueryCollectionToSaveQueryForm(SaveQueryForm saveQueryForm, String pageOf,
Collection<IParameterizedQuery> authorizedQueryCollection,
Collection<IParameterizedQuery> sharedQueryCollection)
{
if(pageOf !=null && (Constants.PUBLIC_QUERY_PROTECTION_GROUP.equals(pageOf)||
Constants.PUBLIC_QUERIES_FOR_WORKFLOW.equals(pageOf)))
{
saveQueryForm.setParameterizedQueryCollection(sharedQueryCollection);
}
else
{
saveQueryForm.setParameterizedQueryCollection(authorizedQueryCollection);
}
}
private Collection<IParameterizedQuery> getMaxRecord(Collection<IParameterizedQuery> queries,HttpServletRequest request)
{
Collection<IParameterizedQuery> coll = new ArrayList<IParameterizedQuery>();
int maxRec = (Integer) request.getSession().getAttribute(Constants.RESULTS_PER_PAGE);
int strartIndex = (Integer) request.getSession().getAttribute("startIndex");
IParameterizedQuery arr[] = new IParameterizedQuery[queries.size()];
queries.toArray(arr);
for (int i=0;i<maxRec;i++)
{
if((i+strartIndex)==arr.length)
break;
else
coll.add(((IParameterizedQuery)arr[i+strartIndex]));
}
return coll;
}
private int getRecordsPerPage(HttpServletRequest request, String requestFor)
{
Object recordsPerPageObj=getSessionAttribute(request,Constants.RESULTS_PER_PAGE);
int maxRecords;
if(recordsPerPageObj!=null && requestFor!=null)
{
maxRecords=Integer.parseInt(recordsPerPageObj.toString());
}
else
{
maxRecords=10;
}
return maxRecords;
}
private int getPageNumber(HttpServletRequest request, String requestFor)
{
Object pageNumObj=getSessionAttribute(request,Constants.PAGE_NUMBER);
int pageNum=0;
if(pageNumObj!=null && requestFor!=null)
{
pageNum=Integer.parseInt(pageNumObj.toString());
}
else
{
pageNum=1;
}
return pageNum;
}
private Object getSessionAttribute(HttpServletRequest request, String attributeName)
{
Object object=null;
if(request!=null)
{
object=request.getParameter(attributeName);
if(object==null)
{
object=request.getAttribute(attributeName);
if(object==null)
{
object=request.getSession().getAttribute(attributeName);
}
}
}
return object;
}
/**
* this function returns the csmUtility class
* @return
*/
public static CsmUtility getDefaultCsmUtility()
{
return (CsmUtility)Utility.getObject(Variables.csmUtility);
}
public void populateGrid(HttpServletRequest request,Collection<IParameterizedQuery> queryColletion)
{
request.setAttribute("identifierFieldIndex",3);
final List<Object[]> attributesList = new ArrayList<Object[]>();
Object[] attributes = null;
for (IParameterizedQuery query : queryColletion) {
attributes = new Object[4];
if (query != null) {
if (query.getName() != null) {
attributes[1] = query.getName();
} else {
attributes[1] = "";
}
attributes[2] = query.getType();
attributes[3] = query.getId().toString();
}
attributesList.add(attributes);
}
request.setAttribute("msgBoardItemList", CiderUtility
.getmyData(attributesList));
List<String> columnList = new ArrayList<String>();
columnList.add(" ");
columnList.add("Query Title");
columnList.add("Query Type");
columnList.add("identifier");
request.setAttribute("columns", edu.wustl.cider.util.global.Utility.getcolumns(columnList));
request.setAttribute("colWidth", "\"4,80,16,0\"");
request.setAttribute("isWidthInPercent", true);
request.setAttribute("colTypes", "\"ch,str,str,int\"");
request.setAttribute("colDataTypes", "\"ch,txt,txt,ro\"");
}
}
| WEB-INF/src/edu/wustl/query/action/RetrieveQueryAction.java | package edu.wustl.query.action;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.hibernate.HibernateException;
import edu.wustl.cider.util.CiderUtility;
import edu.wustl.common.beans.NameValueBean;
import edu.wustl.common.beans.SessionDataBean;
import edu.wustl.common.querysuite.queryobject.IParameterizedQuery;
import edu.wustl.common.util.Utility;
import edu.wustl.common.util.dbManager.HibernateUtility;
import edu.wustl.common.util.global.ApplicationProperties;
import edu.wustl.query.actionForm.SaveQueryForm;
import edu.wustl.query.domain.Workflow;
import edu.wustl.query.flex.dag.DAGConstant;
import edu.wustl.query.util.global.Constants;
import edu.wustl.query.util.global.Variables;
import edu.wustl.query.util.querysuite.CsmUtility;
import gov.nih.nci.security.exceptions.CSException;
import gov.nih.nci.security.exceptions.CSObjectNotFoundException;
/**
* @author chetan_patil
* @created September 12, 2007, 10:24:05 PM
*/
public class RetrieveQueryAction extends Action
{
@Override
public ActionForward execute(ActionMapping actionMapping, ActionForm actionForm,
HttpServletRequest request, HttpServletResponse response) throws Exception
{
ActionForward actionForward = null;
try
{
HttpSession session = request.getSession();
removeAttributesFromSession(session);
SaveQueryForm saveQueryForm = (SaveQueryForm) actionForm;
Collection<IParameterizedQuery> authorizedQueryCollection = new ArrayList<IParameterizedQuery>();
Collection<IParameterizedQuery> sharedQueryCollection = new ArrayList<IParameterizedQuery>();
initializeParameterizeQueryCollection(request, saveQueryForm,
authorizedQueryCollection,
sharedQueryCollection);
//user in workflow popup
request.setAttribute(Constants.PAGE_OF, request.getParameter(Constants.PAGE_OF));
request.setAttribute(Constants.MY_QUERIES_COUNT, authorizedQueryCollection.size());
request.setAttribute(Constants.SHARED_QUERIES_COUNT, sharedQueryCollection.size());
actionForward = setActionForward(actionMapping, request.getParameter("pageOf"));
}
catch (HibernateException hibernateException)
{
actionForward = actionMapping.findForward(Constants.FAILURE);
}
request.setAttribute(Constants.POPUP_MESSAGE, ApplicationProperties
.getValue("query.confirmBox.message"));
if(request.getParameter("pageOf")!=null)
{
request.setAttribute(Constants.PAGE_OF, request.getParameter("pageOf"));
}
return actionForward;
}
/**
* return my queries collection Count
* @param dataBean
* @return
* @throws CSObjectNotFoundException
* @throws CSException
*/
public int setMyQueryCount(SessionDataBean dataBean) throws CSObjectNotFoundException, CSException
{
Collection<IParameterizedQuery> authorizedQueryCollection = new ArrayList<IParameterizedQuery>();
Collection<IParameterizedQuery> sharedQueryCollection = new ArrayList<IParameterizedQuery>();
CsmUtility csmUtility=getDefaultCsmUtility();
csmUtility.checkExecuteQueryPrivilege(authorizedQueryCollection, sharedQueryCollection,dataBean);
if(authorizedQueryCollection!=null)
{
return authorizedQueryCollection.size();
}
return 0;
}
/**
* return shared query Collection Count
* @param dataBean
* @return
* @throws CSObjectNotFoundException
* @throws CSException
*/
public int setSharedQueryCount(SessionDataBean dataBean) throws CSObjectNotFoundException, CSException
{
Collection<IParameterizedQuery> parameterizedQueryCollection=HibernateUtility
.executeHQL(HibernateUtility.GET_PARAMETERIZED_QUERIES_DETAILS);
Collection<IParameterizedQuery> authorizedQueryCollection = new ArrayList<IParameterizedQuery>();
Collection<IParameterizedQuery> sharedQueryCollection = new ArrayList<IParameterizedQuery>();
CsmUtility csmUtility=getDefaultCsmUtility();
csmUtility.checkExecuteQueryPrivilege( authorizedQueryCollection, sharedQueryCollection,dataBean);
if(parameterizedQueryCollection!=null)
{
return sharedQueryCollection.size();
}
return 0;
}
private void initializeParameterizeQueryCollection(HttpServletRequest request,
SaveQueryForm saveQueryForm,
Collection<IParameterizedQuery> authorizedQueryCollection,
Collection<IParameterizedQuery> sharedQueryCollection) throws CSException,
CSObjectNotFoundException
{
Collection<IParameterizedQuery> finalQueries= null;
CsmUtility csmUtility=getDefaultCsmUtility();
csmUtility.checkExecuteQueryPrivilege( authorizedQueryCollection, sharedQueryCollection,(SessionDataBean) request.getSession().getAttribute(Constants.SESSION_DATA));
setQueryCollectionToSaveQueryForm(saveQueryForm, (String) request.getAttribute("pageOf"), authorizedQueryCollection,
sharedQueryCollection);
if(request.getParameter("pageOf")!=null&&
(Constants.MY_QUERIES_FOR_MAIN_MENU.equals(request.getParameter("pageOf"))||
Constants.MY_QUERIES.equals(request.getParameter("pageOf"))||
Constants.MY_QUERIES_FOR_WORKFLOW.equals(request.getParameter("pageOf"))
)
)
{
finalQueries = authorizedQueryCollection;
saveQueryForm.setParameterizedQueryCollection(authorizedQueryCollection);
saveQueryForm=
setPagiantion(request,request.getParameter("requestFor"),saveQueryForm);
}
if(request.getParameter("pageOf")!=null&&
(Constants.SHARED_QUERIES_FOR_MAIN_MENU.equals(request.getParameter("pageOf"))||
Constants.SAHRED_QUERIES.equals(request.getParameter("pageOf"))||
Constants.SAHRED_QUERIES_FOR_WORKFLOW.equals(request.getParameter("pageOf"))
))
{
finalQueries = sharedQueryCollection;
saveQueryForm.setParameterizedQueryCollection(sharedQueryCollection);
}
setPagiantion(request,request.getParameter("requestFor"),saveQueryForm);
saveQueryForm.setParameterizedQueryCollection(getMaxRecord(finalQueries,request));
populateGrid(request,saveQueryForm.getParameterizedQueryCollection());
}
private SaveQueryForm setPagiantion(HttpServletRequest request, String requestFor,
SaveQueryForm saveQueryForm)
{
int totalRecords=0;
if(saveQueryForm.getParameterizedQueryCollection()!=null)
{
totalRecords=saveQueryForm.getParameterizedQueryCollection().size();
}
int startIndex = 0;
int pageNum = getPageNumber(request, requestFor);
int maxRecords = getRecordsPerPage(request, requestFor);
request.getSession().setAttribute(Constants.RESULTS_PER_PAGE,maxRecords );
request.getSession().setAttribute(Constants.PAGE_NUMBER,pageNum );
startIndex = maxRecords * (pageNum - 1);
totalRecords=getTotalRecords(request,requestFor,totalRecords);
int totalPages = getTotalPages(maxRecords, totalRecords);
request.getSession().setAttribute("totalPages",totalPages);
request.getSession().setAttribute(Constants.TOTAL_RESULTS, totalRecords);
request.getSession().setAttribute("startIndex",startIndex);
List<NameValueBean> resultsPerPageOptions=new ArrayList<NameValueBean>();
resultsPerPageOptions.add(new NameValueBean("5","5"));
resultsPerPageOptions.add(new NameValueBean("10","10"));
resultsPerPageOptions.add(new NameValueBean("15","15"));
request.setAttribute("resultsPerPageOptions", resultsPerPageOptions);
int firstPageNo = 1, currentPageNo;
currentPageNo = (Integer) (request.getSession().getAttribute("pageNum"));
if (request.getParameter("firstPageNum") != null)
{
firstPageNo = Integer.parseInt(request.getParameter("firstPageNum"));
}
else
{
if (currentPageNo % 5 == 0)
{
firstPageNo = currentPageNo - 4;
}
else
{
firstPageNo = currentPageNo - (currentPageNo % 5 - 1);
}
}
if (firstPageNo < 5)
{
firstPageNo = 1;
}
request.setAttribute("firstPageNum", firstPageNo);
request.setAttribute("numOfPageNums", 5);
if ((firstPageNo + 4) > (Integer) (request.getSession().getAttribute("totalPages")))
{
request.setAttribute("lastPageNum", (Integer) (request.getSession()
.getAttribute("totalPages")));
}
else
{
request.setAttribute("lastPageNum", firstPageNo + 4);
}
return saveQueryForm;
}
/**
* @param maxRecords
* @param totalRecords
* @return
*/
private int getTotalPages(int maxRecords,
int totalRecords)
{
int totalPages=0;
totalPages = totalRecords % maxRecords == 0
? totalRecords / maxRecords
: (totalRecords / maxRecords) + 1;
return totalPages;
}
private int getTotalRecords(HttpServletRequest request, String requestFor, int matchingUsersCount)
{
int totalRecords=0;
if(requestFor!=null && request.getSession().getAttribute(Constants.TOTAL_RESULTS)!=null)
{
totalRecords=(Integer)request.getSession().getAttribute(Constants.TOTAL_RESULTS);
}
else
{
totalRecords=matchingUsersCount;
}
return totalRecords;
}
private ActionForward setActionForward(ActionMapping actionMapping, String pageOf)
{
ActionForward actionForward;
actionForward = actionMapping.findForward(Constants.SUCCESS);
if(pageOf!=null)
{
actionForward = actionMapping.findForward(pageOf);
}
return actionForward;
}
private void removeAttributesFromSession(HttpSession session)
{
session.removeAttribute(Constants.SELECTED_COLUMN_META_DATA);
session.removeAttribute(Constants.SAVE_GENERATED_SQL);
session.removeAttribute(Constants.SAVE_TREE_NODE_LIST);
session.removeAttribute(Constants.ID_NODES_MAP);
session.removeAttribute(Constants.MAIN_ENTITY_MAP);
session.removeAttribute(Constants.EXPORT_DATA_LIST);
session.removeAttribute(Constants.ENTITY_IDS_MAP);
session.removeAttribute(DAGConstant.TQUIMap);
}
private void setQueryCollectionToSaveQueryForm(SaveQueryForm saveQueryForm, String pageOf,
Collection<IParameterizedQuery> authorizedQueryCollection,
Collection<IParameterizedQuery> sharedQueryCollection)
{
if(pageOf !=null && (Constants.PUBLIC_QUERY_PROTECTION_GROUP.equals(pageOf)||
Constants.PUBLIC_QUERIES_FOR_WORKFLOW.equals(pageOf)))
{
saveQueryForm.setParameterizedQueryCollection(sharedQueryCollection);
}
else
{
saveQueryForm.setParameterizedQueryCollection(authorizedQueryCollection);
}
}
private Collection<IParameterizedQuery> getMaxRecord(Collection<IParameterizedQuery> queries,HttpServletRequest request)
{
Collection<IParameterizedQuery> coll = new ArrayList<IParameterizedQuery>();
int maxRec = (Integer) request.getSession().getAttribute(Constants.RESULTS_PER_PAGE);
int strartIndex = (Integer) request.getSession().getAttribute("startIndex");
IParameterizedQuery arr[] = new IParameterizedQuery[queries.size()];
queries.toArray(arr);
for (int i=0;i<maxRec;i++)
{
if((i+strartIndex)==arr.length)
break;
else
coll.add(((IParameterizedQuery)arr[i+strartIndex]));
}
return coll;
}
private int getRecordsPerPage(HttpServletRequest request, String requestFor)
{
Object recordsPerPageObj=getSessionAttribute(request,Constants.RESULTS_PER_PAGE);
int maxRecords;
if(recordsPerPageObj!=null && requestFor!=null)
{
maxRecords=Integer.parseInt(recordsPerPageObj.toString());
}
else
{
maxRecords=10;
}
return maxRecords;
}
private int getPageNumber(HttpServletRequest request, String requestFor)
{
Object pageNumObj=getSessionAttribute(request,Constants.PAGE_NUMBER);
int pageNum=0;
if(pageNumObj!=null && requestFor!=null)
{
pageNum=Integer.parseInt(pageNumObj.toString());
}
else
{
pageNum=1;
}
return pageNum;
}
private Object getSessionAttribute(HttpServletRequest request, String attributeName)
{
Object object=null;
if(request!=null)
{
object=request.getParameter(attributeName);
if(object==null)
{
object=request.getAttribute(attributeName);
if(object==null)
{
object=request.getSession().getAttribute(attributeName);
}
}
}
return object;
}
/**
* this function returns the csmUtility class
* @return
*/
public static CsmUtility getDefaultCsmUtility()
{
return (CsmUtility)Utility.getObject(Variables.csmUtility);
}
public void populateGrid(HttpServletRequest request,Collection<IParameterizedQuery> queryColletion)
{
request.setAttribute("identifierFieldIndex",3);
final List<Object[]> attributesList = new ArrayList<Object[]>();
Object[] attributes = null;
for (IParameterizedQuery query : queryColletion) {
attributes = new Object[4];
if (query != null) {
if (query.getName() != null) {
attributes[1] = query.getName();
} else {
attributes[1] = "";
}
attributes[2] = query.getType();
attributes[3] = query.getId().toString();
}
attributesList.add(attributes);
}
request.setAttribute("msgBoardItemList", CiderUtility
.getmyData(attributesList));
List<String> columnList = new ArrayList<String>();
columnList.add(" ");
columnList.add("Query Title");
columnList.add("Query Type");
columnList.add("identifier");
request.setAttribute("columns", edu.wustl.cider.util.global.Utility.getcolumns(columnList));
request.setAttribute("colWidth", "\"4,80,16,0\"");
request.setAttribute("isWidthInPercent", true);
request.setAttribute("colTypes", "\"ch,str,str,int\"");
request.setAttribute("colDataTypes", "\"ch,txt,txt,ro\"");
}
}
| removed unused
SVN-Revision: 6052
| WEB-INF/src/edu/wustl/query/action/RetrieveQueryAction.java | removed unused | <ide><path>EB-INF/src/edu/wustl/query/action/RetrieveQueryAction.java
<ide> public int setSharedQueryCount(SessionDataBean dataBean) throws CSObjectNotFoundException, CSException
<ide> {
<ide>
<del> Collection<IParameterizedQuery> parameterizedQueryCollection=HibernateUtility
<del> .executeHQL(HibernateUtility.GET_PARAMETERIZED_QUERIES_DETAILS);
<ide> Collection<IParameterizedQuery> authorizedQueryCollection = new ArrayList<IParameterizedQuery>();
<ide> Collection<IParameterizedQuery> sharedQueryCollection = new ArrayList<IParameterizedQuery>();
<ide> CsmUtility csmUtility=getDefaultCsmUtility();
<ide> csmUtility.checkExecuteQueryPrivilege( authorizedQueryCollection, sharedQueryCollection,dataBean);
<ide>
<del> if(parameterizedQueryCollection!=null)
<add> if(sharedQueryCollection!=null)
<ide> {
<ide> return sharedQueryCollection.size();
<ide> } |
|
Java | apache-2.0 | be652c4848210c9eaca92c2a08f0b4d4d844b56e | 0 | bhecquet/seleniumRobot,bhecquet/seleniumRobot,bhecquet/seleniumRobot | /**
* Orignal work: Copyright 2015 www.seleniumtests.com
* Modified work: Copyright 2016 www.infotel.com
* Copyright 2017-2019 B.Hecquet
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.seleniumtests.browserfactory;
import java.io.File;
import org.openqa.selenium.MutableCapabilities;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import com.seleniumtests.driver.BrowserType;
import com.seleniumtests.driver.DriverConfig;
import com.seleniumtests.driver.DriverMode;
import io.appium.java_client.remote.MobileCapabilityType;
public abstract class IMobileCapabilityFactory extends ICapabilitiesFactory {
public IMobileCapabilityFactory(DriverConfig webDriverConfig) {
super(webDriverConfig);
}
protected abstract String getAutomationName();
protected abstract MutableCapabilities getSystemSpecificCapabilities();
protected abstract MutableCapabilities getBrowserSpecificCapabilities();
@Override
public MutableCapabilities createCapabilities() {
String app = webDriverConfig.getApp().trim();
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(MobileCapabilityType.AUTOMATION_NAME, getAutomationName());
if (app != null && !"".equals(app.trim())) {
if (webDriverConfig.isFullReset()) {
capabilities.setCapability(MobileCapabilityType.FULL_RESET, true);
} else {
capabilities.setCapability(MobileCapabilityType.FULL_RESET, false);
}
}
// Set up version and device name else appium server would pick the only available emulator/device
// Both of these are ignored for android for now
capabilities.setCapability(MobileCapabilityType.PLATFORM_NAME, webDriverConfig.getPlatform());
capabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, webDriverConfig.getMobilePlatformVersion());
capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, webDriverConfig.getDeviceName());
capabilities.setCapability(MobileCapabilityType.NEW_COMMAND_TIMEOUT, webDriverConfig.getNewCommandTimeout());
// in case app has not been specified for cloud provider
if (capabilities.getCapability(MobileCapabilityType.APP) == null && app != null && !app.isEmpty()) {
// in case of local file, give absolute path to file. For remote files (e.g: http://myapp.apk), it will be transmitted as is
if (new File(app).isFile()) {
app = new File(app).getAbsolutePath();
}
capabilities.setCapability(MobileCapabilityType.APP, app.replace("\\", "/"));
}
// do not configure application and browser as they are mutualy exclusive
if (app == null || app.isEmpty() && webDriverConfig.getBrowserType() != BrowserType.NONE) {
capabilities.setCapability(CapabilityType.BROWSER_NAME, webDriverConfig.getBrowserType().toString().toLowerCase());
capabilities.merge(getBrowserSpecificCapabilities());
} else {
capabilities.setCapability(CapabilityType.BROWSER_NAME, "");
}
// add node tags
if (webDriverConfig.getNodeTags().size() > 0 && webDriverConfig.getMode() == DriverMode.GRID) {
capabilities.setCapability(SeleniumRobotCapabilityType.NODE_TAGS, webDriverConfig.getNodeTags());
}
// add OS specific capabilities
capabilities.merge(getSystemSpecificCapabilities());
return capabilities;
}
}
| core/src/main/java/com/seleniumtests/browserfactory/IMobileCapabilityFactory.java | /**
* Orignal work: Copyright 2015 www.seleniumtests.com
* Modified work: Copyright 2016 www.infotel.com
* Copyright 2017-2019 B.Hecquet
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.seleniumtests.browserfactory;
import java.io.File;
import org.openqa.selenium.MutableCapabilities;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import com.seleniumtests.driver.BrowserType;
import com.seleniumtests.driver.DriverConfig;
import com.seleniumtests.driver.DriverMode;
import io.appium.java_client.remote.MobileCapabilityType;
public abstract class IMobileCapabilityFactory extends ICapabilitiesFactory {
public IMobileCapabilityFactory(DriverConfig webDriverConfig) {
super(webDriverConfig);
}
protected abstract String getAutomationName();
protected abstract MutableCapabilities getSystemSpecificCapabilities();
protected abstract MutableCapabilities getBrowserSpecificCapabilities();
@Override
public MutableCapabilities createCapabilities() {
String app = webDriverConfig.getApp().trim();
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(MobileCapabilityType.AUTOMATION_NAME, getAutomationName());
if (app != null && !"".equals(app.trim())) {
if (webDriverConfig.isFullReset()) {
capabilities.setCapability(MobileCapabilityType.FULL_RESET, "true");
} else {
capabilities.setCapability(MobileCapabilityType.FULL_RESET, "false");
}
}
// Set up version and device name else appium server would pick the only available emulator/device
// Both of these are ignored for android for now
capabilities.setCapability(MobileCapabilityType.PLATFORM_NAME, webDriverConfig.getPlatform());
capabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, webDriverConfig.getMobilePlatformVersion());
capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, webDriverConfig.getDeviceName());
capabilities.setCapability(MobileCapabilityType.NEW_COMMAND_TIMEOUT, webDriverConfig.getNewCommandTimeout());
// in case app has not been specified for cloud provider
if (capabilities.getCapability(MobileCapabilityType.APP) == null && app != null && !app.isEmpty()) {
// in case of local file, give absolute path to file. For remote files (e.g: http://myapp.apk), it will be transmitted as is
if (new File(app).isFile()) {
app = new File(app).getAbsolutePath();
}
capabilities.setCapability(MobileCapabilityType.APP, app.replace("\\", "/"));
}
// do not configure application and browser as they are mutualy exclusive
if (app == null || app.isEmpty() && webDriverConfig.getBrowserType() != BrowserType.NONE) {
capabilities.setCapability(CapabilityType.BROWSER_NAME, webDriverConfig.getBrowserType().toString().toLowerCase());
capabilities.merge(getBrowserSpecificCapabilities());
} else {
capabilities.setCapability(CapabilityType.BROWSER_NAME, "");
}
// add node tags
if (webDriverConfig.getNodeTags().size() > 0 && webDriverConfig.getMode() == DriverMode.GRID) {
capabilities.setCapability(SeleniumRobotCapabilityType.NODE_TAGS, webDriverConfig.getNodeTags());
}
// add OS specific capabilities
capabilities.merge(getSystemSpecificCapabilities());
return capabilities;
}
}
| issue #381: changed "fullReset" value | core/src/main/java/com/seleniumtests/browserfactory/IMobileCapabilityFactory.java | issue #381: changed "fullReset" value | <ide><path>ore/src/main/java/com/seleniumtests/browserfactory/IMobileCapabilityFactory.java
<ide>
<ide> if (app != null && !"".equals(app.trim())) {
<ide> if (webDriverConfig.isFullReset()) {
<del> capabilities.setCapability(MobileCapabilityType.FULL_RESET, "true");
<add> capabilities.setCapability(MobileCapabilityType.FULL_RESET, true);
<ide> } else {
<del> capabilities.setCapability(MobileCapabilityType.FULL_RESET, "false");
<add> capabilities.setCapability(MobileCapabilityType.FULL_RESET, false);
<ide> }
<ide> }
<ide> |
|
JavaScript | apache-2.0 | 9d789cf1b1a9c661c3c8858a2170eb5e57571306 | 0 | Brightspace/eslint-config-brightspace |
// nr = not as per eslint:recommended
module.exports = {
"rules": {
"comma-spacing": 2, // nr
"eol-last": 2, // nr
"eqeqeq": 2, // nr
"indent": [2, "tab", { "SwitchCase": 1 }], // nr
"new-parens": 2, // nr
"no-debugger": 2,
"no-dupe-args": 2,
"no-dupe-keys": 2,
"no-duplicate-case": 2,
"no-ex-assign": 2,
"no-fallthrough": 2,
"no-invalid-this": 2, // nr
"no-multiple-empty-lines": [2, {"max": 1}], // nr
"no-trailing-spaces": 2, // nr
"no-undef": 2,
"no-unreachable": 2,
"no-unused-vars": [2, {"vars": "all", "args": "after-used"}],
"prefer-const": 2, // nr
"quotes": [2, "single", "avoid-escape"], // nr
"semi": 2, // nr
"keyword-spacing": 2,
"space-before-blocks": [2, "always"], // nr
"space-before-function-paren": [2, "never"], //nr
"space-in-parens": [2, "never"],
"space-infix-ops": 2, // nr
"strict": [2, "global"], // nr
"valid-typeof": 2
}
};
| common-config.js |
// nr = not as per eslint:recommended
module.exports = {
"rules": {
"comma-spacing": 2, // nr
"eol-last": 2, // nr
"eqeqeq": 2, // nr
"indent": [2, "tab", { "SwitchCase": 1 }], // nr
"new-parens": 2, // nr
"no-debugger": 2,
"no-dupe-args": 2,
"no-dupe-keys": 2,
"no-duplicate-case": 2,
"no-ex-assign": 2,
"no-fallthrough": 2,
"no-invalid-this": 2, // nr
"no-multiple-empty-lines": [2, {"max": 1}], // nr
"no-trailing-spaces": 2, // nr
"no-undef": 2,
"no-unreachable": 2,
"no-unused-vars": [2, {"vars": "all", "args": "after-used"}],
"prefer-const": 2, // nr
"quotes": [2, "single", "avoid-escape"], // nr
"semi": 2, // nr
"keyword-spacing": 2,
"space-before-blocks": [2, "always"], // nr
"space-before-function-paren": [2, "never"], //nr
"space-infix-ops": 2, // nr
"strict": [2, "global"], // nr
"valid-typeof": 2
}
};
| add space-in-parens error
| common-config.js | add space-in-parens error | <ide><path>ommon-config.js
<ide> "eqeqeq": 2, // nr
<ide> "indent": [2, "tab", { "SwitchCase": 1 }], // nr
<ide> "new-parens": 2, // nr
<del> "no-debugger": 2,
<add> "no-debugger": 2,
<ide> "no-dupe-args": 2,
<ide> "no-dupe-keys": 2,
<ide> "no-duplicate-case": 2,
<ide> "semi": 2, // nr
<ide> "keyword-spacing": 2,
<ide> "space-before-blocks": [2, "always"], // nr
<del> "space-before-function-paren": [2, "never"], //nr
<add> "space-before-function-paren": [2, "never"], //nr
<add> "space-in-parens": [2, "never"],
<ide> "space-infix-ops": 2, // nr
<ide> "strict": [2, "global"], // nr
<ide> "valid-typeof": 2 |
|
JavaScript | mit | b66acff5cadbdfb84b95bc763154a376433dafb7 | 0 | unexpectedjs/unexpected,alexjeffburke/unexpected,alexjeffburke/unexpected | /*!
* Copyright (c) 2013 Sune Simonsen <[email protected]>
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the 'Software'), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}(g.weknowhow || (g.weknowhow = {})).expect = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
module.exports = function AssertionString(text) {
this.text = text;
};
},{}],2:[function(require,module,exports){
var createStandardErrorMessage = require(6);
var utils = require(19);
var magicpen = require(44);
var extend = utils.extend;
var leven = require(40);
var makePromise = require(11);
var addAdditionalPromiseMethods = require(4);
var isPendingPromise = require(9);
var oathbreaker = require(13);
var UnexpectedError = require(3);
var notifyPendingPromise = require(12);
var defaultDepth = require(8);
var createWrappedExpectProto = require(7);
var AssertionString = require(1);
var throwIfNonUnexpectedError = require(16);
var makeDiffResultBackwardsCompatible = require(10);
function isAssertionArg(arg) {
return arg.type.is('assertion');
}
function Context(unexpected) {
this.expect = unexpected;
this.level = 0;
}
Context.prototype.child = function () {
var child = Object.create(this);
child.level++;
return child;
};
var anyType = {
_unexpectedType: true,
name: 'any',
level: 0,
identify: function () {
return true;
},
equal: utils.objectIs,
inspect: function (value, depth, output) {
if (output && output.isMagicPen) {
return output.text(value);
} else {
// Guard against node.js' require('util').inspect eagerly calling .inspect() on objects
return 'type: ' + this.name;
}
},
diff: function (actual, expected, output, diff, inspect) {
return null;
},
typeEqualityCache: {},
is: function (typeOrTypeName) {
var typeName;
if (typeof typeOrTypeName === 'string') {
typeName = typeOrTypeName;
} else {
typeName = typeOrTypeName.name;
}
var cachedValue = this.typeEqualityCache[typeName];
if (typeof cachedValue !== 'undefined') {
return cachedValue;
}
var result = false;
if (this.name === typeName) {
result = true;
} else if (this.baseType) {
result = this.baseType.is(typeName);
}
this.typeEqualityCache[typeName] = result;
return result;
}
};
function Unexpected(options) {
options = options || {};
this.assertions = options.assertions || {};
this.typeByName = options.typeByName || {any: anyType};
this.types = options.types || [anyType];
if (options.output) {
this.output = options.output;
} else {
this.output = magicpen();
this.output.inline = false;
this.output.diff = false;
}
this._outputFormat = options.format || magicpen.defaultFormat;
this.installedPlugins = options.installedPlugins || [];
// Make bound versions of these two helpers up front to save a bit when creating wrapped expects:
var that = this;
this.getType = function (typeName) {
return that.typeByName[typeName] || (that.parent && that.parent.getType(typeName));
};
this.findTypeOf = function (obj) {
return utils.findFirst(that.types || [], function (type) {
return type.identify && type.identify(obj);
}) || (that.parent && that.parent.findTypeOf(obj));
};
this.findTypeOfWithParentType = function (obj, requiredParentType) {
return utils.findFirst(that.types || [], function (type) {
return type.identify && type.identify(obj) && (!requiredParentType || type.is(requiredParentType));
}) || (that.parent && that.parent.findTypeOfWithParentType(obj, requiredParentType));
};
this.findCommonType = function (a, b) {
var aAncestorIndex = {};
var current = this.findTypeOf(a);
while (current) {
aAncestorIndex[current.name] = current;
current = current.baseType;
}
current = this.findTypeOf(b);
while (current) {
if (aAncestorIndex[current.name]) {
return current;
}
current = current.baseType;
}
};
this._wrappedExpectProto = createWrappedExpectProto(this);
}
var OR = {};
function getOrGroups(expectations) {
var orGroups = [[]];
expectations.forEach(function (expectation) {
if (expectation === OR) {
orGroups.push([]);
} else {
orGroups[orGroups.length - 1].push(expectation);
}
});
return orGroups;
}
function evaluateGroup(unexpected, context, subject, orGroup) {
return orGroup.map(function (expectation) {
var args = Array.prototype.slice.call(expectation);
args.unshift(subject);
return {
expectation: args,
promise: makePromise(function () {
if (typeof args[1] === 'function') {
if (args.length > 2) {
throw new Error('expect.it(<function>) does not accept additional arguments');
} else {
// expect.it(function (value) { ... })
return args[1](args[0]);
}
} else {
return unexpected._expect(context.child(), args);
}
})
};
});
}
function writeGroupEvaluationsToOutput(output, groupEvaluations) {
var hasOrClauses = groupEvaluations.length > 1;
var hasAndClauses = groupEvaluations.some(function (groupEvaluation) {
return groupEvaluation.length > 1;
});
groupEvaluations.forEach(function (groupEvaluation, i) {
if (i > 0) {
if (hasAndClauses) {
output.nl();
} else {
output.sp();
}
output.jsComment('or').nl();
}
var groupFailed = false;
groupEvaluation.forEach(function (evaluation, j) {
if (j > 0) {
output.jsComment(' and').nl();
}
var isRejected = evaluation.promise.isRejected();
if (isRejected && !groupFailed) {
groupFailed = true;
var err = evaluation.promise.reason();
if (hasAndClauses || hasOrClauses) {
output.error('⨯ ');
}
output.block(function (output) {
output.append(err.getErrorMessage(output));
});
} else {
if (isRejected) {
output.error('⨯ ');
} else {
output.success('✓ ');
}
var expectation = evaluation.expectation;
output.block(function (output) {
var subject = expectation[0];
var subjectOutput = function (output) {
output.appendInspected(subject);
};
var args = expectation.slice(2);
var argsOutput = args.map(function (arg) {
return function (output) {
output.appendInspected(arg);
};
});
var testDescription = expectation[1];
createStandardErrorMessage(output, subjectOutput, testDescription, argsOutput, {
subject: subject
});
});
}
});
});
}
function createExpectIt(unexpected, expectations) {
var orGroups = getOrGroups(expectations);
function expectIt(subject, context) {
context = (
context &&
typeof context === 'object' &&
context instanceof Context
) ? context : new Context(unexpected);
var groupEvaluations = [];
var promises = [];
orGroups.forEach(function (orGroup) {
var evaluations = evaluateGroup(unexpected, context, subject, orGroup);
evaluations.forEach(function (evaluation) {
promises.push(evaluation.promise);
});
groupEvaluations.push(evaluations);
});
return oathbreaker(makePromise.settle(promises).then(function () {
groupEvaluations.forEach(function (groupEvaluation) {
groupEvaluation.forEach(function (evaluation) {
if (evaluation.promise.isRejected() && evaluation.promise.reason().errorMode === 'bubbleThrough') {
throw evaluation.promise.reason();
}
});
});
if (!groupEvaluations.some(function (groupEvaluation) {
return groupEvaluation.every(function (evaluation) {
return evaluation.promise.isFulfilled();
});
})) {
unexpected.fail(function (output) {
writeGroupEvaluationsToOutput(output, groupEvaluations);
});
}
}));
}
expectIt._expectIt = true;
expectIt._expectations = expectations;
expectIt._OR = OR;
expectIt.and = function () {
var copiedExpectations = expectations.slice();
copiedExpectations.push(arguments);
return createExpectIt(unexpected, copiedExpectations);
};
expectIt.or = function () {
var copiedExpectations = expectations.slice();
copiedExpectations.push(OR, arguments);
return createExpectIt(unexpected, copiedExpectations);
};
return expectIt;
}
Unexpected.prototype.it = function () { // ...
return createExpectIt(this, [arguments]);
};
Unexpected.prototype.equal = function (actual, expected, depth, seen) {
var that = this;
depth = typeof depth === 'number' ? depth : 100;
if (depth <= 0) {
// detect recursive loops in the structure
seen = seen || [];
if (seen.indexOf(actual) !== -1) {
throw new Error('Cannot compare circular structures');
}
seen.push(actual);
}
return this.findCommonType(actual, expected).equal(actual, expected, function (a, b) {
return that.equal(a, b, depth - 1, seen);
});
};
Unexpected.prototype.inspect = function (obj, depth, outputOrFormat) {
var seen = [];
var that = this;
var printOutput = function (obj, currentDepth, output) {
var objType = that.findTypeOf(obj);
if (currentDepth <= 0 && objType.is('object') && !objType.is('expect.it')) {
return output.text('...');
}
seen = seen || [];
if (seen.indexOf(obj) !== -1) {
return output.text('[Circular]');
}
return objType.inspect(obj, currentDepth, output, function (v, childDepth) {
output = output.clone();
seen.push(obj);
if (typeof childDepth === 'undefined') {
childDepth = currentDepth - 1;
}
output = printOutput(v, childDepth, output) || output;
seen.pop();
return output;
});
};
var output = typeof outputOrFormat === 'string' ? this.createOutput(outputOrFormat) : outputOrFormat;
output = output || this.createOutput();
return printOutput(obj, typeof depth === 'number' ? depth : defaultDepth, output) || output;
};
Unexpected.prototype.expandTypeAlternations = function (assertion) {
var that = this;
function createPermutations(args, i) {
if (i === args.length) {
return [];
}
var result = [];
args[i].forEach(function (arg) {
var tails = createPermutations(args, i + 1);
if (tails.length) {
tails.forEach(function (tail) {
result.push([arg].concat(tail));
});
} else if (arg.type.is('assertion')) {
result.push([
{ type: arg.type, minimum: 1, maximum: 1 },
{ type: that.getType('any'), minimum: 0, maximum: Infinity }
]);
result.push([
{ type: that.getType('expect.it'), minimum: 1, maximum: 1 }
]);
if (arg.minimum === 0) { // <assertion?>
result.push([]);
}
} else {
result.push([arg]);
}
});
return result;
}
var result = [];
assertion.subject.forEach(function (subjectRequirement) {
if (assertion.args.length) {
createPermutations(assertion.args, 0).forEach(function (args) {
result.push(extend({}, assertion, {
subject: subjectRequirement,
args: args
}));
});
} else {
result.push(extend({}, assertion, {
subject: subjectRequirement,
args: []
}));
}
});
return result;
};
Unexpected.prototype.parseAssertion = function (assertionString) {
var that = this;
var tokens = [];
var nextIndex = 0;
function parseTypeToken(typeToken) {
return typeToken.split('|').map(function (typeDeclaration) {
var matchNameAndOperator = typeDeclaration.match(/^([a-z_](?:|[a-z0-9_.-]*[_a-z0-9]))([+*?]|)$/i);
if (!matchNameAndOperator) {
throw new SyntaxError('Cannot parse type declaration:' + typeDeclaration);
}
var type = that.getType(matchNameAndOperator[1]);
if (!type) {
throw new Error('Unknown type: ' + matchNameAndOperator[1] + ' in ' + assertionString);
}
var operator = matchNameAndOperator[2];
return {
minimum: !operator || operator === '+' ? 1 : 0,
maximum: operator === '*' || operator === '+' ? Infinity : 1,
type: type
};
});
}
function hasVarargs(types) {
return types.some(function (type) {
return type.minimum !== 1 || type.maximum !== 1;
});
}
assertionString.replace(/\s*<((?:[a-z_](?:|[a-z0-9_.-]*[_a-z0-9])[?*+]?)(?:\|(?:[a-z_](?:|[a-z0-9_.-]*[_a-z0-9])[?*+]?))*)>|\s*([^<]+)/ig, function ($0, $1, $2, index) {
if (index !== nextIndex) {
throw new SyntaxError('Cannot parse token at index ' + nextIndex + ' in ' + assertionString);
}
if ($1) {
tokens.push(parseTypeToken($1));
} else {
tokens.push($2.trim());
}
nextIndex += $0.length;
});
var assertion;
if (tokens.length === 1 && typeof tokens[0] === 'string') {
assertion = {
subject: parseTypeToken('any'),
assertion: tokens[0],
args: [parseTypeToken('any*')]
};
} else {
assertion = {
subject: tokens[0],
assertion: tokens[1],
args: tokens.slice(2)
};
}
if (!Array.isArray(assertion.subject)) {
throw new SyntaxError('Missing subject type in ' + assertionString);
}
if (typeof assertion.assertion !== 'string') {
throw new SyntaxError('Missing assertion in ' + assertionString);
}
if (hasVarargs(assertion.subject)) {
throw new SyntaxError('The subject type cannot have varargs: ' + assertionString);
}
if (assertion.args.some(function (arg) { return typeof arg === 'string'; })) {
throw new SyntaxError('Only one assertion string is supported (see #225)');
}
if (assertion.args.slice(0, -1).some(hasVarargs)) {
throw new SyntaxError('Only the last argument type can have varargs: ' + assertionString);
}
if ([assertion.subject].concat(assertion.args.slice(0, -1)).some(function (argRequirements) {
return argRequirements.some(function (argRequirement) {
return argRequirement.type.is('assertion');
});
})) {
throw new SyntaxError('Only the last argument type can be <assertion>: ' + assertionString);
}
var lastArgRequirements = assertion.args[assertion.args.length - 1] || [];
var assertionRequirements = lastArgRequirements.filter(function (argRequirement) {
return argRequirement.type.is('assertion');
});
if (assertionRequirements.length > 0 && lastArgRequirements.length > 1) {
throw new SyntaxError('<assertion> cannot be alternated with other types: ' + assertionString);
}
if (assertionRequirements.some(function (argRequirement) {
return argRequirement.maximum !== 1;
})) {
throw new SyntaxError('<assertion+> and <assertion*> are not allowed: ' + assertionString);
}
return this.expandTypeAlternations(assertion);
};
var placeholderSplitRegexp = /(\{(?:\d+)\})/g;
var placeholderRegexp = /\{(\d+)\}/;
Unexpected.prototype.fail = function (arg) {
if (arg instanceof UnexpectedError) {
arg._hasSerializedErrorMessage = false;
throw arg;
}
if (utils.isError(arg)) {
throw arg;
}
var error = new UnexpectedError(this.expect);
if (typeof arg === 'function') {
error.errorMode = 'bubble';
error.output = arg;
} else if (arg && typeof arg === 'object') {
if (typeof arg.message !== 'undefined') {
error.errorMode = 'bubble';
}
error.output = function (output) {
if (typeof arg.message !== 'undefined') {
if (arg.message.isMagicPen) {
output.append(arg.message);
} else if (typeof arg.message === 'function') {
arg.message.call(output, output);
} else {
output.text(String(arg.message));
}
} else {
output.error('Explicit failure');
}
};
var expect = this.expect;
Object.keys(arg).forEach(function (key) {
var value = arg[key];
if (key === 'diff') {
if (typeof value === 'function' && this.parent) {
error.createDiff = function (output, diff, inspect, equal) {
var childOutput = expect.createOutput(output.format);
childOutput.inline = output.inline;
childOutput.output = output.output;
return value(childOutput, function diff(actual, expected) {
return expect.diff(actual, expected, childOutput.clone());
}, function inspect(v, depth) {
return childOutput.clone().appendInspected(v, (depth || defaultDepth) - 1);
}, function (actual, expected) {
return expect.equal(actual, expected);
});
};
} else {
error.createDiff = value;
}
} else if (key !== 'message') {
error[key] = value;
}
}, this);
} else {
var placeholderArgs;
if (arguments.length > 0) {
placeholderArgs = new Array(arguments.length - 1);
for (var i = 1 ; i < arguments.length ; i += 1) {
placeholderArgs[i - 1] = arguments[i];
}
}
error.errorMode = 'bubble';
error.output = function (output) {
var message = arg ? String(arg) : 'Explicit failure';
var tokens = message.split(placeholderSplitRegexp);
tokens.forEach(function (token) {
var match = placeholderRegexp.exec(token);
if (match) {
var index = match[1];
if (index in placeholderArgs) {
var placeholderArg = placeholderArgs[index];
if (placeholderArg && placeholderArg.isMagicPen) {
output.append(placeholderArg);
} else {
output.appendInspected(placeholderArg);
}
} else {
output.text(match[0]);
}
} else {
output.error(token);
}
});
};
}
throw error;
};
function compareSpecificities(a, b) {
for (var i = 0; i < Math.min(a.length, b.length); i += 1) {
var c = b[i] - a[i];
if (c !== 0) {
return c;
}
}
return b.length - a.length;
}
function calculateAssertionSpecificity(assertion) {
return [assertion.subject.type.level].concat(assertion.args.map(function (argRequirement) {
var bonus = argRequirement.minimum === 1 && argRequirement.maximum === 1 ?
0.5 : 0;
return bonus + argRequirement.type.level;
}));
}
Unexpected.prototype.addAssertion = function (patternOrPatterns, handler, childUnexpected) {
var maxArguments;
if (typeof childUnexpected === 'object') {
maxArguments = 3;
} else {
maxArguments = 2;
}
if (arguments.length > maxArguments || typeof handler !== 'function' || (typeof patternOrPatterns !== 'string' && !Array.isArray(patternOrPatterns))) {
var errorMessage = "Syntax: expect.addAssertion(<string|array[string]>, function (expect, subject, ...) { ... });";
if ((typeof handler === 'string' || Array.isArray(handler)) && typeof arguments[2] === 'function') {
errorMessage +=
'\nAs of Unexpected 10, the syntax for adding assertions that apply only to specific\n' +
'types has changed. See http://unexpected.js.org/api/addAssertion/';
}
throw new Error(errorMessage);
}
var patterns = (Array.isArray(patternOrPatterns) ? patternOrPatterns : [patternOrPatterns]);
patterns.forEach(function (pattern) {
if (typeof pattern !== 'string' || pattern === '') {
throw new Error('Assertion patterns must be a non-empty string');
} else {
if (pattern !== pattern.trim()) {
throw new Error("Assertion patterns can't start or end with whitespace:\n\n " + JSON.stringify(pattern));
}
}
});
var that = this;
var assertions = this.assertions;
var defaultValueByFlag = {};
var assertionHandlers = [];
var maxNumberOfArgs = 0;
patterns.forEach(function (pattern) {
var assertionDeclarations = that.parseAssertion(pattern);
assertionDeclarations.forEach(function (assertionDeclaration) {
ensureValidUseOfParenthesesOrBrackets(assertionDeclaration.assertion);
var expandedAssertions = expandAssertion(assertionDeclaration.assertion);
expandedAssertions.forEach(function (expandedAssertion) {
Object.keys(expandedAssertion.flags).forEach(function (flag) {
defaultValueByFlag[flag] = false;
});
maxNumberOfArgs = Math.max(maxNumberOfArgs, assertionDeclaration.args.reduce(function (previous, argDefinition) {
return previous + (argDefinition.maximum === null ? Infinity : argDefinition.maximum);
}, 0));
assertionHandlers.push({
handler: handler,
alternations: expandedAssertion.alternations,
flags: expandedAssertion.flags,
subject: assertionDeclaration.subject,
args: assertionDeclaration.args,
testDescriptionString: expandedAssertion.text,
declaration: pattern,
unexpected: childUnexpected
});
});
});
});
if (handler.length - 2 > maxNumberOfArgs) {
throw new Error('The provided assertion handler takes ' + (handler.length - 2) + ' parameters, but the type signature specifies a maximum of ' + maxNumberOfArgs + ':\n\n ' + JSON.stringify(patterns));
}
assertionHandlers.forEach(function (handler) {
// Make sure that all flags are defined.
handler.flags = extend({}, defaultValueByFlag, handler.flags);
var assertionHandlers = assertions[handler.testDescriptionString];
handler.specificity = calculateAssertionSpecificity(handler);
if (!assertionHandlers) {
assertions[handler.testDescriptionString] = [handler];
} else {
var i = 0;
while (i < assertionHandlers.length && compareSpecificities(handler.specificity, assertionHandlers[i].specificity) > 0) {
i += 1;
}
assertionHandlers.splice(i, 0, handler);
}
});
return this.expect; // for chaining
};
Unexpected.prototype.addType = function (type, childUnexpected) {
var that = this;
var baseType;
if (typeof type.name !== 'string' || !/^[a-z_](?:|[a-z0-9_.-]*[_a-z0-9])$/i.test(type.name)) {
throw new Error('A type must be given a non-empty name and must match ^[a-z_](?:|[a-z0-9_.-]*[_a-z0-9])$');
}
if (typeof type.identify !== 'function' && type.identify !== false) {
throw new Error('Type ' + type.name + ' must specify an identify function or be declared abstract by setting identify to false');
}
if (this.typeByName[type.name]) {
throw new Error('The type with the name ' + type.name + ' already exists');
}
if (type.base) {
baseType = this.getType(type.base);
if (!baseType) {
throw new Error('Unknown base type: ' + type.base);
}
} else {
baseType = anyType;
}
var extendedBaseType = Object.create(baseType);
extendedBaseType.inspect = function (value, depth, output) {
if (!output || !output.isMagicPen) {
throw new Error('You need to pass the output to baseType.inspect() as the third parameter');
}
return baseType.inspect(value, depth, output, function (value, depth) {
return output.clone().appendInspected(value, depth);
});
};
extendedBaseType.diff = function (actual, expected, output) {
if (!output || !output.isMagicPen) {
throw new Error('You need to pass the output to baseType.diff() as the third parameter');
}
return makeDiffResultBackwardsCompatible(baseType.diff(actual, expected,
output.clone(),
function (actual, expected) {
return that.diff(actual, expected, output.clone());
},
function (value, depth) {
return output.clone().appendInspected(value, depth);
},
that.equal.bind(that)));
};
extendedBaseType.equal = function (actual, expected) {
return baseType.equal(actual, expected, that.equal.bind(that));
};
var extendedType = extend({}, baseType, type, { baseType: extendedBaseType });
var originalInspect = extendedType.inspect;
extendedType.inspect = function (obj, depth, output, inspect) {
if (arguments.length < 2 || (!output || !output.isMagicPen)) {
return 'type: ' + type.name;
} else if (childUnexpected) {
var childOutput = childUnexpected.createOutput(output.format);
return originalInspect.call(this, obj, depth, childOutput, inspect) || childOutput;
} else {
return originalInspect.call(this, obj, depth, output, inspect) || output;
}
};
if (childUnexpected) {
extendedType.childUnexpected = childUnexpected;
var originalDiff = extendedType.diff;
extendedType.diff = function (actual, expected, output, inspect, diff, equal) {
var childOutput = childUnexpected.createOutput(output.format);
// Make sure that already buffered up output is preserved:
childOutput.output = output.output;
return originalDiff.call(this, actual, expected, childOutput, inspect, diff, equal) || output;
};
}
if (extendedType.identify === false) {
this.types.push(extendedType);
} else {
this.types.unshift(extendedType);
}
extendedType.level = baseType.level + 1;
extendedType.typeEqualityCache = {};
this.typeByName[extendedType.name] = extendedType;
return this.expect;
};
Unexpected.prototype.addStyle = function () { // ...
this.output.addStyle.apply(this.output, arguments);
return this.expect;
};
Unexpected.prototype.installTheme = function () { // ...
this.output.installTheme.apply(this.output, arguments);
return this.expect;
};
function getPluginName(plugin) {
if (typeof plugin === 'function') {
return utils.getFunctionName(plugin);
} else {
return plugin.name;
}
}
Unexpected.prototype.use = function (plugin) {
if ((typeof plugin !== 'function' && (typeof plugin !== 'object' || typeof plugin.installInto !== 'function')) ||
(typeof plugin.name !== 'undefined' && typeof plugin.name !== 'string') ||
(typeof plugin.dependencies !== 'undefined' && !Array.isArray(plugin.dependencies))) {
throw new Error(
'Plugins must be functions or adhere to the following interface\n' +
'{\n' +
' name: <an optional plugin name>,\n' +
' version: <an optional semver version string>,\n' +
' dependencies: <an optional list of dependencies>,\n' +
' installInto: <a function that will update the given expect instance>\n' +
'}'
);
}
var pluginName = getPluginName(plugin);
var existingPlugin = utils.findFirst(this.installedPlugins, function (installedPlugin) {
if (installedPlugin === plugin) {
return true;
} else {
return pluginName && pluginName === getPluginName(installedPlugin);
}
});
if (existingPlugin) {
if (existingPlugin === plugin || (typeof plugin.version !== 'undefined' && plugin.version === existingPlugin.version)) {
// No-op
return this.expect;
} else {
throw new Error("Another instance of the plugin '" + pluginName + "' " +
"is already installed" +
(typeof existingPlugin.version !== 'undefined' ?
' (version ' + existingPlugin.version +
(typeof plugin.version !== 'undefined' ?
', trying to install ' + plugin.version : '') +
')' : '') +
". Please check your node_modules folder for unmet peerDependencies.");
}
}
if (pluginName === 'unexpected-promise') {
throw new Error('The unexpected-promise plugin was pulled into Unexpected as of 8.5.0. This means that the plugin is no longer supported.');
}
if (plugin.dependencies) {
var installedPlugins = this.installedPlugins;
var instance = this.parent;
while (instance) {
Array.prototype.push.apply(installedPlugins, instance.installedPlugins);
instance = instance.parent;
}
var unfulfilledDependencies = plugin.dependencies.filter(function (dependency) {
return !installedPlugins.some(function (plugin) {
return getPluginName(plugin) === dependency;
});
});
if (unfulfilledDependencies.length === 1) {
throw new Error(pluginName + ' requires plugin ' + unfulfilledDependencies[0]);
} else if (unfulfilledDependencies.length > 1) {
throw new Error(pluginName + ' requires plugins ' +
unfulfilledDependencies.slice(0, -1).join(', ') +
' and ' + unfulfilledDependencies[unfulfilledDependencies.length - 1]);
}
}
this.installedPlugins.push(plugin);
if (typeof plugin === 'function') {
plugin(this.expect);
} else {
plugin.installInto(this.expect);
}
return this.expect; // for chaining
};
Unexpected.prototype.withError = function (body, handler) {
return oathbreaker(makePromise(body).caught(function (e) {
throwIfNonUnexpectedError(e);
return handler(e);
}));
};
Unexpected.prototype.installPlugin = Unexpected.prototype.use; // Legacy alias
function installExpectMethods(unexpected) {
var expect = function () { /// ...
return unexpected._expect(new Context(unexpected), arguments);
};
expect.it = unexpected.it.bind(unexpected);
expect.equal = unexpected.equal.bind(unexpected);
expect.inspect = unexpected.inspect.bind(unexpected);
expect.findTypeOf = unexpected.findTypeOf; // Already bound
expect.fail = function () {
try {
unexpected.fail.apply(unexpected, arguments);
} catch (e) {
if (e && e._isUnexpected) {
unexpected.setErrorMessage(e);
}
throw e;
}
};
expect.createOutput = unexpected.createOutput.bind(unexpected);
expect.diff = unexpected.diff.bind(unexpected);
expect.async = unexpected.async.bind(unexpected);
expect.promise = makePromise;
expect.withError = unexpected.withError;
expect.addAssertion = unexpected.addAssertion.bind(unexpected);
expect.addStyle = unexpected.addStyle.bind(unexpected);
expect.installTheme = unexpected.installTheme.bind(unexpected);
expect.addType = unexpected.addType.bind(unexpected);
expect.getType = unexpected.getType;
expect.clone = unexpected.clone.bind(unexpected);
expect.child = unexpected.child.bind(unexpected);
expect.toString = unexpected.toString.bind(unexpected);
expect.assertions = unexpected.assertions;
expect.use = expect.installPlugin = unexpected.use.bind(unexpected);
expect.output = unexpected.output;
expect.outputFormat = unexpected.outputFormat.bind(unexpected);
expect.notifyPendingPromise = notifyPendingPromise;
expect.hook = function (fn) {
unexpected._expect = fn(unexpected._expect.bind(unexpected));
};
// TODO For testing purpose while we don't have all the pieces yet
expect.parseAssertion = unexpected.parseAssertion.bind(unexpected);
return expect;
}
function calculateLimits(items) {
return items.reduce(function (result, item) {
result.minimum += item.minimum;
result.maximum += item.maximum;
return result;
}, { minimum: 0, maximum: 0 });
}
Unexpected.prototype.throwAssertionNotFoundError = function (subject, testDescriptionString, args) {
var candidateHandlers = this.assertions[testDescriptionString];
var that = this;
if (candidateHandlers) {
this.fail({
message: function (output) {
var subjectOutput = function (output) {
output.appendInspected(subject);
};
var argsOutput = function (output) {
output.appendItems(args, ', ');
};
output.append(createStandardErrorMessage(output.clone(), subjectOutput, testDescriptionString, argsOutput)).nl()
.indentLines();
output.i().error('The assertion does not have a matching signature for:').nl()
.indentLines().i().text('<').text(that.findTypeOf(subject).name).text('>').sp().text(testDescriptionString);
args.forEach(function (arg, i) {
output.sp().text('<').text(that.findTypeOf(arg).name).text('>');
});
output
.outdentLines()
.nl()
.i().text('did you mean:')
.indentLines()
.nl();
var assertionDeclarations = Object.keys(candidateHandlers.reduce(function (result, handler) {
result[handler.declaration] = true;
return result;
}, {})).sort();
assertionDeclarations.forEach(function (declaration, i) {
output.nl(i > 0 ? 1 : 0).i().text(declaration);
});
output.outdentLines();
}
});
}
var assertionsWithScore = [];
var assertionStrings = [];
var instance = this;
while (instance) {
Array.prototype.push.apply(assertionStrings, Object.keys(instance.assertions));
instance = instance.parent;
}
function compareAssertions(a, b) {
var aAssertion = that.lookupAssertionRule(subject, a, args);
var bAssertion = that.lookupAssertionRule(subject, b, args);
if (!aAssertion && !bAssertion) {
return 0;
}
if (aAssertion && !bAssertion) {
return -1;
}
if (!aAssertion && bAssertion) {
return 1;
}
return compareSpecificities(aAssertion.specificity, bAssertion.specificity);
}
assertionStrings.forEach(function (assertionString) {
var score = leven(testDescriptionString, assertionString);
assertionsWithScore.push({
assertion: assertionString,
score: score
});
}, this);
var bestMatch = assertionsWithScore.sort(function (a, b) {
var c = a.score - b.score;
if (c !== 0) {
return c;
}
if (a.assertion < b.assertion) {
return -1;
} else {
return 1;
}
}).slice(0, 10).filter(function (assertionsWithScore, i, arr) {
return Math.abs(assertionsWithScore.score - arr[0].score) <= 2;
}).sort(function (a, b) {
var c = compareAssertions(a.assertion, b.assertion);
if (c !== 0) {
return c;
}
return a.score - b.score;
})[0];
this.fail({
errorMode: 'bubbleThrough',
message: function (output) {
output.error("Unknown assertion '").jsString(testDescriptionString)
.error("', did you mean: '").jsString(bestMatch.assertion).error("'");
}
});
};
Unexpected.prototype.lookupAssertionRule = function (subject, testDescriptionString, args, requireAssertionSuffix) {
var that = this;
if (typeof testDescriptionString !== 'string') {
throw new Error('The expect function requires the second parameter to be a string or an expect.it.');
}
var handlers;
var instance = this;
while (instance) {
var instanceHandlers = instance.assertions[testDescriptionString];
if (instanceHandlers) {
handlers = handlers ? handlers.concat(instanceHandlers) : instanceHandlers;
}
instance = instance.parent;
}
if (!handlers) {
return null;
}
var cachedTypes = {};
function findTypeOf(value, key) {
var type = cachedTypes[key];
if (!type) {
type = that.findTypeOf(value);
cachedTypes[key] = type;
}
return type;
}
function matches(value, assertionType, key, relaxed) {
if (assertionType.is('assertion') && typeof value === 'string') {
return true;
}
if (relaxed) {
if (assertionType.identify === false) {
return that.types.some(function (type) {
return type.identify && type.is(assertionType) && type.identify(value);
});
}
return assertionType.identify(value);
} else {
return findTypeOf(value, key).is(assertionType);
}
}
function matchesHandler(handler, relaxed) {
if (!matches(subject, handler.subject.type, 'subject', relaxed)) {
return false;
}
if (requireAssertionSuffix && !handler.args.some(isAssertionArg)) {
return false;
}
var requireArgumentsLength = calculateLimits(handler.args);
if (args.length < requireArgumentsLength.minimum || requireArgumentsLength.maximum < args.length) {
return false;
} else if (args.length === 0 && requireArgumentsLength.maximum === 0) {
return true;
}
var lastRequirement = handler.args[handler.args.length - 1];
return args.every(function (arg, i) {
if (i < handler.args.length - 1) {
return matches(arg, handler.args[i].type, i, relaxed);
} else {
return matches(arg, lastRequirement.type, i, relaxed);
}
});
}
var j, handler;
for (j = 0; j < handlers.length; j += 1) {
handler = handlers[j];
if (matchesHandler(handler)) {
return handler;
}
}
for (j = 0; j < handlers.length; j += 1) {
handler = handlers[j];
if (matchesHandler(handler, true)) {
return handler;
}
}
return null;
};
function makeExpectFunction(unexpected) {
var expect = installExpectMethods(unexpected);
unexpected.expect = expect;
return expect;
}
Unexpected.prototype.setErrorMessage = function (err) {
err.serializeMessage(this.outputFormat());
};
Unexpected.prototype._expect = function expect(context, args) {
var that = this;
var subject = args[0];
var testDescriptionString = args[1];
if (args.length < 2) {
throw new Error('The expect function requires at least two parameters.');
} else if (testDescriptionString && testDescriptionString._expectIt) {
return that.expect.withError(function () {
return testDescriptionString(subject);
}, function (err) {
that.fail(err);
});
}
function executeExpect(context, subject, testDescriptionString, args) {
var assertionRule = that.lookupAssertionRule(subject, testDescriptionString, args);
if (!assertionRule) {
var tokens = testDescriptionString.split(' ');
OUTER: for (var n = tokens.length - 1; n > 0 ; n -= 1) {
var prefix = tokens.slice(0, n).join(' ');
var remainingTokens = tokens.slice(n);
var argsWithAssertionPrepended = [ remainingTokens.join(' ') ].concat(args);
assertionRule = that.lookupAssertionRule(subject, prefix, argsWithAssertionPrepended, true);
if (assertionRule) {
// Found the longest prefix of the string that yielded a suitable assertion for the given subject and args
// To avoid bogus error messages when shifting later (#394) we require some prefix of the remaining tokens
// to be a valid assertion name:
for (var i = 1 ; i < remainingTokens.length ; i += 1) {
if (that.assertions.hasOwnProperty(remainingTokens.slice(0, i + 1).join(' '))) {
testDescriptionString = prefix;
args = argsWithAssertionPrepended;
break OUTER;
}
}
}
}
if (!assertionRule) {
that.throwAssertionNotFoundError(subject, testDescriptionString, args);
}
}
if (assertionRule && assertionRule.unexpected && assertionRule.unexpected !== that) {
return assertionRule.unexpected.expect.apply(assertionRule.unexpected.expect, [subject, testDescriptionString].concat(args));
}
var flags = extend({}, assertionRule.flags);
var wrappedExpect = function (subject, testDescriptionString) {
if (arguments.length === 0) {
throw new Error('The expect function requires at least one parameter.');
} else if (arguments.length === 1) {
return addAdditionalPromiseMethods(makePromise.resolve(subject), wrappedExpect, subject);
} else if (testDescriptionString && testDescriptionString._expectIt) {
wrappedExpect.errorMode = 'nested';
return wrappedExpect.withError(function () {
return testDescriptionString(subject);
}, function (err) {
wrappedExpect.fail(err);
});
}
testDescriptionString = utils.forwardFlags(testDescriptionString, flags);
var args = new Array(arguments.length - 2);
for (var i = 2 ; i < arguments.length ; i += 1) {
args[i - 2] = arguments[i];
}
return wrappedExpect.callInNestedContext(function () {
return executeExpect(context.child(), subject, testDescriptionString, args);
});
};
utils.setPrototypeOfOrExtend(wrappedExpect, that._wrappedExpectProto);
wrappedExpect.context = context;
wrappedExpect.execute = wrappedExpect;
wrappedExpect.alternations = assertionRule.alternations;
wrappedExpect.flags = flags;
wrappedExpect.subject = subject;
wrappedExpect.testDescription = testDescriptionString;
wrappedExpect.args = args;
wrappedExpect.assertionRule = assertionRule;
wrappedExpect.subjectOutput = function (output) {
output.appendInspected(subject);
};
wrappedExpect.argsOutput = args.map(function (arg, i) {
var argRule = wrappedExpect.assertionRule.args[i];
if (typeof arg === 'string' && (argRule && argRule.type.is('assertion') || wrappedExpect._getAssertionIndices().indexOf(i) >= 0)) {
return new AssertionString(arg);
}
return function (output) {
output.appendInspected(arg);
};
});
// Eager-compute these properties in browsers that don't support getters
// (Object.defineProperty might be polyfilled by es5-sham):
if (!Object.__defineGetter__) {
wrappedExpect.subjectType = wrappedExpect._getSubjectType();
wrappedExpect.argTypes = wrappedExpect._getArgTypes();
}
return oathbreaker(assertionRule.handler.apply(wrappedExpect, [wrappedExpect, subject].concat(args)));
}
try {
var result = executeExpect(context, subject, testDescriptionString, Array.prototype.slice.call(args, 2));
if (isPendingPromise(result)) {
that.expect.notifyPendingPromise(result);
result = result.then(undefined, function (e) {
if (e && e._isUnexpected && context.level === 0) {
that.setErrorMessage(e);
}
throw e;
});
} else {
if (!result || typeof result.then !== 'function') {
result = makePromise.resolve(result);
}
}
return addAdditionalPromiseMethods(result, that.expect, subject);
} catch (e) {
if (e && e._isUnexpected) {
var newError = e;
if (typeof mochaPhantomJS !== 'undefined') {
newError = e.clone();
}
if (context.level === 0) {
that.setErrorMessage(newError);
}
throw newError;
}
throw e;
}
};
Unexpected.prototype.async = function (cb) {
var that = this;
function asyncMisusage(message) {
that._isAsync = false;
that.expect.fail(function (output) {
output.error(message).nl()
.text("Usage: ").nl()
.text("it('test description', expect.async(function () {").nl()
.indentLines()
.i().text("return expect('test.txt', 'to have content', 'Content read asynchroniously');").nl()
.outdentLines()
.text("});");
});
}
if (typeof cb !== 'function' || cb.length !== 0) {
asyncMisusage("expect.async requires a callback without arguments.");
}
return function (done) {
if (that._isAsync) {
asyncMisusage("expect.async can't be within a expect.async context.");
}
that._isAsync = true;
if (typeof done !== 'function') {
asyncMisusage("expect.async should be called in the context of an it-block\n" +
"and the it-block should supply a done callback.");
}
var result;
try {
result = cb();
} finally {
that._isAsync = false;
}
if (!result || typeof result.then !== 'function') {
asyncMisusage("expect.async requires the block to return a promise or throw an exception.");
}
result.then(function () {
that._isAsync = false;
done();
}, function (err) {
that._isAsync = false;
done(err);
});
};
};
Unexpected.prototype.diff = function (a, b, output, recursions, seen) {
output = output || this.createOutput();
var that = this;
var maxRecursions = 100;
recursions = typeof recursions === 'number' ? recursions : maxRecursions;
if (recursions <= 0) {
// detect recursive loops in the structure
seen = seen || [];
if (seen.indexOf(a) !== -1) {
throw new Error('Cannot compare circular structures');
}
seen.push(a);
}
return makeDiffResultBackwardsCompatible(this.findCommonType(a, b).diff(a, b, output, function (actual, expected) {
return that.diff(actual, expected, output.clone(), recursions - 1, seen);
}, function (v, depth) {
return output.clone().appendInspected(v, depth);
}, function (actual, expected) {
return that.equal(actual, expected);
}));
};
Unexpected.prototype.toString = function () {
var assertions = this.assertions;
var seen = {};
var declarations = [];
var pen = magicpen();
Object.keys(assertions).sort().forEach(function (key) {
assertions[key].forEach(function (assertion) {
if (!seen[assertion.declaration]) {
declarations.push(assertion.declaration);
seen[assertion.declaration] = true;
}
});
});
declarations.forEach(function (declaration) {
pen.text(declaration).nl();
});
return pen.toString();
};
Unexpected.prototype.clone = function () {
var clonedAssertions = {};
Object.keys(this.assertions).forEach(function (assertion) {
clonedAssertions[assertion] = [].concat(this.assertions[assertion]);
}, this);
var unexpected = new Unexpected({
assertions: clonedAssertions,
types: [].concat(this.types),
typeByName: extend({}, this.typeByName),
output: this.output.clone(),
format: this.outputFormat(),
installedPlugins: [].concat(this.installedPlugins)
});
// Install the hooks:
unexpected._expect = this._expect;
return makeExpectFunction(unexpected);
};
Unexpected.prototype.child = function () {
var childUnexpected = new Unexpected({
assertions: {},
types: [],
typeByName: {},
output: this.output.clone(),
format: this.outputFormat(),
installedPlugins: []
});
var parent = childUnexpected.parent = this;
var childExpect = makeExpectFunction(childUnexpected);
childExpect.exportAssertion = function (testDescription, handler) {
parent.addAssertion(testDescription, handler, childUnexpected);
return this;
};
childExpect.exportType = function (type) {
parent.addType(type, childUnexpected);
return this;
};
childExpect.exportStyle = function (name, handler) {
parent.addStyle(name, function () { // ...
var childOutput = childExpect.createOutput(this.format);
this.append(handler.apply(childOutput, arguments) || childOutput);
});
return this;
};
return childExpect;
};
Unexpected.prototype.outputFormat = function (format) {
if (typeof format === 'undefined') {
return this._outputFormat;
} else {
this._outputFormat = format;
return this.expect;
}
};
Unexpected.prototype.createOutput = function (format) {
var that = this;
var output = this.output.clone(format || 'text');
output.addStyle('appendInspected', function (value, depth) {
this.append(that.inspect(value, depth, this.clone()));
});
return output;
};
Unexpected.create = function () {
var unexpected = new Unexpected();
return makeExpectFunction(unexpected);
};
var expandAssertion = (function () {
function isFlag(token) {
return token.slice(0, 1) === '[' && token.slice(-1) === ']';
}
function isAlternation(token) {
return token.slice(0, 1) === '(' && token.slice(-1) === ')';
}
function removeEmptyStrings(texts) {
return texts.filter(function (text) {
return text !== '';
});
}
function createPermutations(tokens, index) {
if (index === tokens.length) {
return [{ text: '', flags: {}, alternations: [] }];
}
var token = tokens[index];
var tail = createPermutations(tokens, index + 1);
if (isFlag(token)) {
var flag = token.slice(1, -1);
return tail.map(function (pattern) {
var flags = {};
flags[flag] = true;
return {
text: flag + ' ' + pattern.text,
flags: extend(flags, pattern.flags),
alternations: pattern.alternations
};
}).concat(tail.map(function (pattern) {
var flags = {};
flags[flag] = false;
return {
text: pattern.text,
flags: extend(flags, pattern.flags),
alternations: pattern.alternations
};
}));
} else if (isAlternation(token)) {
return token
.substr(1, token.length - 2) // Remove parentheses
.split(/\|/)
.reduce(function (result, alternation) {
return result.concat(tail.map(function (pattern) {
return {
// Make sure that an empty alternation doesn't produce two spaces:
text: alternation ? alternation + pattern.text : pattern.text.replace(/^ /, ''),
flags: pattern.flags,
alternations: [alternation].concat(pattern.alternations)
};
}));
}, []);
} else {
return tail.map(function (pattern) {
return {
text: token + pattern.text,
flags: pattern.flags,
alternations: pattern.alternations
};
});
}
}
return function (pattern) {
pattern = pattern.replace(/(\[[^\]]+\]) ?/g, '$1');
var splitRegex = /\[[^\]]+\]|\([^\)]+\)/g;
var tokens = [];
var m;
var lastIndex = 0;
while ((m = splitRegex.exec(pattern))) {
tokens.push(pattern.slice(lastIndex, m.index));
tokens.push(pattern.slice(m.index, splitRegex.lastIndex));
lastIndex = splitRegex.lastIndex;
}
tokens.push(pattern.slice(lastIndex));
tokens = removeEmptyStrings(tokens);
var permutations = createPermutations(tokens, 0);
permutations.forEach(function (permutation) {
permutation.text = permutation.text.trim();
if (permutation.text === '') {
// This can only happen if the pattern only contains flags
throw new Error("Assertion patterns must not only contain flags");
}
});
return permutations;
};
}());
function ensureValidUseOfParenthesesOrBrackets(pattern) {
var counts = {
'[': 0,
']': 0,
'(': 0,
')': 0
};
for (var i = 0; i < pattern.length; i += 1) {
var c = pattern.charAt(i);
if (c in counts) {
counts[c] += 1;
}
if (c === ']' && counts['['] >= counts[']']) {
if (counts['['] === counts[']'] + 1) {
throw new Error("Assertion patterns must not contain flags with brackets: '" + pattern + "'");
}
if (counts['('] !== counts[')']) {
throw new Error("Assertion patterns must not contain flags with parentheses: '" + pattern + "'");
}
if (pattern.charAt(i - 1) === '[') {
throw new Error("Assertion patterns must not contain empty flags: '" + pattern + "'");
}
} else if (c === ')' && counts['('] >= counts[')']) {
if (counts['('] === counts[')'] + 1) {
throw new Error("Assertion patterns must not contain alternations with parentheses: '" + pattern + "'");
}
if (counts['['] !== counts[']']) {
throw new Error("Assertion patterns must not contain alternations with brackets: '" + pattern + "'");
}
}
}
if (counts['['] !== counts[']']) {
throw new Error("Assertion patterns must not contain unbalanced brackets: '" + pattern + "'");
}
if (counts['('] !== counts[')']) {
throw new Error("Assertion patterns must not contain unbalanced parentheses: '" + pattern + "'");
}
}
module.exports = Unexpected;
},{"1":1,"10":10,"11":11,"12":12,"13":13,"16":16,"19":19,"3":3,"4":4,"40":40,"44":44,"6":6,"7":7,"8":8,"9":9}],3:[function(require,module,exports){
var utils = require(19);
var defaultDepth = require(8);
var useFullStackTrace = require(18);
var makeDiffResultBackwardsCompatible = require(10);
var errorMethodBlacklist = ['message', 'line', 'sourceId', 'sourceURL', 'stack', 'stackArray'].reduce(function (result, prop) {
result[prop] = true;
return result;
}, {});
function UnexpectedError(expect, parent) {
this.errorMode = (expect && expect.errorMode) || 'default';
var base = Error.call(this, '');
if (Error.captureStackTrace) {
Error.captureStackTrace(this, UnexpectedError);
} else {
// Throw the error to make sure it has its stack serialized:
try { throw base; } catch (err) {}
this.stack = base.stack;
}
this.expect = expect;
this.parent = parent || null;
this.name = 'UnexpectedError';
}
UnexpectedError.prototype = Object.create(Error.prototype);
UnexpectedError.prototype.useFullStackTrace = useFullStackTrace;
var missingOutputMessage = 'You must either provide a format or a magicpen instance';
UnexpectedError.prototype.outputFromOptions = function (options) {
if (!options) {
throw new Error(missingOutputMessage);
}
if (typeof options === 'string') {
return this.expect.createOutput(options);
}
if (options.isMagicPen) {
return options.clone();
}
if (options.output) {
return options.output.clone();
}
if (options.format) {
return this.expect.createOutput(options.format);
}
throw new Error(missingOutputMessage);
};
UnexpectedError.prototype._isUnexpected = true;
UnexpectedError.prototype.isUnexpected = true;
UnexpectedError.prototype.buildDiff = function (options) {
var output = this.outputFromOptions(options);
var expect = this.expect;
return this.createDiff && makeDiffResultBackwardsCompatible(this.createDiff(output, function (actual, expected) {
return expect.diff(actual, expected, output.clone());
}, function (v, depth) {
return output.clone().appendInspected(v, (depth || defaultDepth) - 1);
}, function (actual, expected) {
return expect.equal(actual, expected);
}));
};
UnexpectedError.prototype.getDefaultErrorMessage = function (options) {
var output = this.outputFromOptions(options);
if (this.expect.testDescription) {
output.append(this.expect.standardErrorMessage(output.clone(), options));
} else if (typeof this.output === 'function') {
this.output.call(output, output);
}
var errorWithDiff = this;
while (!errorWithDiff.createDiff && errorWithDiff.parent) {
errorWithDiff = errorWithDiff.parent;
}
if (errorWithDiff && errorWithDiff.createDiff) {
var comparison = errorWithDiff.buildDiff(options);
if (comparison) {
output.nl(2).append(comparison);
}
}
return output;
};
UnexpectedError.prototype.getNestedErrorMessage = function (options) {
var output = this.outputFromOptions(options);
if (this.expect.testDescription) {
output.append(this.expect.standardErrorMessage(output.clone(), options));
} else if (typeof this.output === 'function') {
this.output.call(output, output);
}
var parent = this.parent;
while (parent.getErrorMode() === 'bubble') {
parent = parent.parent;
}
if (typeof options === 'string') {
options = { format: options };
} else if (options && options.isMagicPen) {
options = { output: options };
}
output.nl()
.indentLines()
.i().block(parent.getErrorMessage(utils.extend({}, options || {}, {
compact: this.expect.subject === parent.expect.subject
})));
return output;
};
UnexpectedError.prototype.getDefaultOrNestedMessage = function (options) {
if (this.hasDiff()) {
return this.getDefaultErrorMessage(options);
} else {
return this.getNestedErrorMessage(options);
}
};
UnexpectedError.prototype.hasDiff = function () {
return !!this.getDiffMethod();
};
UnexpectedError.prototype.getDiffMethod = function () {
var errorWithDiff = this;
while (!errorWithDiff.createDiff && errorWithDiff.parent) {
errorWithDiff = errorWithDiff.parent;
}
return errorWithDiff && errorWithDiff.createDiff || null;
};
UnexpectedError.prototype.getDiff = function (options) {
var errorWithDiff = this;
while (!errorWithDiff.createDiff && errorWithDiff.parent) {
errorWithDiff = errorWithDiff.parent;
}
return errorWithDiff && errorWithDiff.buildDiff(options);
};
UnexpectedError.prototype.getDiffMessage = function (options) {
var output = this.outputFromOptions(options);
var comparison = this.getDiff(options);
if (comparison) {
output.append(comparison);
} else if (this.expect.testDescription) {
output.append(this.expect.standardErrorMessage(output.clone(), options));
} else if (typeof this.output === 'function') {
this.output.call(output, output);
}
return output;
};
UnexpectedError.prototype.getErrorMode = function () {
if (!this.parent) {
switch (this.errorMode) {
case 'default':
case 'bubbleThrough':
return this.errorMode;
default:
return 'default';
}
} else {
return this.errorMode;
}
};
UnexpectedError.prototype.getErrorMessage = function (options) {
// Search for any parent error that has an error mode of 'bubbleThrough' through on the
// error these should be bubbled to the top
var errorWithBubbleThrough = this.parent;
while (errorWithBubbleThrough && errorWithBubbleThrough.getErrorMode() !== 'bubbleThrough') {
errorWithBubbleThrough = errorWithBubbleThrough.parent;
}
if (errorWithBubbleThrough) {
return errorWithBubbleThrough.getErrorMessage(options);
}
var errorMode = this.getErrorMode();
switch (errorMode) {
case 'nested': return this.getNestedErrorMessage(options);
case 'default': return this.getDefaultErrorMessage(options);
case 'bubbleThrough': return this.getDefaultErrorMessage(options);
case 'bubble': return this.parent.getErrorMessage(options);
case 'diff': return this.getDiffMessage(options);
case 'defaultOrNested': return this.getDefaultOrNestedMessage(options);
default: throw new Error("Unknown error mode: '" + errorMode + "'");
}
};
function findStackStart(lines) {
for (var i = lines.length - 1; 0 <= i; i -= 1) {
if (lines[i] === '') {
return i + 1;
}
}
return -1;
}
UnexpectedError.prototype.serializeMessage = function (outputFormat) {
if (!this._hasSerializedErrorMessage) {
var htmlFormat = outputFormat === 'html';
if (htmlFormat) {
if (!('htmlMessage' in this)) {
this.htmlMessage = this.getErrorMessage({format: 'html'}).toString();
}
}
this.message = '\n' + this.getErrorMessage({
format: htmlFormat ? 'text' : outputFormat
}).toString() + '\n';
if (this.originalError && this.originalError instanceof Error && typeof this.originalError.stack === 'string') {
// The stack of the original error looks like this:
// <constructor name>: <error message>\n<actual stack trace>
// Try to get hold of <actual stack trace> and append it
// to the error message of this error:
var index = this.originalError.stack.indexOf(this.originalError.message);
if (index === -1) {
// Phantom.js doesn't include the error message in the stack property
this.stack = this.message + '\n' + this.originalError.stack;
} else {
this.stack = this.message + this.originalError.stack.substr(index + this.originalError.message.length);
}
} else if (/^(Unexpected)?Error:?\n/.test(this.stack)) {
// Fix for Jest that does not seem to capture the error message
this.stack = this.stack.replace(/^(Unexpected)?Error:?\n/, this.message);
}
if (this.stack && !this.useFullStackTrace) {
var newStack = [];
var removedFrames = false;
var lines = this.stack.split(/\n/);
var stackStart = findStackStart(lines);
lines.forEach(function (line, i) {
if (stackStart <= i && (/node_modules\/unexpected(?:-[^\/]+)?\//).test(line)) {
removedFrames = true;
} else {
newStack.push(line);
}
});
if (removedFrames) {
var indentation = (/^(\s*)/).exec(lines[lines.length - 1])[1];
if (outputFormat === 'html') {
newStack.push(indentation + 'set the query parameter full-trace=true to see the full stack trace');
} else {
newStack.push(indentation + 'set UNEXPECTED_FULL_TRACE=true to see the full stack trace');
}
}
this.stack = newStack.join('\n');
}
this._hasSerializedErrorMessage = true;
}
};
UnexpectedError.prototype.clone = function () {
var that = this;
var newError = new UnexpectedError(this.expect);
Object.keys(that).forEach(function (key) {
if (!errorMethodBlacklist[key]) {
newError[key] = that[key];
}
});
return newError;
};
UnexpectedError.prototype.getLabel = function () {
var currentError = this;
while (currentError && !currentError.label) {
currentError = currentError.parent;
}
return (currentError && currentError.label) || null;
};
UnexpectedError.prototype.getParents = function () {
var result = [];
var parent = this.parent;
while (parent) {
result.push(parent);
parent = parent.parent;
}
return result;
};
UnexpectedError.prototype.getAllErrors = function () {
var result = this.getParents();
result.unshift(this);
return result;
};
if (Object.__defineGetter__) {
Object.defineProperty(UnexpectedError.prototype, 'htmlMessage', {
enumerable: true,
get: function () {
return this.getErrorMessage({ format: 'html' }).toString();
}
});
}
module.exports = UnexpectedError;
},{"10":10,"18":18,"19":19,"8":8}],4:[function(require,module,exports){
module.exports = function addAdditionalPromiseMethods(promise, expect, subject) {
promise.and = function () { // ...
var args = Array.prototype.slice.call(arguments);
function executeAnd() {
if (expect.findTypeOf(args[0]).is('expect.it')) {
return addAdditionalPromiseMethods(args[0](subject), expect, subject);
} else {
return expect.apply(expect, [subject].concat(args));
}
}
if (this.isFulfilled()) {
return executeAnd();
} else {
return addAdditionalPromiseMethods(this.then(executeAnd), expect, subject);
}
};
return promise;
};
},{}],5:[function(require,module,exports){
(function (Buffer){
/*global setTimeout*/
var utils = require(19);
var arrayChanges = require(24);
var arrayChangesAsync = require(23);
var throwIfNonUnexpectedError = require(16);
var objectIs = utils.objectIs;
var isRegExp = utils.isRegExp;
var extend = utils.extend;
module.exports = function (expect) {
expect.addAssertion('<any> [not] to be (ok|truthy)', function (expect, subject) {
var not = !!expect.flags.not;
var condition = !!subject;
if (condition === not) {
expect.fail();
}
});
expect.addAssertion('<any> [not] to be (ok|truthy) <string>', function (expect, subject, message) {
var not = !!expect.flags.not;
var condition = !!subject;
if (condition === not) {
expect.fail({
errorMode: 'bubble',
message: message
});
}
});
expect.addAssertion('<any> [not] to be <any>', function (expect, subject, value) {
expect(objectIs(subject, value), '[not] to be truthy');
});
expect.addAssertion('<string> [not] to be <string>', function (expect, subject, value) {
expect(subject, '[not] to equal', value);
});
expect.addAssertion('<boolean> [not] to be true', function (expect, subject) {
expect(subject, '[not] to be', true);
});
expect.addAssertion('<boolean> [not] to be false', function (expect, subject) {
expect(subject, '[not] to be', false);
});
expect.addAssertion('<any> [not] to be falsy', function (expect, subject) {
expect(subject, '[!not] to be truthy');
});
expect.addAssertion('<any> [not] to be falsy <string>', function (expect, subject, message) {
var not = !!expect.flags.not;
var condition = !!subject;
if (condition !== not) {
expect.fail({
errorMode: 'bubble',
message: message
});
}
});
expect.addAssertion('<any> [not] to be null', function (expect, subject) {
expect(subject, '[not] to be', null);
});
expect.addAssertion('<any> [not] to be undefined', function (expect, subject) {
expect(typeof subject === 'undefined', '[not] to be truthy');
});
expect.addAssertion('<any> to be defined', function (expect, subject) {
expect(subject, 'not to be undefined');
});
expect.addAssertion('<number|NaN> [not] to be NaN', function (expect, subject) {
expect(isNaN(subject), '[not] to be truthy');
});
expect.addAssertion('<number> [not] to be close to <number> <number?>', function (expect, subject, value, epsilon) {
expect.errorMode = 'bubble';
if (typeof epsilon !== 'number') {
epsilon = 1e-9;
}
expect.withError(function () {
expect(Math.abs(subject - value), '[not] to be less than or equal to', epsilon);
}, function (e) {
expect.fail(function (output) {
output.error('expected ')
.appendInspected(subject).sp()
.error(expect.testDescription).sp()
.appendInspected(value).sp()
.text('(epsilon: ')
.jsNumber(epsilon.toExponential())
.text(')');
});
});
});
expect.addAssertion('<any> [not] to be (a|an) <type>', function (expect, subject, type) {
expect.argsOutput[0] = function (output) {
output.text(type.name);
};
expect(type.identify(subject), '[not] to be true');
});
expect.addAssertion('<any> [not] to be (a|an) <string>', function (expect, subject, typeName) {
typeName = /^reg(?:exp?|ular expression)$/.test(typeName) ? 'regexp' : typeName;
expect.argsOutput[0] = function (output) {
output.jsString(typeName);
};
if (!expect.getType(typeName)) {
expect.errorMode = 'nested';
expect.fail(function (output) {
output.error('Unknown type:').sp().jsString(typeName);
});
}
expect(expect.subjectType.is(typeName), '[not] to be truthy');
});
expect.addAssertion('<any> [not] to be (a|an) <function>', function (expect, subject, Constructor) {
var className = utils.getFunctionName(Constructor);
if (className) {
expect.argsOutput[0] = function (output) {
output.text(className);
};
}
expect(subject instanceof Constructor, '[not] to be truthy');
});
expect.addAssertion('<any> [not] to be one of <array>', function (expect, subject, superset) {
var found = false;
for (var i = 0; i < superset.length; i += 1) {
found = found || objectIs(subject, superset[i]);
}
if (found === expect.flags.not) { expect.fail(); }
});
// Alias for common '[not] to be (a|an)' assertions
expect.addAssertion('<any> [not] to be an (object|array)', function (expect, subject) {
expect(subject, '[not] to be an', expect.alternations[0]);
});
expect.addAssertion('<any> [not] to be a (boolean|number|string|function|regexp|regex|regular expression)', function (expect, subject) {
expect(subject, '[not] to be a', expect.alternations[0]);
});
expect.addAssertion('<string> to be (the empty|an empty|a non-empty) string', function (expect, subject) {
expect(subject, expect.alternations[0] === 'a non-empty' ? 'not to be empty' : 'to be empty');
});
expect.addAssertion('<array-like> to be (the empty|an empty|a non-empty) array', function (expect, subject) {
expect(subject, expect.alternations[0] === 'a non-empty' ? 'not to be empty' : 'to be empty');
});
expect.addAssertion('<string> to match <regexp>', function (expect, subject, regexp) {
return expect.withError(function () {
var captures = subject.match(regexp);
expect(captures, 'to be truthy');
return captures;
}, function (e) {
e.label = 'should match';
expect.fail(e);
});
});
expect.addAssertion('<string> not to match <regexp>', function (expect, subject, regexp) {
return expect.withError(function () {
expect(regexp.test(subject), 'to be false');
}, function (e) {
expect.fail({
label: 'should not match',
diff: function (output) {
output.inline = false;
var lastIndex = 0;
function flushUntilIndex(i) {
if (i > lastIndex) {
output.text(subject.substring(lastIndex, i));
lastIndex = i;
}
}
subject.replace(new RegExp(regexp.source, 'g'), function ($0, index) {
flushUntilIndex(index);
lastIndex += $0.length;
output.removedHighlight($0);
});
flushUntilIndex(subject.length);
return output;
}
});
});
});
expect.addAssertion('<object|function> [not] to have own property <string>', function (expect, subject, key) {
expect(subject.hasOwnProperty(key), '[not] to be truthy');
return subject[key];
});
expect.addAssertion('<object|function> [not] to have (enumerable|configurable|writable) property <string>', function (expect, subject, key) {
var descriptor = expect.alternations[0];
expect(Object.getOwnPropertyDescriptor(subject, key)[descriptor], '[not] to be truthy');
return subject[key];
});
expect.addAssertion('<object|function> [not] to have property <string>', function (expect, subject, key) {
expect(subject[key], '[!not] to be undefined');
return subject[key];
});
expect.addAssertion('<object|function> to have [own] property <string> <any>', function (expect, subject, key, expectedPropertyValue) {
return expect(subject, 'to have [own] property', key).then(function (actualPropertyValue) {
expect.argsOutput = function () {
this.appendInspected(key).sp().error('with a value of').sp().appendInspected(expectedPropertyValue);
};
expect(actualPropertyValue, 'to equal', expectedPropertyValue);
return actualPropertyValue;
});
});
expect.addAssertion('<object|function> [not] to have [own] properties <array>', function (expect, subject, properties) {
properties.forEach(function (property) {
expect(subject, '[not] to have [own] property', property);
});
});
expect.addAssertion('<object|function> to have [own] properties <object>', function (expect, subject, properties) {
expect.withError(function () {
Object.keys(properties).forEach(function (property) {
var value = properties[property];
if (typeof value === 'undefined') {
expect(subject, 'not to have [own] property', property);
} else {
expect(subject, 'to have [own] property', property, value);
}
});
}, function (e) {
expect.fail({
diff: function (output, diff) {
output.inline = false;
var expected = extend({}, properties);
var actual = {};
var propertyNames = expect.findTypeOf(subject).getKeys(subject);
// Might put duplicates into propertyNames, but that does not matter:
for (var propertyName in subject) {
if (!subject.hasOwnProperty(propertyName)) {
propertyNames.push(propertyName);
}
}
propertyNames.forEach(function (propertyName) {
if ((!expect.flags.own || subject.hasOwnProperty(propertyName)) && !(propertyName in properties)) {
expected[propertyName] = subject[propertyName];
}
if ((!expect.flags.own || subject.hasOwnProperty(propertyName)) && !(propertyName in actual)) {
actual[propertyName] = subject[propertyName];
}
});
return utils.wrapConstructorNameAroundOutput(diff(actual, expected), subject);
}
});
});
});
expect.addAssertion('<string|array-like> [not] to have length <number>', function (expect, subject, length) {
if (!expect.flags.not) {
expect.errorMode = 'nested';
}
expect(subject.length, '[not] to be', length);
});
expect.addAssertion('<string|array-like> [not] to be empty', function (expect, subject) {
expect(subject, '[not] to have length', 0);
});
expect.addAssertion('<string|array-like|object> to be non-empty', function (expect, subject) {
expect(subject, 'not to be empty');
});
expect.addAssertion('<object> to [not] [only] have keys <array>', function (expect, subject, keys) {
var keysInSubject = {};
var subjectKeys = expect.findTypeOf(subject).getKeys(subject);
subjectKeys.forEach(function (key) {
keysInSubject[key] = true;
});
if (expect.flags.not && keys.length === 0) {
return;
}
var hasKeys = keys.every(function (key) {
return keysInSubject[key];
});
if (expect.flags.only) {
expect(hasKeys, 'to be truthy');
expect.withError(function () {
expect(subjectKeys.length === keys.length, '[not] to be truthy');
}, function (err) {
expect.fail({
diff: !expect.flags.not && function (output, diff, inspect, equal) {
output.inline = true;
var keyInValue = {};
keys.forEach(function (key) {
keyInValue[key] = true;
});
var subjectType = expect.findTypeOf(subject);
var subjectIsArrayLike = subjectType.is('array-like');
subjectType.prefix(output, subject);
output.nl().indentLines();
subjectKeys.forEach(function (key, index) {
output.i().block(function () {
this.property(key, inspect(subject[key]), subjectIsArrayLike);
subjectType.delimiter(this, index, subjectKeys.length);
if (!keyInValue[key]) {
this.sp().annotationBlock(function () {
this.error('should be removed');
});
}
}).nl();
});
output.outdentLines();
subjectType.suffix(output, subject);
return output;
}
});
});
} else {
expect(hasKeys, '[not] to be truthy');
}
});
expect.addAssertion('<object> [not] to be empty', function (expect, subject) {
if (expect.flags.not && !expect.findTypeOf(subject).getKeys(subject).length) {
return expect.fail();
}
expect(subject, 'to [not] only have keys', []);
});
expect.addAssertion('<object> not to have keys <array>', function (expect, subject, keys) {
expect(subject, 'to not have keys', keys);
});
expect.addAssertion('<object> not to have key <string>', function (expect, subject, value) {
expect(subject, 'to not have keys', [ value ]);
});
expect.addAssertion('<object> not to have keys <string+>', function (expect, subject, value) {
expect(subject, 'to not have keys', Array.prototype.slice.call(arguments, 2));
});
expect.addAssertion('<object> to [not] [only] have key <string>', function (expect, subject, value) {
expect(subject, 'to [not] [only] have keys', [ value ]);
});
expect.addAssertion('<object> to [not] [only] have keys <string+>', function (expect, subject) {
expect(subject, 'to [not] [only] have keys', Array.prototype.slice.call(arguments, 2));
});
expect.addAssertion('<string> [not] to contain <string+>', function (expect, subject) {
var args = Array.prototype.slice.call(arguments, 2);
args.forEach(function (arg) {
if (arg === '') {
throw new Error("The '" + expect.testDescription + "' assertion does not support the empty string");
}
});
expect.withError(function () {
args.forEach(function (arg) {
expect(subject.indexOf(arg) !== -1, '[not] to be truthy');
});
}, function (e) {
expect.fail({
diff: function (output) {
output.inline = false;
var lastIndex = 0;
function flushUntilIndex(i) {
if (i > lastIndex) {
output.text(subject.substring(lastIndex, i));
lastIndex = i;
}
}
if (expect.flags.not) {
subject.replace(new RegExp(args.map(function (arg) {
return utils.escapeRegExpMetaChars(arg);
}).join('|'), 'g'), function ($0, index) {
flushUntilIndex(index);
lastIndex += $0.length;
output.removedHighlight($0);
});
flushUntilIndex(subject.length);
} else {
var ranges = [];
args.forEach(function (arg) {
var needle = arg;
var partial = false;
while (needle.length > 1) {
var found = false;
lastIndex = -1;
var index;
do {
index = subject.indexOf(needle, lastIndex + 1);
if (index !== -1) {
found = true;
ranges.push({
startIndex: index,
endIndex: index + needle.length,
partial: partial
});
}
lastIndex = index;
} while (lastIndex !== -1);
if (found) {
break;
}
needle = arg.substr(0, needle.length - 1);
partial = true;
}
});
lastIndex = 0;
ranges.sort(function (a, b) {
return a.startIndex - b.startIndex;
}).forEach(function (range) {
flushUntilIndex(range.startIndex);
var firstUncoveredIndex = Math.max(range.startIndex, lastIndex);
if (range.endIndex > firstUncoveredIndex) {
if (range.partial) {
output.partialMatch(subject.substring(firstUncoveredIndex, range.endIndex));
} else {
output.match(subject.substring(firstUncoveredIndex, range.endIndex));
}
lastIndex = range.endIndex;
}
});
flushUntilIndex(subject.length);
}
return output;
}
});
});
});
expect.addAssertion('<array-like> [not] to contain <any+>', function (expect, subject) {
var args = Array.prototype.slice.call(arguments, 2);
expect.withError(function () {
args.forEach(function (arg) {
expect(subject && Array.prototype.some.call(subject, function (item) {
return expect.equal(item, arg);
}), '[not] to be truthy');
});
}, function (e) {
expect.fail({
diff: expect.flags.not && function (output, diff, inspect, equal) {
return diff(subject, Array.prototype.filter.call(subject, function (item) {
return !args.some(function (arg) {
return equal(item, arg);
});
}));
}
});
});
});
expect.addAssertion('<string> [not] to begin with <string>', function (expect, subject, value) {
if (value === '') {
throw new Error("The '" + expect.testDescription + "' assertion does not support a prefix of the empty string");
}
expect.withError(function () {
expect(subject.substr(0, value.length), '[not] to equal', value);
}, function (err) {
expect.fail({
diff: function (output) {
output.inline = false;
if (expect.flags.not) {
output.removedHighlight(value).text(subject.substr(value.length));
} else {
var i = 0;
while (subject[i] === value[i]) {
i += 1;
}
if (i === 0) {
// No common prefix, omit diff
return null;
} else {
output
.partialMatch(subject.substr(0, i))
.text(subject.substr(i));
}
}
return output;
}
});
});
});
expect.addAssertion('<string> [not] to end with <string>', function (expect, subject, value) {
if (value === '') {
throw new Error("The '" + expect.testDescription + "' assertion does not support a suffix of the empty string");
}
expect.withError(function () {
expect(subject.substr(-value.length), '[not] to equal', value);
}, function (err) {
expect.fail({
diff: function (output) {
output.inline = false;
if (expect.flags.not) {
output.text(subject.substr(0, subject.length - value.length)).removedHighlight(value);
} else {
var i = 0;
while (subject[subject.length - 1 - i] === value[value.length - 1 - i]) {
i += 1;
}
if (i === 0) {
// No common suffix, omit diff
return null;
}
output
.text(subject.substr(0, subject.length - i))
.partialMatch(subject.substr(subject.length - i, subject.length));
}
return output;
}
});
});
});
expect.addAssertion('<number> [not] to be finite', function (expect, subject) {
expect(isFinite(subject), '[not] to be truthy');
});
expect.addAssertion('<number> [not] to be infinite', function (expect, subject) {
expect(!isNaN(subject) && !isFinite(subject), '[not] to be truthy');
});
expect.addAssertion('<number> [not] to be within <number> <number>', function (expect, subject, start, finish) {
expect.argsOutput = function (output) {
output.appendInspected(start).text('..').appendInspected(finish);
};
expect(subject >= start && subject <= finish, '[not] to be truthy');
});
expect.addAssertion('<string> [not] to be within <string> <string>', function (expect, subject, start, finish) {
expect.argsOutput = function (output) {
output.appendInspected(start).text('..').appendInspected(finish);
};
expect(subject >= start && subject <= finish, '[not] to be truthy');
});
expect.addAssertion('<number> [not] to be (less than|below) <number>', function (expect, subject, value) {
expect(subject < value, '[not] to be truthy');
});
expect.addAssertion('<string> [not] to be (less than|below) <string>', function (expect, subject, value) {
expect(subject < value, '[not] to be truthy');
});
expect.addAssertion('<number> [not] to be less than or equal to <number>', function (expect, subject, value) {
expect(subject <= value, '[not] to be truthy');
});
expect.addAssertion('<string> [not] to be less than or equal to <string>', function (expect, subject, value) {
expect(subject <= value, '[not] to be truthy');
});
expect.addAssertion('<number> [not] to be (greater than|above) <number>', function (expect, subject, value) {
expect(subject > value, '[not] to be truthy');
});
expect.addAssertion('<string> [not] to be (greater than|above) <string>', function (expect, subject, value) {
expect(subject > value, '[not] to be truthy');
});
expect.addAssertion('<number> [not] to be greater than or equal to <number>', function (expect, subject, value) {
expect(subject >= value, '[not] to be truthy');
});
expect.addAssertion('<string> [not] to be greater than or equal to <string>', function (expect, subject, value) {
expect(subject >= value, '[not] to be truthy');
});
expect.addAssertion('<number> [not] to be positive', function (expect, subject) {
expect(subject, '[not] to be greater than', 0);
});
expect.addAssertion('<number> [not] to be negative', function (expect, subject) {
expect(subject, '[not] to be less than', 0);
});
expect.addAssertion('<any> to equal <any>', function (expect, subject, value) {
expect.withError(function () {
expect(expect.equal(value, subject), 'to be truthy');
}, function (e) {
expect.fail({
label: 'should equal',
diff: function (output, diff) {
return diff(subject, value);
}
});
});
});
expect.addAssertion('<any> not to equal <any>', function (expect, subject, value) {
expect(expect.equal(value, subject), 'to be falsy');
});
expect.addAssertion('<function> to error', function (expect, subject) {
return expect.promise(function () {
return subject();
}).then(function () {
expect.fail();
}, function (error) {
return error;
});
});
expect.addAssertion('<function> to error [with] <any>', function (expect, subject, arg) {
return expect(subject, 'to error').then(function (error) {
expect.errorMode = 'nested';
return expect.withError(function () {
if (error.isUnexpected && (typeof arg === 'string' || isRegExp(arg))) {
return expect(error, 'to have message', arg);
} else {
return expect(error, 'to satisfy', arg);
}
}, function (e) {
e.originalError = error;
throw e;
});
});
});
expect.addAssertion('<function> not to error', function (expect, subject) {
var threw = false;
return expect.promise(function () {
try {
return subject();
} catch (e) {
threw = true;
throw e;
}
}).caught(function (error) {
expect.errorMode = 'nested';
expect.fail({
output: function (output) {
output.error(threw ? 'threw' : 'returned promise rejected with').error(': ')
.appendErrorMessage(error);
},
originalError: error
});
});
});
expect.addAssertion('<function> not to throw', function (expect, subject) {
var threw = false;
var error;
try {
subject();
} catch (e) {
error = e;
threw = true;
}
if (threw) {
expect.errorMode = 'nested';
expect.fail({
output: function (output) {
output.error('threw: ').appendErrorMessage(error);
},
originalError: error
});
}
});
expect.addAssertion('<function> to (throw|throw error|throw exception)', function (expect, subject) {
try {
subject();
} catch (e) {
return e;
}
expect.errorMode = 'nested';
expect.fail('did not throw');
});
expect.addAssertion('<function> to throw (a|an) <function>', function (expect, subject, value) {
var constructorName = utils.getFunctionName(value);
if (constructorName) {
expect.argsOutput[0] = function (output) {
output.jsFunctionName(constructorName);
};
}
expect.errorMode = 'nested';
return expect(subject, 'to throw').then(function (error) {
expect(error, 'to be a', value);
});
});
expect.addAssertion('<function> to (throw|throw error|throw exception) <any>', function (expect, subject, arg) {
expect.errorMode = 'nested';
return expect(subject, 'to throw').then(function (error) {
var isUnexpected = error && error._isUnexpected;
// in the presence of a matcher an error must have been thrown.
expect.errorMode = 'nested';
return expect.withError(function () {
if (isUnexpected && (typeof arg === 'string' || isRegExp(arg))) {
return expect(error.getErrorMessage('text').toString(), 'to satisfy', arg);
} else {
return expect(error, 'to satisfy', arg);
}
}, function (err) {
err.originalError = error;
throw err;
});
});
});
expect.addAssertion('<function> to have arity <number>', function (expect, subject, value) {
expect(subject.length, 'to equal', value);
});
expect.addAssertion([
'<object> to have values [exhaustively] satisfying <any>',
'<object> to have values [exhaustively] satisfying <assertion>',
'<object> to be (a map|a hash|an object) whose values [exhaustively] satisfy <any>',
'<object> to be (a map|a hash|an object) whose values [exhaustively] satisfy <assertion>'
], function (expect, subject, nextArg) {
expect.errorMode = 'nested';
expect(subject, 'not to be empty');
expect.errorMode = 'bubble';
var keys = expect.subjectType.getKeys(subject);
var expected = {};
keys.forEach(function (key, index) {
if (typeof nextArg === 'string') {
expected[key] = function (s) {
return expect.shift(s);
};
} else if (typeof nextArg === 'function') {
expected[key] = function (s) {
return nextArg._expectIt
? nextArg(s, expect.context)
: nextArg(s, index);
};
} else {
expected[key] = nextArg;
}
});
return expect.withError(function () {
return expect(subject, 'to [exhaustively] satisfy', expected);
}, function (err) {
expect.fail({
message: function (output) {
output.append(expect.standardErrorMessage(output.clone(), { compact: true }));
},
diff: function (output) {
var diff = err.getDiff({ output: output });
diff.inline = true;
return diff;
}
});
});
});
expect.addAssertion([
'<array-like> to have items [exhaustively] satisfying <any>',
'<array-like> to have items [exhaustively] satisfying <assertion>',
'<array-like> to be an array whose items [exhaustively] satisfy <any>',
'<array-like> to be an array whose items [exhaustively] satisfy <assertion>'
], function (expect, subject) { // ...
var extraArgs = Array.prototype.slice.call(arguments, 2);
expect.errorMode = 'nested';
expect(subject, 'not to be empty');
expect.errorMode = 'bubble';
return expect.withError(function () {
return expect.apply(expect, [subject, 'to have values [exhaustively] satisfying'].concat(extraArgs));
}, function (err) {
expect.fail({
message: function (output) {
output.append(expect.standardErrorMessage(output.clone(), { compact: true }));
},
diff: function (output) {
var diff = err.getDiff({ output: output });
diff.inline = true;
return diff;
}
});
});
});
expect.addAssertion([
'<object> to have keys satisfying <any>',
'<object> to have keys satisfying <assertion>',
'<object> to be (a map|a hash|an object) whose (keys|properties) satisfy <any>',
'<object> to be (a map|a hash|an object) whose (keys|properties) satisfy <assertion>'
], function (expect, subject) {
expect.errorMode = 'nested';
expect(subject, 'not to be empty');
expect.errorMode = 'default';
var keys = expect.subjectType.getKeys(subject);
var extraArgs = Array.prototype.slice.call(arguments, 2);
return expect.apply(expect, [keys, 'to have items satisfying'].concat(extraArgs));
});
expect.addAssertion([
'<object> to have a value [exhaustively] satisfying <any>',
'<object> to have a value [exhaustively] satisfying <assertion>'
], function (expect, subject, nextArg) {
expect.errorMode = 'nested';
expect(subject, 'not to be empty');
expect.errorMode = 'bubble';
var keys = expect.subjectType.getKeys(subject);
return expect.promise.any(keys.map(function (key, index) {
var expected;
if (typeof nextArg === 'string') {
expected = function (s) {
return expect.shift(s);
};
} else if (typeof nextArg === 'function') {
expected = function (s) {
return nextArg(s, index);
};
} else {
expected = nextArg;
}
return expect.promise(function () {
return expect(subject[key], 'to [exhaustively] satisfy', expected);
});
})).catch(function (e) {
return expect.fail(function (output) {
output.append(expect.standardErrorMessage(output.clone(), { compact: true }));
});
});
});
expect.addAssertion([
'<array-like> to have an item [exhaustively] satisfying <any>',
'<array-like> to have an item [exhaustively] satisfying <assertion>'
], function (expect, subject) { // ...
expect.errorMode = 'nested';
expect(subject, 'not to be empty');
expect.errorMode = 'bubble';
var extraArgs = Array.prototype.slice.call(arguments, 2);
return expect.withError(function () {
return expect.apply(expect, [subject, 'to have a value [exhaustively] satisfying'].concat(extraArgs));
}, function (err) {
expect.fail(function (output) {
output.append(expect.standardErrorMessage(output.clone(), { compact: true }));
});
});
});
expect.addAssertion('<object> to be canonical', function (expect, subject) {
var stack = [];
(function traverse(obj) {
var i;
for (i = 0 ; i < stack.length ; i += 1) {
if (stack[i] === obj) {
return;
}
}
if (obj && typeof obj === 'object') {
var keys = Object.keys(obj);
for (i = 0 ; i < keys.length - 1 ; i += 1) {
expect(keys[i], 'to be less than', keys[i + 1]);
}
stack.push(obj);
keys.forEach(function (key) {
traverse(obj[key]);
});
stack.pop();
}
}(subject));
});
expect.addAssertion('<Error> to have message <any>', function (expect, subject, value) {
expect.errorMode = 'nested';
return expect(subject.isUnexpected ? subject.getErrorMessage('text').toString() : subject.message, 'to satisfy', value);
});
expect.addAssertion('<Error> to [exhaustively] satisfy <Error>', function (expect, subject, value) {
expect(subject.constructor, 'to be', value.constructor);
var unwrappedValue = expect.argTypes[0].unwrap(value);
return expect.withError(function () {
return expect(subject, 'to [exhaustively] satisfy', unwrappedValue);
}, function (e) {
expect.fail({
diff: function (output, diff) {
output.inline = false;
var unwrappedSubject = expect.subjectType.unwrap(subject);
return utils.wrapConstructorNameAroundOutput(
diff(unwrappedSubject, unwrappedValue),
subject
);
}
});
});
});
expect.addAssertion('<Error> to [exhaustively] satisfy <object>', function (expect, subject, value) {
var valueType = expect.argTypes[0];
var subjectKeys = expect.subjectType.getKeys(subject);
var valueKeys = valueType.getKeys(value);
var convertedSubject = {};
subjectKeys.concat(valueKeys).forEach(function (key) {
convertedSubject[key] = subject[key];
});
return expect(convertedSubject, 'to [exhaustively] satisfy', value);
});
expect.addAssertion('<Error> to [exhaustively] satisfy <regexp|string>', function (expect, subject, value) {
return expect(subject.message, 'to [exhaustively] satisfy', value);
});
expect.addAssertion('<Error> to [exhaustively] satisfy <any>', function (expect, subject, value) {
return expect(subject.message, 'to [exhaustively] satisfy', value);
});
expect.addAssertion('<binaryArray> to [exhaustively] satisfy <expect.it>', function (expect, subject, value) {
return expect.withError(function () {
return value(subject, expect.context);
}, function (e) {
expect.fail({
diff: function (output, diff, inspect, equal) {
output.inline = false;
return output.appendErrorMessage(e);
}
});
});
});
expect.addAssertion('<UnexpectedError> to [exhaustively] satisfy <function>', function (expect, subject, value) {
return expect.promise(function () {
subject.serializeMessage(expect.outputFormat());
return value(subject);
});
});
expect.addAssertion('<any|Error> to [exhaustively] satisfy <function>', function (expect, subject, value) {
return expect.promise(function () {
return value(subject);
});
});
if (typeof Buffer !== 'undefined') {
expect.addAssertion('<Buffer> [when] decoded as <string> <assertion?>', function (expect, subject, value) {
return expect.shift(subject.toString(value));
});
}
expect.addAssertion('<any> not to [exhaustively] satisfy [assertion] <any>', function (expect, subject, value) {
return expect.promise(function (resolve, reject) {
return expect.promise(function () {
return expect(subject, 'to [exhaustively] satisfy [assertion]', value);
}).then(function () {
try {
expect.fail();
} catch (e) {
reject(e);
}
}).caught(function (e) {
if (!e || !e._isUnexpected) {
reject(e);
} else {
resolve();
}
});
});
});
expect.addAssertion('<any> to [exhaustively] satisfy assertion <any>', function (expect, subject, value) {
expect.errorMode = 'bubble'; // to satisfy assertion 'to be a number' => to be a number
return expect(subject, 'to [exhaustively] satisfy', value);
});
expect.addAssertion('<any> to [exhaustively] satisfy assertion <assertion>', function (expect, subject) {
expect.errorMode = 'bubble'; // to satisfy assertion 'to be a number' => to be a number
return expect.shift();
});
expect.addAssertion('<any> to [exhaustively] satisfy [assertion] <expect.it>', function (expect, subject, value) {
return expect.withError(function () {
return value(subject, expect.context);
}, function (e) {
expect.fail({
diff: function (output) {
output.inline = false;
return output.appendErrorMessage(e);
}
});
});
});
expect.addAssertion('<regexp> to [exhaustively] satisfy <regexp>', function (expect, subject, value) {
expect(subject, 'to equal', value);
});
expect.addAssertion('<string> to [exhaustively] satisfy <regexp>', function (expect, subject, value) {
expect.errorMode = 'bubble';
return expect(subject, 'to match', value);
});
expect.addAssertion('<function> to [exhaustively] satisfy <function>', function (expect, subject, value) {
expect.errorMode = 'bubble';
expect(subject, 'to equal', value);
});
expect.addAssertion('<binaryArray> to [exhaustively] satisfy <binaryArray>', function (expect, subject, value) {
expect.errorMode = 'bubble';
expect(subject, 'to equal', value);
});
expect.addAssertion('<any> to [exhaustively] satisfy <any>', function (expect, subject, value) {
expect.errorMode = 'bubble';
expect(subject, 'to equal', value);
});
expect.addAssertion('<array-like> to [exhaustively] satisfy <array-like>', function (expect, subject, value) {
expect.errorMode = 'bubble';
var i;
var valueType = expect.argTypes[0];
var valueKeys = valueType.getKeys(value);
var keyPromises = {};
valueKeys.forEach(function (valueKey) {
keyPromises[valueKey] = expect.promise(function () {
var valueKeyType = expect.findTypeOf(value[valueKey]);
if (valueKeyType.is('function')) {
return value[valueKey](subject[valueKey]);
} else {
return expect(subject[valueKey], 'to [exhaustively] satisfy', value[valueKey]);
}
});
});
return expect.promise.all([
expect.promise(function () {
expect(subject, 'to only have keys', valueKeys);
}),
expect.promise.all(keyPromises)
]).caught(function () {
var subjectType = expect.subjectType;
return expect.promise.settle(keyPromises).then(function () {
var toSatisfyMatrix = new Array(subject.length);
for (i = 0 ; i < subject.length ; i += 1) {
toSatisfyMatrix[i] = new Array(value.length);
if (i < value.length) {
toSatisfyMatrix[i][i] = keyPromises[i].isFulfilled() || keyPromises[i].reason();
}
}
if (subject.length > 10 || value.length > 10) {
var indexByIndexChanges = [];
for (i = 0 ; i < subject.length ; i += 1) {
var promise = keyPromises[i];
if (i < value.length) {
indexByIndexChanges.push({
type: promise.isFulfilled() ? 'equal' : 'similar',
value: subject[i],
expected: value[i],
actualIndex: i,
expectedIndex: i,
last: i === Math.max(subject.length, value.length) - 1
});
} else {
indexByIndexChanges.push({
type: 'remove',
value: subject[i],
actualIndex: i,
last: i === subject.length - 1
});
}
}
for (i = subject.length ; i < value.length ; i += 1) {
indexByIndexChanges.push({
type: 'insert',
value: value[i],
expectedIndex: i
});
}
return failWithChanges(indexByIndexChanges);
}
var isAsync = false;
var nonNumericalKeysAndSymbols = !subjectType.numericalPropertiesOnly &&
utils.uniqueNonNumericalStringsAndSymbols(subjectType.getKeys(subject), valueType.getKeys(value));
var changes = arrayChanges(subject, value, function equal(a, b, aIndex, bIndex) {
toSatisfyMatrix[aIndex] = toSatisfyMatrix[aIndex] || [];
var existingResult = toSatisfyMatrix[aIndex][bIndex];
if (typeof existingResult !== 'undefined') {
return existingResult === true;
}
var result;
try {
result = expect(a, 'to [exhaustively] satisfy', b);
} catch (err) {
throwIfNonUnexpectedError(err);
toSatisfyMatrix[aIndex][bIndex] = err;
return false;
}
result.then(function () {}, function () {});
if (result.isPending()) {
isAsync = true;
return false;
}
toSatisfyMatrix[aIndex][bIndex] = true;
return true;
}, function (a, b) {
return subjectType.similar(a, b);
}, nonNumericalKeysAndSymbols);
if (isAsync) {
return expect.promise(function (resolve, reject) {
arrayChangesAsync(subject, value, function equal(a, b, aIndex, bIndex, cb) {
toSatisfyMatrix[aIndex] = toSatisfyMatrix[aIndex] || [];
var existingResult = toSatisfyMatrix[aIndex][bIndex];
if (typeof existingResult !== 'undefined') {
return cb(existingResult === true);
}
expect.promise(function () {
return expect(a, 'to [exhaustively] satisfy', b);
}).then(function () {
toSatisfyMatrix[aIndex][bIndex] = true;
cb(true);
}, function (err) {
toSatisfyMatrix[aIndex][bIndex] = err;
cb(false);
});
}, function (a, b, aIndex, bIndex, cb) {
cb(subjectType.similar(a, b));
}, nonNumericalKeysAndSymbols, resolve);
}).then(failWithChanges);
} else {
return failWithChanges(changes);
}
function failWithChanges(changes) {
expect.errorMode = 'default';
expect.fail({
diff: function (output, diff, inspect, equal) {
output.inline = true;
var indexOfLastNonInsert = changes.reduce(function (previousValue, diffItem, index) {
return (diffItem.type === 'insert') ? previousValue : index;
}, -1);
var prefixOutput = subjectType.prefix(output.clone(), subject);
output
.append(prefixOutput)
.nl(prefixOutput.isEmpty() ? 0 : 1);
if (subjectType.indent) {
output.indentLines();
}
var packing = utils.packArrows(changes); // NOTE: Will have side effects in changes if the packing results in too many arrow lanes
output.arrowsAlongsideChangeOutputs(packing, changes.map(function (diffItem, index) {
var delimiterOutput = subjectType.delimiter(output.clone(), index, indexOfLastNonInsert + 1);
var type = diffItem.type;
if (type === 'moveTarget') {
return output.clone();
} else {
return output.clone().block(function () {
if (type === 'moveSource') {
this.property(diffItem.actualIndex, inspect(diffItem.value), true)
.amend(delimiterOutput.sp()).error('// should be moved');
} else if (type === 'insert') {
this.annotationBlock(function () {
var index = typeof diffItem.actualIndex !== 'undefined' ? diffItem.actualIndex : diffItem.expectedIndex;
if (expect.findTypeOf(diffItem.value).is('function')) {
this.error('missing: ')
.property(index, output.clone().block(function () {
this.omitSubject = undefined;
var promise = keyPromises[diffItem.expectedIndex];
if (promise.isRejected()) {
this.appendErrorMessage(promise.reason());
} else {
this.appendInspected(diffItem.value);
}
}), true);
} else {
this.error('missing ').property(index, inspect(diffItem.value), true);
}
});
} else {
this.property(diffItem.actualIndex, output.clone().block(function () {
if (type === 'remove') {
this.append(inspect(diffItem.value).amend(delimiterOutput.sp()).error('// should be removed'));
} else if (type === 'equal') {
this.append(inspect(diffItem.value).amend(delimiterOutput));
} else {
var toSatisfyResult = toSatisfyMatrix[diffItem.actualIndex][diffItem.expectedIndex];
var valueDiff = toSatisfyResult && toSatisfyResult !== true && toSatisfyResult.getDiff({ output: output.clone() });
if (valueDiff && valueDiff.inline) {
this.append(valueDiff.amend(delimiterOutput));
} else {
this.append(inspect(diffItem.value).amend(delimiterOutput)).sp().annotationBlock(function () {
this.omitSubject = diffItem.value;
var label = toSatisfyResult.getLabel();
if (label) {
this.error(label).sp()
.block(inspect(diffItem.expected));
if (valueDiff) {
this.nl(2).append(valueDiff);
}
} else {
this.appendErrorMessage(toSatisfyResult);
}
});
}
}
}), true);
}
});
}
}));
if (subjectType.indent) {
output.outdentLines();
}
var suffixOutput = subjectType.suffix(output.clone(), subject);
output
.nl(suffixOutput.isEmpty() ? 0 : 1)
.append(suffixOutput);
return output;
}
});
}
});
});
});
expect.addAssertion('<object> to [exhaustively] satisfy <object>', function (expect, subject, value) {
var valueType = expect.argTypes[0];
var subjectType = expect.subjectType;
var subjectIsArrayLike = subjectType.is('array-like');
if (subject === value) {
return;
}
if (valueType.is('array-like') && !subjectIsArrayLike) {
expect.fail();
}
var promiseByKey = {};
var keys = valueType.getKeys(value);
var subjectKeys = subjectType.getKeys(subject);
if (!subjectIsArrayLike) {
// Find all non-enumerable subject keys present in value, but not returned by subjectType.getKeys:
keys.forEach(function (key) {
if (Object.prototype.hasOwnProperty.call(subject, key) && subjectKeys.indexOf(key) === -1) {
subjectKeys.push(key);
}
});
}
keys.forEach(function (key, index) {
promiseByKey[key] = expect.promise(function () {
var valueKeyType = expect.findTypeOf(value[key]);
if (valueKeyType.is('expect.it')) {
expect.context.thisObject = subject;
return value[key](subject[key], expect.context);
} else if (valueKeyType.is('function')) {
return value[key](subject[key]);
} else {
return expect(subject[key], 'to [exhaustively] satisfy', value[key]);
}
});
});
return expect.promise.all([
expect.promise(function () {
if (expect.flags.exhaustively) {
var nonOwnKeysWithDefinedValues = keys.filter(function (key) {
return !Object.prototype.hasOwnProperty.call(subject, key) && typeof subject[key] !== 'undefined';
});
var valueKeysWithDefinedValues = keys.filter(function (key) {
return typeof value[key] !== 'undefined';
});
var subjectKeysWithDefinedValues = subjectKeys.filter(function (key) {
return typeof subject[key] !== 'undefined';
});
expect(valueKeysWithDefinedValues.length - nonOwnKeysWithDefinedValues.length, 'to equal', subjectKeysWithDefinedValues.length);
}
}),
expect.promise.all(promiseByKey)
]).caught(function () {
return expect.promise.settle(promiseByKey).then(function () {
expect.fail({
diff: function (output, diff, inspect, equal) {
output.inline = true;
var subjectIsArrayLike = subjectType.is('array-like');
var keys = utils.uniqueStringsAndSymbols(subjectKeys, valueType.getKeys(value)).filter(function (key) {
// Skip missing keys expected to be missing so they don't get rendered in the diff
return key in subject || typeof value[key] !== 'undefined';
});
var prefixOutput = subjectType.prefix(output.clone(), subject);
output
.append(prefixOutput)
.nl(prefixOutput.isEmpty() ? 0 : 1);
if (subjectType.indent) {
output.indentLines();
}
keys.forEach(function (key, index) {
output.nl(index > 0 ? 1 : 0).i().block(function () {
var valueOutput;
var annotation = output.clone();
var conflicting;
if (Object.prototype.hasOwnProperty.call(promiseByKey, key) && promiseByKey[key].isRejected()) {
conflicting = promiseByKey[key].reason();
}
var missingArrayIndex = subjectType.is('array-like') && !(key in subject);
var isInlineDiff = true;
output.omitSubject = subject[key];
if (!(key in value)) {
if (expect.flags.exhaustively) {
annotation.error('should be removed');
} else {
conflicting = null;
}
} else if (!(key in subject)) {
if (expect.findTypeOf(value[key]).is('function')) {
if (promiseByKey[key].isRejected()) {
output.error('// missing:').sp();
valueOutput = output.clone().appendErrorMessage(promiseByKey[key].reason());
} else {
output.error('// missing').sp();
valueOutput = output.clone().error('should satisfy').sp().block(inspect(value[key]));
}
} else {
output.error('// missing').sp();
valueOutput = inspect(value[key]);
}
} else if (conflicting || missingArrayIndex) {
var keyDiff = conflicting && conflicting.getDiff({ output: output });
isInlineDiff = !keyDiff || keyDiff.inline ;
if (missingArrayIndex) {
output.error('// missing').sp();
}
if (keyDiff && keyDiff.inline) {
valueOutput = keyDiff;
} else if (typeof value[key] === 'function') {
isInlineDiff = false;
annotation.appendErrorMessage(conflicting);
} else if (!keyDiff || (keyDiff && !keyDiff.inline)) {
annotation.error((conflicting && conflicting.getLabel()) || 'should satisfy').sp()
.block(inspect(value[key]));
if (keyDiff) {
annotation.nl(2).append(keyDiff);
}
} else {
valueOutput = keyDiff;
}
}
if (!valueOutput) {
if (missingArrayIndex || !(key in subject)) {
valueOutput = output.clone();
} else {
valueOutput = inspect(subject[key]);
}
}
var omitDelimiter =
missingArrayIndex ||
index >= subjectKeys.length - 1;
if (!omitDelimiter) {
valueOutput.amend(subjectType.delimiter(output.clone(), index, keys.length));
}
var annotationOnNextLine = !isInlineDiff &&
output.preferredWidth < this.size().width + valueOutput.size().width + annotation.size().width;
if (!annotation.isEmpty()) {
if (!valueOutput.isEmpty()) {
if (annotationOnNextLine) {
valueOutput.nl();
} else {
valueOutput.sp();
}
}
valueOutput.annotationBlock(function () {
this.append(annotation);
});
}
if (!isInlineDiff) {
valueOutput = output.clone().block(valueOutput);
}
this.property(key, valueOutput, subjectIsArrayLike);
});
});
if (subjectType.indent) {
output.outdentLines();
}
var suffixOutput = subjectType.suffix(output.clone(), subject);
return output
.nl(suffixOutput.isEmpty() ? 0 : 1)
.append(suffixOutput);
}
});
});
});
});
function wrapDiffWithTypePrefixAndSuffix(e, type, subject) {
var createDiff = e.getDiffMethod();
if (createDiff) {
return function (output) { // ...
type.prefix.call(type, output, subject);
var result = createDiff.apply(this, arguments);
type.suffix.call(type, output, subject);
return result;
};
}
}
expect.addAssertion('<wrapperObject> to [exhaustively] satisfy <wrapperObject>', function (expect, subject, value) {
var type = expect.findCommonType(subject, value);
expect(type.is('wrapperObject'), 'to be truthy');
return expect.withError(function () {
return expect(type.unwrap(subject), 'to [exhaustively] satisfy', type.unwrap(value));
}, function (e) {
expect.fail({
label: e.getLabel(),
diff: wrapDiffWithTypePrefixAndSuffix(e, type, subject)
});
});
});
expect.addAssertion('<wrapperObject> to [exhaustively] satisfy <any>', function (expect, subject, value) {
var subjectType = expect.subjectType;
return expect.withError(function () {
return expect(subjectType.unwrap(subject), 'to [exhaustively] satisfy', value);
}, function (e) {
expect.fail({
label: e.getLabel(),
diff: wrapDiffWithTypePrefixAndSuffix(e, subjectType, subject)
});
});
});
expect.addAssertion('<function> [when] called with <array-like> <assertion?>', function (expect, subject, args) { // ...
expect.errorMode = 'nested';
expect.argsOutput[0] = function (output) {
output.appendItems(args, ', ');
};
var thisObject = expect.context.thisObject || null;
return expect.shift(subject.apply(thisObject, args));
});
expect.addAssertion('<function> [when] called <assertion?>', function (expect, subject) {
expect.errorMode = 'nested';
var thisObject = expect.context.thisObject || null;
return expect.shift(subject.call(thisObject));
});
function instantiate(Constructor, args) {
function ProxyConstructor() {
return Constructor.apply(this, args);
}
ProxyConstructor.prototype = Constructor.prototype;
return new ProxyConstructor();
}
expect.addAssertion([
'<array-like> [when] passed as parameters to [async] <function> <assertion?>',
'<array-like> [when] passed as parameters to [constructor] <function> <assertion?>'
], function (expect, subject, fn) { // ...
expect.errorMode = 'nested';
var args = subject;
if (expect.flags.async) {
return expect.promise(function (run) {
args = [].concat(args);
args.push(run(function (err, result) {
expect(err, 'to be falsy');
return expect.shift(result);
}));
fn.apply(null, args);
});
} else {
return expect.shift(expect.flags.constructor ? instantiate(fn, args) : fn.apply(fn, args));
}
});
expect.addAssertion([
'<any> [when] passed as parameter to [async] <function> <assertion?>',
'<any> [when] passed as parameter to [constructor] <function> <assertion?>'
], function (expect, subject, fn) { // ...
expect.errorMode = 'nested';
var args = [subject];
if (expect.flags.async) {
return expect.promise(function (run) {
args = [].concat(args);
args.push(run(function (err, result) {
expect(err, 'to be falsy');
return expect.shift(result);
}));
fn.apply(null, args);
});
} else {
return expect.shift(expect.flags.constructor ? instantiate(fn, args) : fn.apply(fn, args));
}
});
expect.addAssertion([
'<array-like> [when] sorted [numerically] <assertion?>',
'<array-like> [when] sorted by <function> <assertion?>'
], function (expect, subject, compareFunction) {
if (expect.flags.numerically) {
compareFunction = function (a, b) {
return a - b;
};
}
return expect.shift(Array.prototype.slice.call(subject).sort(compareFunction));
});
expect.addAssertion('<Promise> to be rejected', function (expect, subject) {
expect.errorMode = 'nested';
return expect.promise(function () {
return subject;
}).then(function (obj) {
expect.fail(function (output) {
output.appendInspected(subject).sp().text('unexpectedly fulfilled');
if (typeof obj !== 'undefined') {
output.sp().text('with').sp().appendInspected(obj);
}
});
}, function (err) {
return err;
});
});
expect.addAssertion('<function> to be rejected', function (expect, subject) {
expect.errorMode = 'nested';
return expect(expect.promise(function () {
return subject();
}), 'to be rejected');
});
expect.addAssertion([
'<Promise> to be rejected with <any>',
'<Promise> to be rejected with error [exhaustively] satisfying <any>'
], function (expect, subject, value) {
expect.errorMode = 'nested';
return expect(subject, 'to be rejected').tap(function (err) {
return expect.withError(function () {
if (err && err._isUnexpected && (typeof value === 'string' || isRegExp(value))) {
return expect(err, 'to have message', value);
} else {
return expect(err, 'to [exhaustively] satisfy', value);
}
}, function (e) {
e.originalError = err;
throw e;
});
});
});
expect.addAssertion([
'<function> to be rejected with <any>',
'<function> to be rejected with error [exhaustively] satisfying <any>'
], function (expect, subject, value) {
expect.errorMode = 'nested';
return expect(expect.promise(function () {
return subject();
}), 'to be rejected with error [exhaustively] satisfying', value);
});
expect.addAssertion('<Promise> to be fulfilled', function (expect, subject) {
expect.errorMode = 'nested';
return expect.promise(function () {
return subject;
}).caught(function (err) {
expect.fail({
output: function (output) {
output.appendInspected(subject).sp().text('unexpectedly rejected');
if (typeof err !== 'undefined') {
output.sp().text('with').sp().appendInspected(err);
}
},
originalError: err
});
});
});
expect.addAssertion('<function> to be fulfilled', function (expect, subject) {
expect.errorMode = 'nested';
return expect(expect.promise(function () {
return subject();
}), 'to be fulfilled');
});
expect.addAssertion([
'<Promise> to be fulfilled with <any>',
'<Promise> to be fulfilled with value [exhaustively] satisfying <any>'
], function (expect, subject, value) {
expect.errorMode = 'nested';
return expect(subject, 'to be fulfilled').tap(function (fulfillmentValue) {
return expect(fulfillmentValue, 'to [exhaustively] satisfy', value);
});
});
expect.addAssertion([
'<function> to be fulfilled with <any>',
'<function> to be fulfilled with value [exhaustively] satisfying <any>'
], function (expect, subject, value) {
expect.errorMode = 'nested';
return expect(expect.promise(function () {
return subject();
}), 'to be fulfilled with value [exhaustively] satisfying', value);
});
expect.addAssertion('<Promise> when rejected <assertion>', function (expect, subject, nextAssertion) {
expect.errorMode = 'nested';
return expect.promise(function () {
return subject;
}).then(function (fulfillmentValue) {
if (typeof nextAssertion === 'string') {
expect.argsOutput = function (output) {
output.error(nextAssertion);
var rest = expect.args.slice(1);
if (rest.length > 0) {
output.sp().appendItems(rest, ', ');
}
};
}
expect.fail(function (output) {
output.appendInspected(subject).sp().text('unexpectedly fulfilled');
if (typeof fulfillmentValue !== 'undefined') {
output.sp().text('with').sp().appendInspected(fulfillmentValue);
}
});
}, function (err) {
return expect.withError(function () {
return expect.shift(err);
}, function (e) {
e.originalError = err;
throw e;
});
});
});
expect.addAssertion('<function> when rejected <assertion>', function (expect, subject) {
expect.errorMode = 'nested';
return expect.apply(expect, [expect.promise(function () {
return subject();
}), 'when rejected'].concat(Array.prototype.slice.call(arguments, 2)));
});
expect.addAssertion('<Promise> when fulfilled <assertion>', function (expect, subject, nextAssertion) {
expect.errorMode = 'nested';
return expect.promise(function () {
return subject;
}).then(function (fulfillmentValue) {
return expect.shift(fulfillmentValue);
}, function (err) {
// typeof nextAssertion === 'string' because expect.it is handled by the above (and shift only supports those two):
expect.argsOutput = function (output) {
output.error(nextAssertion);
var rest = expect.args.slice(1);
if (rest.length > 0) {
output.sp().appendItems(rest, ', ');
}
};
expect.fail({
output: function (output) {
output.appendInspected(subject).sp().text('unexpectedly rejected');
if (typeof err !== 'undefined') {
output.sp().text('with').sp().appendInspected(err);
}
},
originalError: err
});
});
});
expect.addAssertion('<function> when fulfilled <assertion>', function (expect, subject) {
expect.errorMode = 'nested';
return expect.apply(expect, [expect.promise(function () {
return subject();
}), 'when fulfilled'].concat(Array.prototype.slice.call(arguments, 2)));
});
expect.addAssertion('<function> to call the callback', function (expect, subject) {
expect.errorMode = 'nested';
return expect.promise(function (run) {
var async = false;
var calledTwice = false;
var callbackArgs;
function cb() {
if (callbackArgs) {
calledTwice = true;
} else {
callbackArgs = Array.prototype.slice.call(arguments);
}
if (async) {
setTimeout(assert, 0);
}
}
var assert = run(function () {
if (calledTwice) {
expect.fail(function () {
this.error('The callback was called twice');
});
}
return callbackArgs;
});
subject(cb);
async = true;
if (callbackArgs) {
return assert();
}
});
});
expect.addAssertion('<function> to call the callback without error', function (expect, subject) {
return expect(subject, 'to call the callback').then(function (callbackArgs) {
var err = callbackArgs[0];
if (err) {
expect.errorMode = 'nested';
expect.fail({
message: function (output) {
output.error('called the callback with: ');
if (err.getErrorMessage) {
output.appendErrorMessage(err);
} else {
output.appendInspected(err);
}
}
});
} else {
return callbackArgs.slice(1);
}
});
});
expect.addAssertion('<function> to call the callback with error', function (expect, subject) {
return expect(subject, 'to call the callback').spread(function (err) {
expect(err, 'to be truthy');
return err;
});
});
expect.addAssertion('<function> to call the callback with error <any>', function (expect, subject, value) {
return expect(subject, 'to call the callback with error').tap(function (err) {
expect.errorMode = 'nested';
if (err && err._isUnexpected && (typeof value === 'string' || isRegExp(value))) {
return expect(err, 'to have message', value);
} else {
return expect(err, 'to satisfy', value);
}
});
});
};
}).call(this,require(28).Buffer)
},{"16":16,"19":19,"23":23,"24":24,"28":28}],6:[function(require,module,exports){
var AssertionString = require(1);
module.exports = function createStandardErrorMessage(output, subject, testDescription, args, options) {
options = options || {};
var preamble = 'expected';
var subjectOutput = output.clone();
if (subject) {
subject.call(subjectOutput, subjectOutput);
}
var argsOutput = output.clone();
if (typeof args === 'function') {
args.call(argsOutput, argsOutput);
} else {
if (args.length > 0) {
var previousWasAssertion = false;
args.forEach(function (arg, index) {
var isAssertion = arg && typeof arg === 'object' && arg instanceof AssertionString;
if (0 < index) {
if (!isAssertion && !previousWasAssertion) {
argsOutput.text(',');
}
argsOutput.sp();
}
if (isAssertion) {
argsOutput.error(arg.text);
} else {
arg.call(argsOutput, argsOutput);
}
previousWasAssertion = isAssertion;
});
}
}
var subjectSize = subjectOutput.size();
var argsSize = argsOutput.size();
var width = preamble.length + subjectSize.width + argsSize.width + testDescription.length;
var height = Math.max(subjectSize.height, argsSize.height);
if ('omitSubject' in output && output.omitSubject === options.subject) {
var matchTestDescription = /^(not )?to (.*)/.exec(testDescription);
if (matchTestDescription) {
output.error('should ');
if (matchTestDescription[1]) {
output.error('not ');
}
testDescription = matchTestDescription[2];
} else {
testDescription = 'expected: ' + testDescription;
}
} else if (options.compact && options.compactSubject && (subjectSize.height > 1 || subjectSize.width > (options.compactWidth || 35))) {
output.error('expected').sp();
options.compactSubject.call(output, output);
output.sp();
} else {
output.error(preamble);
if (subjectSize.height > 1) {
output.nl();
} else {
output.sp();
}
output.append(subjectOutput);
if (subjectSize.height > 1 || (height === 1 && width > output.preferredWidth)) {
output.nl();
} else {
output.sp();
}
}
output.error(testDescription);
if (argsSize.height > 1) {
output.nl();
} else if (argsSize.width > 0) {
output.sp();
}
output.append(argsOutput);
return output;
};
},{"1":1}],7:[function(require,module,exports){
var createStandardErrorMessage = require(6);
var makePromise = require(11);
var isPendingPromise = require(9);
var oathbreaker = require(13);
var UnexpectedError = require(3);
var addAdditionalPromiseMethods = require(4);
var utils = require(19);
function isAssertionArg(arg) {
return arg.type.is('assertion');
}
function lookupAssertionsInParentChain(assertionString, unexpected) {
var assertions = [];
for (var instance = unexpected ; instance ; instance = instance.parent) {
if (instance.assertions[assertionString]) {
Array.prototype.push.apply(assertions, instance.assertions[assertionString]);
}
}
return assertions;
}
function findSuffixAssertions(assertionString, unexpected) {
if (typeof assertionString !== 'string') {
return null;
}
var straightforwardAssertions = lookupAssertionsInParentChain(assertionString, unexpected);
if (straightforwardAssertions.length > 0) {
return straightforwardAssertions;
}
var tokens = assertionString.split(' ');
for (var n = tokens.length - 1 ; n > 0 ; n -= 1) {
var suffix = tokens.slice(n).join(' ');
var suffixAssertions = lookupAssertionsInParentChain(suffix, unexpected);
if (findSuffixAssertions(tokens.slice(0, n).join(' '), unexpected) && suffixAssertions.length > 0) {
return suffixAssertions;
}
}
return null;
}
module.exports = function createWrappedExpectProto(unexpected) {
var wrappedExpectProto = {
promise: makePromise,
errorMode: 'default',
equal: unexpected.equal,
inspect: unexpected.inspect,
createOutput: unexpected.createOutput.bind(unexpected),
findTypeOf: unexpected.findTypeOf.bind(unexpected),
findTypeOfWithParentType: unexpected.findTypeOfWithParentType.bind(unexpected),
findCommonType: unexpected.findCommonType.bind(unexpected),
it: function () { // ...
var length = arguments.length;
var args = new Array(length);
for (var i = 0 ; i < length ; i += 1) {
args[i] = arguments[i];
}
if (typeof args[0] === 'string') {
args[0] = utils.forwardFlags(args[0], this.flags);
}
return unexpected.it.apply(unexpected, args);
},
diff: unexpected.diff,
getType: unexpected.getType,
output: unexpected.output,
outputFormat: unexpected.outputFormat.bind(unexpected),
format: unexpected.format,
withError: unexpected.withError,
fail: function () {
var args = arguments;
var expect = this.context.expect;
this.callInNestedContext(function () {
expect.fail.apply(expect, args);
});
},
standardErrorMessage: function (output, options) {
var that = this;
options = typeof options === 'object' ? options : {};
if ('omitSubject' in output) {
options.subject = this.subject;
}
if (options && options.compact) {
options.compactSubject = function (output) {
output.jsFunctionName(that.subjectType.name);
};
}
return createStandardErrorMessage(output, that.subjectOutput, that.testDescription, that.argsOutput, options);
},
callInNestedContext: function (callback) {
var that = this;
try {
var result = oathbreaker(callback());
if (isPendingPromise(result)) {
result = result.then(undefined, function (e) {
if (e && e._isUnexpected) {
var wrappedError = new UnexpectedError(that, e);
wrappedError.originalError = e.originalError;
throw wrappedError;
}
throw e;
});
} else if (!result || typeof result.then !== 'function') {
result = makePromise.resolve(result);
}
return addAdditionalPromiseMethods(result, that.execute, that.subject);
} catch (e) {
if (e && e._isUnexpected) {
var wrappedError = new UnexpectedError(that, e);
wrappedError.originalError = e.originalError;
throw wrappedError;
}
throw e;
}
},
shift: function (subject, assertionIndex) {
if (arguments.length <= 1) {
if (arguments.length === 0) {
subject = this.subject;
}
assertionIndex = -1;
for (var i = 0 ; i < this.assertionRule.args.length ; i += 1) {
var type = this.assertionRule.args[i].type;
if (type.is('assertion') || type.is('expect.it')) {
assertionIndex = i;
break;
}
}
} else if (arguments.length === 3) {
// The 3-argument syntax for wrappedExpect.shift is deprecated, please omit the first (expect) arg
subject = arguments[1];
assertionIndex = arguments[2];
}
if (assertionIndex !== -1) {
var args = this.args.slice(0, assertionIndex);
var rest = this.args.slice(assertionIndex);
var nextArgumentType = this.findTypeOf(rest[0]);
if (arguments.length > 1) {
// Legacy
this.argsOutput = function (output) {
args.forEach(function (arg, index) {
if (0 < index) {
output.text(', ');
}
output.appendInspected(arg);
});
if (args.length > 0) {
output.sp();
}
if (nextArgumentType.is('string')) {
output.error(rest[0]);
} else if (rest.length > 0) {
output.appendInspected(rest[0]);
}
if (rest.length > 1) {
output.sp();
}
rest.slice(1).forEach(function (arg, index) {
if (0 < index) {
output.text(', ');
}
output.appendInspected(arg);
});
};
}
if (nextArgumentType.is('expect.it')) {
var that = this;
return this.withError(function () {
return rest[0](subject);
}, function (err) {
that.fail(err);
});
} else if (nextArgumentType.is('string')) {
return this.execute.apply(this.execute, [subject].concat(rest));
} else {
return subject;
}
} else {
// No assertion to delegate to. Provide the new subject as the fulfillment value:
return subject;
}
},
_getSubjectType: function () {
return this.findTypeOfWithParentType(this.subject, this.assertionRule.subject.type);
},
_getArgTypes: function (index) {
var lastIndex = this.assertionRule.args.length - 1;
return this.args.map(function (arg, index) {
return this.findTypeOfWithParentType(arg, this.assertionRule.args[Math.min(index, lastIndex)].type);
}, this);
},
_getAssertionIndices: function () {
if (!this._assertionIndices) {
var assertionIndices = [];
var args = this.args;
var currentAssertionRule = this.assertionRule;
var offset = 0;
OUTER: while (true) {
if (currentAssertionRule.args.length > 1 && isAssertionArg(currentAssertionRule.args[currentAssertionRule.args.length - 2])) {
assertionIndices.push(offset + currentAssertionRule.args.length - 2);
var suffixAssertions = findSuffixAssertions(args[offset + currentAssertionRule.args.length - 2], unexpected);
if (suffixAssertions) {
for (var i = 0 ; i < suffixAssertions.length ; i += 1) {
if (suffixAssertions[i].args.some(isAssertionArg)) {
offset += currentAssertionRule.args.length - 1;
currentAssertionRule = suffixAssertions[i];
continue OUTER;
}
}
}
}
// No further assertions found,
break;
}
this._assertionIndices = assertionIndices;
}
return this._assertionIndices;
}
};
if (Object.__defineGetter__) {
Object.defineProperty(wrappedExpectProto, 'subjectType', {
enumerable: true,
get: function () {
return this.assertionRule && this._getSubjectType();
}
});
Object.defineProperty(wrappedExpectProto, 'argTypes', {
enumerable: true,
get: function () {
return this.assertionRule && this._getArgTypes();
}
});
}
utils.setPrototypeOfOrExtend(wrappedExpectProto, Function.prototype);
return wrappedExpectProto;
};
},{"11":11,"13":13,"19":19,"3":3,"4":4,"6":6,"9":9}],8:[function(require,module,exports){
(function (process){
/*global window*/
var defaultDepth = 3;
var matchDepthParameter =
typeof window !== 'undefined' &&
typeof window.location !== 'undefined' &&
window.location.search.match(/[?&]depth=(\d+)(?:$|&)/);
if (matchDepthParameter) {
defaultDepth = parseInt(matchDepthParameter[1], 10);
} else if (typeof process !== 'undefined' && process.env.UNEXPECTED_DEPTH) {
defaultDepth = parseInt(process.env.UNEXPECTED_DEPTH, 10);
}
module.exports = defaultDepth;
}).call(this,require(53))
},{"53":53}],9:[function(require,module,exports){
module.exports = function isPendingPromise(obj) {
return obj && typeof obj.then === 'function' && typeof obj.isPending === 'function' && obj.isPending();
};
},{}],10:[function(require,module,exports){
module.exports = function makeDiffResultBackwardsCompatible(diff) {
if (diff) {
if (diff.isMagicPen) {
// New format: { [MagicPen], inline: <boolean> }
// Make backwards compatible by adding a 'diff' property that points
// to the instance itself.
diff.diff = diff;
} else {
// Old format: { inline: <boolean>, diff: <magicpen> }
// Upgrade to the new format by moving the inline property to
// the magicpen instance, and remain backwards compatibly by adding
// the diff property pointing to the instance itself.
diff.diff.inline = diff.inline;
diff = diff.diff;
diff.diff = diff;
}
}
return diff;
};
},{}],11:[function(require,module,exports){
var Promise = require(56);
var oathbreaker = require(13);
var throwIfNonUnexpectedError = require(16);
function makePromise(body) {
if (typeof body !== 'function') {
throw new TypeError('expect.promise(...) requires a function argument to be supplied.\n' +
'See http://unexpected.js.org/api/promise/ for more details.');
}
if (body.length === 2) {
return new Promise(body);
}
return new Promise(function (resolve, reject) {
var runningTasks = 0;
var resolvedValue;
var outerFunctionHasReturned = false;
function fulfillIfDone() {
if (outerFunctionHasReturned && runningTasks === 0) {
resolve(resolvedValue);
}
}
function noteResolvedValue(value) {
if (typeof value !== 'undefined' && typeof resolvedValue === 'undefined') {
resolvedValue = value;
}
}
var runner = function (cb) {
runningTasks += 1;
return function () {
runningTasks -= 1;
var result;
try {
if (typeof cb === 'function') {
result = oathbreaker(cb.apply(null, arguments));
if (isPromise(result)) {
runningTasks += 1;
result.then(function (value) {
noteResolvedValue(value);
runningTasks -= 1;
fulfillIfDone();
}, reject);
} else {
noteResolvedValue(result);
}
}
} catch (e) {
return reject(e);
}
fulfillIfDone();
return result;
};
};
try {
var result = oathbreaker(body(runner));
if (isPromise(result)) {
runningTasks += 1;
result.then(function (value) {
noteResolvedValue(value);
runningTasks -= 1;
fulfillIfDone();
}, reject);
} else {
noteResolvedValue(result);
}
} catch (e) {
return reject(e);
}
outerFunctionHasReturned = true;
fulfillIfDone();
});
}
function isPromise(obj) {
return obj && typeof obj === 'object' && typeof obj.then === 'function';
}
function extractPromisesFromObject(obj) {
if (isPromise(obj)) {
return [obj];
} else if (obj && typeof obj === 'object') {
var promises = [];
// Object or Array
Object.keys(obj).forEach(function (key) {
Array.prototype.push.apply(promises, extractPromisesFromObject(obj[key]));
});
return promises;
}
return [];
}
['all', 'any', 'settle'].forEach(function (staticMethodName) {
makePromise[staticMethodName] = function (obj) {
var result = Promise[staticMethodName](extractPromisesFromObject(obj));
if (staticMethodName === 'settle') {
return result.then(function (promises) {
promises.forEach(function (promise) {
if (promise.isRejected()) {
throwIfNonUnexpectedError(promise.reason());
}
});
return promises;
});
}
return result;
};
});
// Expose all of Bluebird's static methods, except the ones related to long stack traces,
// unhandled rejections and the scheduler, which we need to manage ourselves:
Object.keys(Promise).forEach(function (staticMethodName) {
if (!/^_|^on|^setScheduler|ongStackTraces/.test(staticMethodName) && typeof Promise[staticMethodName] === 'function' && typeof makePromise[staticMethodName] === 'undefined') {
makePromise[staticMethodName] = Promise[staticMethodName];
}
});
module.exports = makePromise;
},{"13":13,"16":16,"56":56}],12:[function(require,module,exports){
/*global afterEach, jasmine*/
var pendingPromisesForTheCurrentTest = [];
var afterEachRegistered = false;
var currentSpec = null;
if (typeof jasmine === 'object') {
// Add a custom reporter that allows us to capture the name of the currently executing spec:
jasmine.getEnv().addReporter({
specStarted: function (spec) {
currentSpec = spec;
},
specDone: function (spec) {
currentSpec = null;
}
});
}
function isPendingOrHasUnhandledRejection(promise) {
return promise.isPending() || (promise.isRejected() && promise.reason().uncaught);
}
function registerAfterEachHook() {
if (typeof afterEach === 'function' && !afterEachRegistered) {
afterEachRegistered = true;
try {
afterEach(function () {
var error;
var testPassed = true;
if (pendingPromisesForTheCurrentTest.some(isPendingOrHasUnhandledRejection)) {
var displayName;
if (this.currentTest) {
// mocha
testPassed = this.currentTest.state === 'passed';
displayName = this.currentTest.title;
} else if (typeof currentSpec === 'object') {
testPassed = currentSpec.failedExpectations.length === 0;
displayName = currentSpec.fullName;
}
error = new Error(displayName + ': You have created a promise that was not returned from the it block');
}
pendingPromisesForTheCurrentTest = [];
if (error && testPassed) {
throw error;
}
});
} catch (e) {
// The benchmark suite fails when attempting to add an afterEach
}
}
}
// When running in jasmine/node.js, afterEach is available immediately,
// but doesn't work within the it block. Register the hook immediately:
registerAfterEachHook();
module.exports = function notifyPendingPromise(promise) {
pendingPromisesForTheCurrentTest.push(promise);
// Register the afterEach hook lazily (mocha/node.js):
registerAfterEachHook();
};
},{}],13:[function(require,module,exports){
var workQueue = require(20);
var Promise = require(56);
var useFullStackTrace = require(18);
module.exports = function oathbreaker(value) {
if (!value || typeof value.then !== 'function') {
return value;
}
if (!value.isRejected) {
// this is not a bluebird promise
return value;
}
if (value.isFulfilled()) {
return value;
}
if (value.isRejected()) {
value.caught(function () {
// Ignore - already handled
});
throw value.reason();
}
var onResolve = function () {};
var onReject = function () {};
var evaluated = false;
var error;
value.then(function (obj) {
evaluated = true;
onResolve(value);
}, function (err) {
evaluated = true;
error = err;
onReject(err);
});
workQueue.drain();
if (evaluated && error) {
if (error._isUnexpected && Error.captureStackTrace) {
Error.captureStackTrace(error);
}
throw error;
} else if (evaluated) {
return value;
} else if (value._captureStackTrace && !useFullStackTrace) {
value._captureStackTrace(true);
}
return new Promise(function (resolve, reject) {
onResolve = resolve;
onReject = reject;
});
};
},{"18":18,"20":20,"56":56}],14:[function(require,module,exports){
module.exports = /([\x00-\x09\x0B-\x1F\x7F-\x9F\xAD\u0378\u0379\u037F-\u0383\u038B\u038D\u03A2\u0528-\u0530\u0557\u0558\u0560\u0588\u058B-\u058E\u0590\u05C8-\u05CF\u05EB-\u05EF\u05F5-\u0605\u061C\u061D\u06DD\u070E\u070F\u074B\u074C\u07B2-\u07BF\u07FB-\u07FF\u082E\u082F\u083F\u085C\u085D\u085F-\u089F\u08A1\u08AD-\u08E3\u08FF\u0978\u0980\u0984\u098D\u098E\u0991\u0992\u09A9\u09B1\u09B3-\u09B5\u09BA\u09BB\u09C5\u09C6\u09C9\u09CA\u09CF-\u09D6\u09D8-\u09DB\u09DE\u09E4\u09E5\u09FC-\u0A00\u0A04\u0A0B-\u0A0E\u0A11\u0A12\u0A29\u0A31\u0A34\u0A37\u0A3A\u0A3B\u0A3D\u0A43-\u0A46\u0A49\u0A4A\u0A4E-\u0A50\u0A52-\u0A58\u0A5D\u0A5F-\u0A65\u0A76-\u0A80\u0A84\u0A8E\u0A92\u0AA9\u0AB1\u0AB4\u0ABA\u0ABB\u0AC6\u0ACA\u0ACE\u0ACF\u0AD1-\u0ADF\u0AE4\u0AE5\u0AF2-\u0B00\u0B04\u0B0D\u0B0E\u0B11\u0B12\u0B29\u0B31\u0B34\u0B3A\u0B3B\u0B45\u0B46\u0B49\u0B4A\u0B4E-\u0B55\u0B58-\u0B5B\u0B5E\u0B64\u0B65\u0B78-\u0B81\u0B84\u0B8B-\u0B8D\u0B91\u0B96-\u0B98\u0B9B\u0B9D\u0BA0-\u0BA2\u0BA5-\u0BA7\u0BAB-\u0BAD\u0BBA-\u0BBD\u0BC3-\u0BC5\u0BC9\u0BCE\u0BCF\u0BD1-\u0BD6\u0BD8-\u0BE5\u0BFB-\u0C00\u0C04\u0C0D\u0C11\u0C29\u0C34\u0C3A-\u0C3C\u0C45\u0C49\u0C4E-\u0C54\u0C57\u0C5A-\u0C5F\u0C64\u0C65\u0C70-\u0C77\u0C80\u0C81\u0C84\u0C8D\u0C91\u0CA9\u0CB4\u0CBA\u0CBB\u0CC5\u0CC9\u0CCE-\u0CD4\u0CD7-\u0CDD\u0CDF\u0CE4\u0CE5\u0CF0\u0CF3-\u0D01\u0D04\u0D0D\u0D11\u0D3B\u0D3C\u0D45\u0D49\u0D4F-\u0D56\u0D58-\u0D5F\u0D64\u0D65\u0D76-\u0D78\u0D80\u0D81\u0D84\u0D97-\u0D99\u0DB2\u0DBC\u0DBE\u0DBF\u0DC7-\u0DC9\u0DCB-\u0DCE\u0DD5\u0DD7\u0DE0-\u0DF1\u0DF5-\u0E00\u0E3B-\u0E3E\u0E5C-\u0E80\u0E83\u0E85\u0E86\u0E89\u0E8B\u0E8C\u0E8E-\u0E93\u0E98\u0EA0\u0EA4\u0EA6\u0EA8\u0EA9\u0EAC\u0EBA\u0EBE\u0EBF\u0EC5\u0EC7\u0ECE\u0ECF\u0EDA\u0EDB\u0EE0-\u0EFF\u0F48\u0F6D-\u0F70\u0F98\u0FBD\u0FCD\u0FDB-\u0FFF\u10C6\u10C8-\u10CC\u10CE\u10CF\u1249\u124E\u124F\u1257\u1259\u125E\u125F\u1289\u128E\u128F\u12B1\u12B6\u12B7\u12BF\u12C1\u12C6\u12C7\u12D7\u1311\u1316\u1317\u135B\u135C\u137D-\u137F\u139A-\u139F\u13F5-\u13FF\u169D-\u169F\u16F1-\u16FF\u170D\u1715-\u171F\u1737-\u173F\u1754-\u175F\u176D\u1771\u1774-\u177F\u17DE\u17DF\u17EA-\u17EF\u17FA-\u17FF\u180F\u181A-\u181F\u1878-\u187F\u18AB-\u18AF\u18F6-\u18FF\u191D-\u191F\u192C-\u192F\u193C-\u193F\u1941-\u1943\u196E\u196F\u1975-\u197F\u19AC-\u19AF\u19CA-\u19CF\u19DB-\u19DD\u1A1C\u1A1D\u1A5F\u1A7D\u1A7E\u1A8A-\u1A8F\u1A9A-\u1A9F\u1AAE-\u1AFF\u1B4C-\u1B4F\u1B7D-\u1B7F\u1BF4-\u1BFB\u1C38-\u1C3A\u1C4A-\u1C4C\u1C80-\u1CBF\u1CC8-\u1CCF\u1CF7-\u1CFF\u1DE7-\u1DFB\u1F16\u1F17\u1F1E\u1F1F\u1F46\u1F47\u1F4E\u1F4F\u1F58\u1F5A\u1F5C\u1F5E\u1F7E\u1F7F\u1FB5\u1FC5\u1FD4\u1FD5\u1FDC\u1FF0\u1FF1\u1FF5\u1FFF\u200B-\u200F\u202A-\u202E\u2060-\u206F\u2072\u2073\u208F\u209D-\u209F\u20BA-\u20CF\u20F1-\u20FF\u218A-\u218F\u23F4-\u23FF\u2427-\u243F\u244B-\u245F\u2700\u2B4D-\u2B4F\u2B5A-\u2BFF\u2C2F\u2C5F\u2CF4-\u2CF8\u2D26\u2D28-\u2D2C\u2D2E\u2D2F\u2D68-\u2D6E\u2D71-\u2D7E\u2D97-\u2D9F\u2DA7\u2DAF\u2DB7\u2DBF\u2DC7\u2DCF\u2DD7\u2DDF\u2E3C-\u2E7F\u2E9A\u2EF4-\u2EFF\u2FD6-\u2FEF\u2FFC-\u2FFF\u3040\u3097\u3098\u3100-\u3104\u312E-\u3130\u318F\u31BB-\u31BF\u31E4-\u31EF\u321F\u32FF\u4DB6-\u4DBF\u9FCD-\u9FFF\uA48D-\uA48F\uA4C7-\uA4CF\uA62C-\uA63F\uA698-\uA69E\uA6F8-\uA6FF\uA78F\uA794-\uA79F\uA7AB-\uA7F7\uA82C-\uA82F\uA83A-\uA83F\uA878-\uA87F\uA8C5-\uA8CD\uA8DA-\uA8DF\uA8FC-\uA8FF\uA954-\uA95E\uA97D-\uA97F\uA9CE\uA9DA-\uA9DD\uA9E0-\uA9FF\uAA37-\uAA3F\uAA4E\uAA4F\uAA5A\uAA5B\uAA7C-\uAA7F\uAAC3-\uAADA\uAAF7-\uAB00\uAB07\uAB08\uAB0F\uAB10\uAB17-\uAB1F\uAB27\uAB2F-\uABBF\uABEE\uABEF\uABFA-\uABFF\uD7A4-\uD7AF\uD7C7-\uD7CA\uD7FC-\uF8FF\uFA6E\uFA6F\uFADA-\uFAFF\uFB07-\uFB12\uFB18-\uFB1C\uFB37\uFB3D\uFB3F\uFB42\uFB45\uFBC2-\uFBD2\uFD40-\uFD4F\uFD90\uFD91\uFDC8-\uFDEF\uFDFE\uFDFF\uFE1A-\uFE1F\uFE27-\uFE2F\uFE53\uFE67\uFE6C-\uFE6F\uFE75\uFEFD-\uFF00\uFFBF-\uFFC1\uFFC8\uFFC9\uFFD0\uFFD1\uFFD8\uFFD9\uFFDD-\uFFDF\uFFE7\uFFEF-\uFFFB\uFFFE\uFFFF])/g;
},{}],15:[function(require,module,exports){
var utils = require(19);
var stringDiff = require(34);
var specialCharRegExp = require(14);
module.exports = function (expect) {
expect.installTheme({ styles: {
jsBoolean: 'jsPrimitive',
jsNumber: 'jsPrimitive',
error: ['red', 'bold'],
success: ['green', 'bold'],
diffAddedLine: 'green',
diffAddedHighlight: ['bgGreen', 'white'],
diffAddedSpecialChar: ['bgGreen', 'cyan', 'bold'],
diffRemovedLine: 'red',
diffRemovedHighlight: ['bgRed', 'white'],
diffRemovedSpecialChar: ['bgRed', 'cyan', 'bold'],
partialMatchHighlight: ['bgYellow']
}});
expect.installTheme('html', {
palette: [
'#993333', '#669933', '#314575', '#337777', '#710071', '#319916',
'#BB1A53', '#999933', '#4311C2', '#996633', '#993399', '#333399',
'#228842', '#C24747', '#336699', '#663399'
],
styles: {
jsComment: '#969896',
jsFunctionName: '#795da3',
jsKeyword: '#a71d5d',
jsPrimitive: '#0086b3',
jsRegexp: '#183691',
jsString: '#df5000',
jsKey: '#555'
}
});
expect.installTheme('ansi', {
palette: [
'#FF1A53', '#E494FF', '#1A53FF', '#FF1AC6', '#1AFF53', '#D557FF',
'#81FF57', '#C6FF1A', '#531AFF', '#AFFF94', '#C61AFF', '#53FF1A',
'#FF531A', '#1AFFC6', '#FFC61A', '#1AC6FF'
],
styles: {
jsComment: 'gray',
jsFunctionName: 'jsKeyword',
jsKeyword: 'magenta',
jsNumber: [],
jsPrimitive: 'cyan',
jsRegexp: 'green',
jsString: 'cyan',
jsKey: '#666',
diffAddedHighlight: ['bgGreen', 'black'],
diffRemovedHighlight: ['bgRed', 'black'],
partialMatchHighlight: ['bgYellow', 'black']
}
});
expect.addStyle('colorByIndex', function (content, index) {
var palette = this.theme().palette;
if (palette) {
var color = palette[index % palette.length];
this.text(content, color);
} else {
this.text(content);
}
});
expect.addStyle('singleQuotedString', function (content) {
content = String(content);
this.jsString("'")
.jsString(content.replace(/[\\\x00-\x1f']/g, function ($0) {
if ($0 === '\n') {
return '\\n';
} else if ($0 === '\r') {
return '\\r';
} else if ($0 === "'") {
return "\\'";
} else if ($0 === '\\') {
return '\\\\';
} else if ($0 === '\t') {
return '\\t';
} else if ($0 === '\b') {
return '\\b';
} else if ($0 === '\f') {
return '\\f';
} else {
var charCode = $0.charCodeAt(0);
return '\\x' + (charCode < 16 ? '0' : '') + charCode.toString(16);
}
}))
.jsString("'");
});
expect.addStyle('property', function (key, inspectedValue, isArrayLike) {
var keyOmitted = false;
var isSymbol;
isSymbol = typeof key === 'symbol';
if (isSymbol) {
this.text('[').sp().appendInspected(key).sp().text(']').text(':');
} else {
key = String(key);
if (/^[a-z\$\_][a-z0-9\$\_]*$/i.test(key)) {
this.text(key, 'jsKey').text(':');
} else if (/^(?:0|[1-9][0-9]*)$/.test(key)) {
if (isArrayLike) {
keyOmitted = true;
} else {
this.jsNumber(key).text(':');
}
} else {
this.singleQuotedString(key).text(':');
}
}
if (!inspectedValue.isEmpty()) {
if (!keyOmitted) {
if (key.length > 5 && inspectedValue.isBlock() && inspectedValue.isMultiline()) {
this.indentLines();
this.nl().i();
} else {
this.sp();
}
}
this.append(inspectedValue);
}
});
// Intended to be redefined by a plugin that offers syntax highlighting:
expect.addStyle('code', function (content, language) {
this.text(content);
});
expect.addStyle('annotationBlock', function () {
var pen = this.getContentFromArguments(arguments);
var height = pen.size().height;
this.block(function () {
for (var i = 0; i < height; i += 1) {
if (0 < i) {
this.nl();
}
this.error('//');
}
});
this.sp().block(pen);
});
expect.addStyle('commentBlock', function () {
var pen = this.getContentFromArguments(arguments);
var height = pen.size().height;
this.block(function () {
for (var i = 0; i < height; i += 1) {
if (0 < i) {
this.nl();
}
this.jsComment('//');
}
});
this.sp().block(pen);
});
expect.addStyle('removedHighlight', function (content) {
this.alt({
text: function () {
content.split(/(\n)/).forEach(function (fragment) {
if (fragment === '\n') {
this.nl();
} else {
this.block(function () {
this.text(fragment).nl().text(fragment.replace(/[\s\S]/g, '^'));
});
}
}, this);
},
fallback: function () {
this.diffRemovedHighlight(content);
}
});
});
expect.addStyle('match', function (content) {
this.alt({
text: function () {
content.split(/(\n)/).forEach(function (fragment) {
if (fragment === '\n') {
this.nl();
} else {
this.block(function () {
this.text(fragment).nl().text(fragment.replace(/[\s\S]/g, '^'));
});
}
}, this);
},
fallback: function () {
this.diffAddedHighlight(content);
}
});
});
expect.addStyle('partialMatch', function (content) {
this.alt({
text: function () {
// We haven't yet come up with a good styling for partial matches in text mode
this.match(content);
},
fallback: function () {
this.partialMatchHighlight(content);
}
});
});
expect.addStyle('shouldEqualError', function (expected) {
this.error(typeof expected === 'undefined' ? 'should be' : 'should equal').sp().block(function () {
this.appendInspected(expected);
});
});
expect.addStyle('errorName', function (error) {
if (typeof error.name === 'string' && error.name !== 'Error') {
this.text(error.name);
} else if (error.constructor && typeof error.constructor.name === 'string') {
this.text(error.constructor.name);
} else {
this.text('Error');
}
});
expect.addStyle('appendErrorMessage', function (error, options) {
if (error && error.isUnexpected) {
this.append(error.getErrorMessage(utils.extend({ output: this }, options)));
} else {
this.appendInspected(error);
}
});
expect.addStyle('appendItems', function (items, separator) {
var that = this;
separator = separator || '';
items.forEach(function (item, index) {
if (0 < index) {
that.append(separator);
}
that.appendInspected(item);
});
});
expect.addStyle('stringDiffFragment', function (ch, text, baseStyle, markUpSpecialCharacters) {
text.split(/\n/).forEach(function (line, i, lines) {
if (this.isAtStartOfLine()) {
this.alt({
text: ch,
fallback: function () {
if (line === '' && ch !== ' ' && (i === 0 || i !== lines.length - 1)) {
this[ch === '+' ? 'diffAddedSpecialChar' : 'diffRemovedSpecialChar']('\\n');
}
}
});
}
var matchTrailingSpace = line.match(/^(.*[^ ])?( +)$/);
if (matchTrailingSpace) {
line = matchTrailingSpace[1] || '';
}
if (markUpSpecialCharacters) {
line.split(specialCharRegExp).forEach(function (part) {
if (specialCharRegExp.test(part)) {
this[{'+': 'diffAddedSpecialChar', '-': 'diffRemovedSpecialChar'}[ch] || baseStyle](utils.escapeChar(part));
} else {
this[baseStyle](part);
}
}, this);
} else {
this[baseStyle](line);
}
if (matchTrailingSpace) {
this[{'+': 'diffAddedHighlight', '-': 'diffRemovedHighlight'}[ch] || baseStyle](matchTrailingSpace[2]);
}
if (i !== lines.length - 1) {
this.nl();
}
}, this);
});
expect.addStyle('stringDiff', function (actual, expected, options) {
options = options || {};
var type = options.type || 'WordsWithSpace';
var diffLines = [];
var lastPart;
stringDiff.diffLines(actual, expected).forEach(function (part) {
if (lastPart && lastPart.added && part.removed) {
diffLines.push({
oldValue: part.value,
newValue: lastPart.value,
replaced: true
});
lastPart = null;
} else {
if (lastPart) {
diffLines.push(lastPart);
}
lastPart = part;
}
});
if (lastPart) {
diffLines.push(lastPart);
}
diffLines.forEach(function (part, index) {
if (part.replaced) {
var oldValue = part.oldValue;
var newValue = part.newValue;
var newLine = this.clone();
var oldEndsWithNewline = oldValue.slice(-1) === '\n';
var newEndsWithNewline = newValue.slice(-1) === '\n';
if (oldEndsWithNewline) {
oldValue = oldValue.slice(0, -1);
}
if (newEndsWithNewline) {
newValue = newValue.slice(0, -1);
}
stringDiff['diff' + type](oldValue, newValue).forEach(function (part) {
if (part.added) {
newLine.stringDiffFragment('+', part.value, 'diffAddedHighlight', options.markUpSpecialCharacters);
} else if (part.removed) {
this.stringDiffFragment('-', part.value, 'diffRemovedHighlight', options.markUpSpecialCharacters);
} else {
newLine.stringDiffFragment('+', part.value, 'diffAddedLine');
this.stringDiffFragment('-', part.value, 'diffRemovedLine');
}
}, this);
if (newEndsWithNewline && !oldEndsWithNewline) {
newLine.diffAddedSpecialChar('\\n');
}
if (oldEndsWithNewline && !newEndsWithNewline) {
this.diffRemovedSpecialChar('\\n');
}
this.nl().append(newLine).nl(oldEndsWithNewline && index < diffLines.length - 1 ? 1 : 0);
} else {
var endsWithNewline = /\n$/.test(part.value);
var value = endsWithNewline ?
part.value.slice(0, -1) :
part.value;
if (part.added) {
this.stringDiffFragment('+', value, 'diffAddedLine', options.markUpSpecialCharacters);
} else if (part.removed) {
this.stringDiffFragment('-', value, 'diffRemovedLine', options.markUpSpecialCharacters);
} else {
this.stringDiffFragment(' ', value, 'text');
}
if (endsWithNewline) {
this.nl();
}
}
}, this);
});
expect.addStyle('arrow', function (options) {
options = options || {};
var styles = options.styles || [];
var i;
this.nl(options.top || 0).sp(options.left || 0).text('┌', styles);
for (i = 1 ; i < options.width ; i += 1) {
this.text(i === options.width - 1 && options.direction === 'up' ? '▷' : '─', styles);
}
this.nl();
for (i = 1 ; i < options.height - 1 ; i += 1) {
this.sp(options.left || 0).text('│', styles).nl();
}
this.sp(options.left || 0).text('└', styles);
for (i = 1 ; i < options.width ; i += 1) {
this.text(i === options.width - 1 && options.direction === 'down' ? '▷' : '─', styles);
}
});
var flattenBlocksInLines = require(48);
expect.addStyle('merge', function (pens) {
var flattenedPens = pens.map(function (pen) {
return flattenBlocksInLines(pen.output);
}).reverse();
var maxHeight = flattenedPens.reduce(function (maxHeight, pen) {
return Math.max(maxHeight, pen.length);
}, 0);
var blockNumbers = new Array(flattenedPens.length);
var blockOffsets = new Array(flattenedPens.length);
// As long as there's at least one pen with a line left:
for (var lineNumber = 0 ; lineNumber < maxHeight ; lineNumber += 1) {
if (lineNumber > 0) {
this.nl();
}
var i;
for (i = 0 ; i < blockNumbers.length ; i += 1) {
blockNumbers[i] = 0;
blockOffsets[i] = 0;
}
var contentLeft;
do {
contentLeft = false;
var hasOutputChar = false;
for (i = 0 ; i < flattenedPens.length ; i += 1) {
var currentLine = flattenedPens[i][lineNumber];
if (currentLine) {
while (currentLine[blockNumbers[i]] && blockOffsets[i] >= currentLine[blockNumbers[i]].args.content.length) {
blockNumbers[i] += 1;
blockOffsets[i] = 0;
}
var currentBlock = currentLine[blockNumbers[i]];
if (currentBlock) {
contentLeft = true;
if (!hasOutputChar) {
var ch = currentBlock.args.content.charAt(blockOffsets[i]);
if (ch !== ' ') {
this.text(ch, currentBlock.args.styles);
hasOutputChar = true;
}
}
blockOffsets[i] += 1;
}
}
}
if (!hasOutputChar && contentLeft) {
this.sp();
}
} while (contentLeft);
}
});
expect.addStyle('arrowsAlongsideChangeOutputs', function (packing, changeOutputs) {
if (packing) {
var topByChangeNumber = {};
var top = 0;
changeOutputs.forEach(function (changeOutput, index) {
topByChangeNumber[index] = top;
top += changeOutput.size().height;
});
var that = this;
var arrows = [];
packing.forEach(function (columnSet, i, packing) {
columnSet.forEach(function (entry) {
arrows.push(that.clone().arrow({
left: i * 2,
top: topByChangeNumber[entry.start],
width: 1 + (packing.length - i) * 2,
height: topByChangeNumber[entry.end] - topByChangeNumber[entry.start] + 1,
direction: entry.direction
}));
});
});
if (arrows.length === 1) {
this.block(arrows[0]);
} else if (arrows.length > 1) {
this.block(function () {
this.merge(arrows);
});
}
} else {
this.i();
}
this.block(function () {
changeOutputs.forEach(function (changeOutput, index) {
this.nl(index > 0 ? 1 : 0);
if (!changeOutput.isEmpty()) {
this.sp(packing ? 1 : 0).append(changeOutput);
}
}, this);
});
});
};
},{"14":14,"19":19,"34":34,"48":48}],16:[function(require,module,exports){
module.exports = function throwIfNonUnexpectedError(err) {
if (err && err.message === 'aggregate error') {
for (var i = 0 ; i < err.length ; i += 1) {
throwIfNonUnexpectedError(err[i]);
}
} else if (!err || !err._isUnexpected) {
throw err;
}
};
},{}],17:[function(require,module,exports){
(function (Buffer){
var utils = require(19);
var isRegExp = utils.isRegExp;
var leftPad = utils.leftPad;
var arrayChanges = require(24);
var leven = require(40);
var detectIndent = require(33);
var defaultDepth = require(8);
var AssertionString = require(1);
module.exports = function (expect) {
expect.addType({
name: 'wrapperObject',
identify: false,
equal: function (a, b, equal) {
return a === b || equal(this.unwrap(a), this.unwrap(b));
},
inspect: function (value, depth, output, inspect) {
output.append(this.prefix(output.clone(), value));
output.append(inspect(this.unwrap(value), depth));
output.append(this.suffix(output.clone(), value));
return output;
},
diff: function (actual, expected, output, diff, inspect) {
output.inline = true;
actual = this.unwrap(actual);
expected = this.unwrap(expected);
var comparison = diff(actual, expected);
var prefixOutput = this.prefix(output.clone(), actual);
var suffixOutput = this.suffix(output.clone(), actual);
if (comparison && comparison.inline) {
return output.append(prefixOutput).append(comparison).append(suffixOutput);
} else {
return output.append(prefixOutput).nl()
.indentLines()
.i().block(function () {
this.append(inspect(actual)).sp().annotationBlock(function () {
this.shouldEqualError(expected, inspect);
if (comparison) {
this.nl(2).append(comparison);
}
});
}).nl()
.outdentLines()
.append(suffixOutput);
}
}
});
if (typeof Symbol === 'function') {
expect.addType({
name: 'Symbol',
identify: function (obj) {
return typeof obj === 'symbol';
},
inspect: function (obj, depth, output, inspect) {
return output
.jsKeyword('Symbol')
.text('(')
.singleQuotedString(obj.toString().replace(/^Symbol\(|\)$/g, ''))
.text(')');
}
});
}
// If Symbol support is not detected, default to passing undefined to
// Array.prototype.sort, which means "natural" (asciibetical) sort.
var keyComparator;
if (typeof Symbol === 'function') {
// Comparator that puts symbols last:
keyComparator = function (a, b) {
var aIsSymbol, bIsSymbol;
var aString = a;
var bString = b;
aIsSymbol = typeof a === 'symbol';
bIsSymbol = typeof b === 'symbol';
if (aIsSymbol) {
if (bIsSymbol) {
aString = a.toString();
bString = b.toString();
} else {
return 1;
}
} else if (bIsSymbol) {
return -1;
}
if (aString < bString) {
return -1;
} else if (aString > bString) {
return 1;
}
return 0;
};
}
expect.addType({
name: 'object',
indent: true,
forceMultipleLines: false,
identify: function (obj) {
return obj && typeof obj === 'object';
},
prefix: function (output, obj) {
var constructor = obj.constructor;
var constructorName = constructor && typeof constructor === 'function' && constructor !== Object && utils.getFunctionName(constructor);
if (constructorName && constructorName !== 'Object') {
output.text(constructorName + '(');
}
return output.text('{');
},
suffix: function (output, obj) {
output.text('}');
var constructor = obj.constructor;
var constructorName = constructor && typeof constructor === 'function' && constructor !== Object && utils.getFunctionName(constructor);
if (constructorName && constructorName !== 'Object') {
output.text(')');
}
return output;
},
delimiter: function (output, i, length) {
if (i < length - 1) {
output.text(',');
}
return output;
},
getKeys: Object.getOwnPropertySymbols ? function (obj) {
var keys = Object.keys(obj);
var symbols = Object.getOwnPropertySymbols(obj);
if (symbols.length > 0) {
return keys.concat(symbols);
} else {
return keys;
}
} : Object.keys,
equal: function (a, b, equal) {
if (a === b) {
return true;
}
if (b.constructor !== a.constructor) {
return false;
}
var actualKeys = this.getKeys(a).filter(function (key) {
return typeof a[key] !== 'undefined';
}),
expectedKeys = this.getKeys(b).filter(function (key) {
return typeof b[key] !== 'undefined';
});
// having the same number of owned properties (keys incorporates hasOwnProperty)
if (actualKeys.length !== expectedKeys.length) {
return false;
}
//the same set of keys (although not necessarily the same order),
actualKeys.sort(keyComparator);
expectedKeys.sort(keyComparator);
// cheap key test
for (var i = 0; i < actualKeys.length; i += 1) {
if (actualKeys[i] !== expectedKeys[i]) {
return false;
}
}
//equivalent values for every corresponding key, and
// possibly expensive deep test
for (var j = 0; j < actualKeys.length; j += 1) {
var key = actualKeys[j];
if (!equal(a[key], b[key])) {
return false;
}
}
return true;
},
inspect: function (obj, depth, output, inspect) {
var keys = this.getKeys(obj);
if (keys.length === 0) {
this.prefix(output, obj);
this.suffix(output, obj);
return output;
}
var type = this;
var inspectedItems = keys.map(function (key, index) {
var propertyDescriptor = Object.getOwnPropertyDescriptor && Object.getOwnPropertyDescriptor(obj, key);
var hasGetter = propertyDescriptor && propertyDescriptor.get;
var hasSetter = propertyDescriptor && propertyDescriptor.set;
var propertyOutput = output.clone();
if (hasSetter && !hasGetter) {
propertyOutput.text('set').sp();
}
// Inspect the setter function if there's no getter:
var value = (hasSetter && !hasGetter) ? hasSetter : obj[key];
var inspectedValue = inspect(value);
if (value && value._expectIt) {
inspectedValue = output.clone().block(inspectedValue);
}
propertyOutput.property(key, inspectedValue);
propertyOutput.amend(type.delimiter(output.clone(), index, keys.length));
if (hasGetter && hasSetter) {
propertyOutput.sp().jsComment('/* getter/setter */');
} else if (hasGetter) {
propertyOutput.sp().jsComment('/* getter */');
}
return propertyOutput;
});
var maxLineLength = output.preferredWidth - (depth === Infinity ? 0 : depth) * 2 - 2;
var width = 0;
var compact = inspectedItems.length > 5 || inspectedItems.every(function (inspectedItem) {
if (inspectedItem.isMultiline()) {
return false;
}
width += inspectedItem.size().width;
return width < maxLineLength;
});
var itemsOutput = output.clone();
if (compact) {
var currentLineLength = 0;
inspectedItems.forEach(function (inspectedItem, index) {
var size = inspectedItem.size();
currentLineLength += size.width + 1;
if (index > 0) {
if (size.height === 1 && currentLineLength < maxLineLength) {
itemsOutput.sp();
} else {
itemsOutput.nl();
currentLineLength = size.width;
}
if (size.height > 1) {
// Make sure that we don't append more to this line
currentLineLength = maxLineLength;
}
}
itemsOutput.append(inspectedItem);
});
} else {
inspectedItems.forEach(function (inspectedItem, index) {
if (index > 0) {
itemsOutput.nl();
}
itemsOutput.append(inspectedItem);
});
}
var prefixOutput = this.prefix(output.clone(), obj);
var suffixOutput = this.suffix(output.clone(), obj);
output.append(prefixOutput);
if (this.forceMultipleLines || itemsOutput.isMultiline()) {
if (!prefixOutput.isEmpty()) {
output.nl();
}
if (this.indent) {
output.indentLines().i();
}
output.block(itemsOutput);
if (this.indent) {
output.outdentLines();
}
if (!suffixOutput.isEmpty()) {
output.nl();
}
} else {
output
.sp(prefixOutput.isEmpty() ? 0 : 1)
.append(itemsOutput)
.sp(suffixOutput.isEmpty() ? 0 : 1);
}
return output.append(suffixOutput);
},
diff: function (actual, expected, output, diff, inspect, equal) {
if (actual.constructor !== expected.constructor) {
return output.text('Mismatching constructors ')
.text(actual.constructor && utils.getFunctionName(actual.constructor) || actual.constructor)
.text(' should be ').text(expected.constructor && utils.getFunctionName(expected.constructor) || expected.constructor);
}
output.inline = true;
var actualKeys = this.getKeys(actual);
var keys = utils.uniqueStringsAndSymbols(actualKeys, this.getKeys(expected));
var prefixOutput = this.prefix(output.clone(), actual);
output
.append(prefixOutput)
.nl(prefixOutput.isEmpty() ? 0 : 1);
if (this.indent) {
output.indentLines();
}
var type = this;
keys.forEach(function (key, index) {
output.nl(index > 0 ? 1 : 0).i().block(function () {
var valueOutput;
var annotation = output.clone();
var conflicting = !equal(actual[key], expected[key]);
var isInlineDiff = false;
if (conflicting) {
if (!(key in expected)) {
annotation.error('should be removed');
isInlineDiff = true;
} else if (!(key in actual)) {
this.error('// missing').sp();
valueOutput = output.clone().appendInspected(expected[key]);
isInlineDiff = true;
} else {
var keyDiff = diff(actual[key], expected[key]);
if (!keyDiff || (keyDiff && !keyDiff.inline)) {
annotation.shouldEqualError(expected[key]);
if (keyDiff) {
annotation.nl(2).append(keyDiff);
}
} else {
isInlineDiff = true;
valueOutput = keyDiff;
}
}
} else {
isInlineDiff = true;
}
if (!valueOutput) {
valueOutput = inspect(actual[key], conflicting ? Infinity : null);
}
valueOutput.amend(type.delimiter(output.clone(), index, actualKeys.length));
if (!isInlineDiff) {
valueOutput = output.clone().block(valueOutput);
}
this.property(key, valueOutput);
if (!annotation.isEmpty()) {
this.sp().annotationBlock(annotation);
}
});
});
if (this.indent) {
output.outdentLines();
}
var suffixOutput = this.suffix(output.clone(), actual);
return output
.nl(suffixOutput.isEmpty() ? 0 : 1)
.append(suffixOutput);
},
similar: function (a, b) {
if (a === null || b === null) {
return false;
}
var typeA = typeof a;
var typeB = typeof b;
if (typeA !== typeB) {
return false;
}
if (typeA === 'string') {
return leven(a, b) < a.length / 2;
}
if (typeA !== 'object' || !a) {
return false;
}
if (utils.isArray(a) && utils.isArray(b)) {
return true;
}
var aKeys = this.getKeys(a);
var bKeys = this.getKeys(b);
var numberOfSimilarKeys = 0;
var requiredSimilarKeys = Math.round(Math.max(aKeys.length, bKeys.length) / 2);
return aKeys.concat(bKeys).some(function (key) {
if (key in a && key in b) {
numberOfSimilarKeys += 1;
}
return numberOfSimilarKeys >= requiredSimilarKeys;
});
}
});
expect.addType({
name: 'type',
base: 'object',
identify: function (value) {
return value && value._unexpectedType;
},
inspect: function (value, depth, output) {
return output.text('type: ').jsKeyword(value.name);
}
});
expect.addType({
name: 'array-like',
base: 'object',
identify: false,
numericalPropertiesOnly: true,
getKeys: function (obj) {
var keys = new Array(obj.length);
for (var i = 0 ; i < obj.length ; i += 1) {
keys[i] = i;
}
if (!this.numericalPropertiesOnly) {
Object.keys(obj).forEach(function (key) {
if (!utils.numericalRegExp.test(key)) {
keys.push(key);
}
});
}
return keys;
},
equal: function (a, b, equal) {
if (a === b) {
return true;
} else if (a.constructor === b.constructor && a.length === b.length) {
var i;
if (this.numericalPropertiesOnly) {
for (i = 0; i < a.length; i += 1) {
if (!equal(a[i], b[i])) {
return false;
}
}
} else {
var aKeys = this.getKeys(a);
var bKeys = this.getKeys(b);
if (aKeys.length !== bKeys.length) {
return false;
}
for (i = 0; i < aKeys.length; i += 1) {
if (!equal(a[aKeys[i]], b[aKeys[i]])) {
return false;
}
}
}
return true;
} else {
return false;
}
},
prefix: function (output) {
return output.text('[');
},
suffix: function (output) {
return output.text(']');
},
inspect: function (arr, depth, output, inspect) {
var prefixOutput = this.prefix(output.clone(), arr);
var suffixOutput = this.suffix(output.clone(), arr);
var keys = this.getKeys(arr);
if (keys.length === 0) {
return output.append(prefixOutput).append(suffixOutput);
}
if (depth === 1 && arr.length > 10) {
return output.append(prefixOutput).text('...').append(suffixOutput);
}
var inspectedItems = keys.map(function (key) {
var inspectedValue;
if (key in arr) {
inspectedValue = inspect(arr[key]);
} else if (utils.numericalRegExp.test(key)) {
// Sparse array entry
inspectedValue = output.clone();
} else {
// Not present non-numerical property returned by getKeys
inspectedValue = inspect(undefined);
}
return output.clone().property(key, inspectedValue, true);
});
var currentDepth = defaultDepth - Math.min(defaultDepth, depth);
var maxLineLength = (output.preferredWidth - 20) - currentDepth * output.indentationWidth - 2;
var width = 0;
var multipleLines = this.forceMultipleLines || inspectedItems.some(function (o) {
if (o.isMultiline()) {
return true;
}
var size = o.size();
width += size.width;
return width > maxLineLength;
});
var type = this;
inspectedItems.forEach(function (inspectedItem, index) {
inspectedItem.amend(type.delimiter(output.clone(), index, keys.length));
});
if (multipleLines) {
output.append(prefixOutput);
if (!prefixOutput.isEmpty()) {
output.nl();
}
if (this.indent) {
output.indentLines();
}
inspectedItems.forEach(function (inspectedItem, index) {
output.nl(index > 0 ? 1 : 0).i().block(inspectedItem);
});
if (this.indent) {
output.outdentLines();
}
if (!suffixOutput.isEmpty()) {
output.nl();
}
return output.append(suffixOutput);
} else {
output
.append(prefixOutput)
.sp(prefixOutput.isEmpty() ? 0 : 1);
inspectedItems.forEach(function (inspectedItem, index) {
output.append(inspectedItem);
var lastIndex = index === inspectedItems.length - 1;
if (!lastIndex) {
output.sp();
}
});
return output
.sp(suffixOutput.isEmpty() ? 0 : 1)
.append(suffixOutput);
}
},
diffLimit: 512,
diff: function (actual, expected, output, diff, inspect, equal) {
output.inline = true;
if (Math.max(actual.length, expected.length) > this.diffLimit) {
output.jsComment('Diff suppressed due to size > ' + this.diffLimit);
return output;
}
if (actual.constructor !== expected.constructor) {
return this.baseType.diff(actual, expected, output);
}
var prefixOutput = this.prefix(output.clone(), actual);
output
.append(prefixOutput)
.nl(prefixOutput.isEmpty() ? 0 : 1);
if (this.indent) {
output.indentLines();
}
var type = this;
var changes = arrayChanges(actual, expected, equal, function (a, b) {
return type.similar(a, b);
}, !type.numericalPropertiesOnly && utils.uniqueNonNumericalStringsAndSymbols(this.getKeys(actual), this.getKeys(expected)));
var indexOfLastNonInsert = changes.reduce(function (previousValue, diffItem, index) {
return (diffItem.type === 'insert') ? previousValue : index;
}, -1);
var packing = utils.packArrows(changes); // NOTE: Will have side effects in changes if the packing results in too many arrow lanes
output.arrowsAlongsideChangeOutputs(packing, changes.map(function (diffItem, index) {
var delimiterOutput = type.delimiter(output.clone(), index, indexOfLastNonInsert + 1);
if (diffItem.type === 'moveTarget') {
return output.clone();
} else {
return output.clone().block(function () {
if (diffItem.type === 'moveSource') {
this.property(diffItem.actualIndex, inspect(diffItem.value), true)
.amend(delimiterOutput.sp()).error('// should be moved');
} else if (diffItem.type === 'insert') {
this.annotationBlock(function () {
this.error('missing ').block(function () {
var index = typeof diffItem.actualIndex !== 'undefined' ? diffItem.actualIndex : diffItem.expectedIndex;
this.property(index, inspect(diffItem.value), true);
});
});
} else if (diffItem.type === 'remove') {
this.block(function () {
this.property(diffItem.actualIndex, inspect(diffItem.value), true)
.amend(delimiterOutput.sp()).error('// should be removed');
});
} else if (diffItem.type === 'equal') {
this.block(function () {
this.property(diffItem.actualIndex, inspect(diffItem.value), true)
.amend(delimiterOutput);
});
} else {
this.block(function () {
var valueDiff = diff(diffItem.value, diffItem.expected);
this.property(diffItem.actualIndex, output.clone().block(function () {
if (valueDiff && valueDiff.inline) {
this.append(valueDiff.amend(delimiterOutput));
} else if (valueDiff) {
this.append(inspect(diffItem.value).amend(delimiterOutput.sp())).annotationBlock(function () {
this.shouldEqualError(diffItem.expected, inspect).nl(2).append(valueDiff);
});
} else {
this.append(inspect(diffItem.value).amend(delimiterOutput.sp())).annotationBlock(function () {
this.shouldEqualError(diffItem.expected, inspect);
});
}
}), true);
});
}
});
}
}));
if (this.indent) {
output.outdentLines();
}
var suffixOutput = this.suffix(output.clone(), actual);
return output
.nl(suffixOutput.isEmpty() ? 0 : 1)
.append(suffixOutput);
}
});
expect.addType({
name: 'array',
base: 'array-like',
numericalPropertiesOnly: false,
identify: function (arr) {
return utils.isArray(arr);
}
});
expect.addType({
name: 'arguments',
base: 'array-like',
prefix: function (output) {
return output.text('arguments(', 'cyan');
},
suffix: function (output) {
return output.text(')', 'cyan');
},
identify: function (obj) {
return Object.prototype.toString.call(obj) === '[object Arguments]';
}
});
var errorMethodBlacklist = ['message', 'name', 'description', 'line', 'column', 'sourceId', 'sourceURL', 'stack', 'stackArray'].reduce(function (result, prop) {
result[prop] = true;
return result;
}, {});
expect.addType({
base: 'object',
name: 'Error',
identify: function (value) {
return utils.isError(value);
},
getKeys: function (value) {
var keys = this.baseType.getKeys(value).filter(function (key) {
return !errorMethodBlacklist[key];
});
keys.unshift('message');
return keys;
},
unwrap: function (value) {
return this.getKeys(value).reduce(function (result, key) {
result[key] = value[key];
return result;
}, {});
},
equal: function (a, b, equal) {
return a === b ||
(equal(a.message, b.message) && this.baseType.equal(a, b));
},
inspect: function (value, depth, output, inspect) {
output.errorName(value).text('(');
var keys = this.getKeys(value);
if (keys.length === 1 && keys[0] === 'message') {
if (value.message !== '') {
output.append(inspect(value.message));
}
} else {
output.append(inspect(this.unwrap(value), depth));
}
return output.text(')');
},
diff: function (actual, expected, output, diff) {
if (actual.constructor !== expected.constructor) {
return output.text('Mismatching constructors ')
.errorName(actual)
.text(' should be ').errorName(expected);
}
output = diff(this.unwrap(actual), this.unwrap(expected));
if (output) {
output = output.clone().errorName(actual).text('(').append(output).text(')');
output.inline = false;
}
return output;
}
});
var unexpectedErrorMethodBlacklist = ['output', '_isUnexpected', 'htmlMessage', '_hasSerializedErrorMessage', 'expect', 'assertion', 'originalError'].reduce(function (result, prop) {
result[prop] = true;
return result;
}, {});
expect.addType({
base: 'Error',
name: 'UnexpectedError',
identify: function (value) {
return value && typeof value === 'object' &&
value._isUnexpected && this.baseType.identify(value);
},
getKeys: function (value) {
return this.baseType.getKeys(value).filter(function (key) {
return !unexpectedErrorMethodBlacklist[key];
});
},
inspect: function (value, depth, output) {
output.jsFunctionName(this.name).text('(');
var errorMessage = value.getErrorMessage(output);
if (errorMessage.isMultiline()) {
output.nl().indentLines().i().block(errorMessage).nl();
} else {
output.append(errorMessage);
}
return output.text(')');
}
});
expect.addType({
name: 'date',
identify: function (obj) {
return Object.prototype.toString.call(obj) === '[object Date]';
},
equal: function (a, b) {
return a.getTime() === b.getTime();
},
inspect: function (date, depth, output, inspect) {
// TODO: Inspect "new" as an operator and Date as a built-in once we have the styles defined:
var dateStr = date.toUTCString().replace(/UTC/, 'GMT');
var milliseconds = date.getUTCMilliseconds();
if (milliseconds > 0) {
var millisecondsStr = String(milliseconds);
while (millisecondsStr.length < 3) {
millisecondsStr = '0' + millisecondsStr;
}
dateStr = dateStr.replace(' GMT', '.' + millisecondsStr + ' GMT');
}
return output.jsKeyword('new').sp().text('Date(').append(inspect(dateStr).text(')'));
}
});
expect.addType({
base: 'any',
name: 'function',
identify: function (f) {
return typeof f === 'function';
},
getKeys: Object.keys,
equal: function (a, b) {
return a === b;
},
inspect: function (f, depth, output, inspect) {
var source = f.toString().replace(/\r\n?|\n\r?/g, '\n');
var name = utils.getFunctionName(f) || '';
var preamble;
var body;
var bodyIndent;
var matchSource = source.match(/^\s*((?:async )?\s*(?:\S+\s*=>|\([^\)]*\)\s*=>|function \w*?\s*\([^\)]*\)))([\s\S]*)$/);
if (matchSource) {
preamble = matchSource[1];
body = matchSource[2];
var matchBodyAndIndent = body.match(/^(\s*\{)([\s\S]*?)([ ]*)\}\s*$/);
var openingBrace;
var closingBrace = '}';
if (matchBodyAndIndent) {
openingBrace = matchBodyAndIndent[1];
body = matchBodyAndIndent[2];
bodyIndent = matchBodyAndIndent[3] || '';
if (bodyIndent.length === 1) {
closingBrace = ' }';
}
}
// Remove leading indentation unless the function is a one-liner or it uses multiline string literals
if (/\n/.test(body) && !/\\\n/.test(body)) {
body = body.replace(new RegExp('^ {' + bodyIndent.length + '}', 'mg'), '');
var indent = detectIndent(body);
body = body.replace(new RegExp('^(?:' + indent.indent + ')+', 'mg'), function ($0) {
return utils.leftPad('', ($0.length / indent.amount) * output.indentationWidth, ' ');
});
}
if (!name || name === 'anonymous') {
name = '';
}
if (/^\s*\[native code\]\s*$/.test(body)) {
body = ' /* native code */ ';
closingBrace = '}';
} else if (/^\s*$/.test(body)) {
body = '';
} else if (/^\s*[^\r\n]{1,30}\s*$/.test(body) && body.indexOf('//') === -1) {
body = ' ' + body.trim() + ' ';
closingBrace = '}';
} else {
body = body.replace(/^((?:.*\n){3}( *).*\n)[\s\S]*?\n[\s\S]*?\n((?:.*\n){3})$/, '$1$2// ... lines removed ...\n$3');
}
if (matchBodyAndIndent) {
body = openingBrace + body + closingBrace;
} else {
// Strip trailing space from arrow function body
body = body.replace(/[ ]*$/, '');
}
} else {
preamble = 'function ' + name + '( /*...*/ ) ';
body = '{ /*...*/ }';
}
return output.code(preamble + body, 'javascript');
}
});
expect.addType({
base: 'function',
name: 'expect.it',
identify: function (f) {
return typeof f === 'function' && f._expectIt;
},
inspect: function (f, depth, output, inspect) {
output.text('expect.it(');
var orBranch = false;
f._expectations.forEach(function (expectation, index) {
if (expectation === f._OR) {
orBranch = true;
return;
}
if (orBranch) {
output.text(')\n .or(');
} else if (0 < index) {
output.text(')\n .and(');
}
var args = Array.prototype.slice.call(expectation);
args.forEach(function (arg, i) {
if (0 < i) {
output.text(', ');
}
output.append(inspect(arg));
});
orBranch = false;
});
return output.amend(')');
}
});
expect.addType({
name: 'Promise',
base: 'object',
identify: function (obj) {
return obj && this.baseType.identify(obj) && typeof obj.then === 'function';
},
inspect: function (promise, depth, output, inspect) {
output.jsFunctionName('Promise');
if (promise.isPending && promise.isPending()) {
output.sp().yellow('(pending)');
} else if (promise.isFulfilled && promise.isFulfilled()) {
output.sp().green('(fulfilled)');
if (promise.value) {
var value = promise.value();
if (typeof value !== 'undefined') {
output.sp().text('=>').sp().append(inspect(value));
}
}
} else if (promise.isRejected && promise.isRejected()) {
output.sp().red('(rejected)');
var reason = promise.reason();
if (typeof reason !== 'undefined') {
output.sp().text('=>').sp().append(inspect(promise.reason()));
}
}
return output;
}
});
expect.addType({
name: 'regexp',
base: 'object',
identify: isRegExp,
equal: function (a, b) {
return a === b || (
a.source === b.source &&
a.global === b.global &&
a.ignoreCase === b.ignoreCase &&
a.multiline === b.multiline
);
},
inspect: function (regExp, depth, output) {
return output.jsRegexp(regExp);
},
diff: function (actual, expected, output, diff, inspect) {
output.inline = false;
return output.stringDiff(String(actual), String(expected), {type: 'Chars', markUpSpecialCharacters: true});
}
});
expect.addType({
name: 'binaryArray',
base: 'array-like',
digitWidth: 2,
hexDumpWidth: 16,
identify: false,
prefix: function (output) {
return output.code(this.name + '([', 'javascript');
},
suffix: function (output) {
return output.code('])', 'javascript');
},
equal: function (a, b) {
if (a === b) {
return true;
}
if (a.length !== b.length) { return false; }
for (var i = 0; i < a.length; i += 1) {
if (a[i] !== b[i]) { return false; }
}
return true;
},
hexDump: function (obj, maxLength) {
var hexDump = '';
if (typeof maxLength !== 'number' || maxLength === 0) {
maxLength = obj.length;
}
for (var i = 0 ; i < maxLength ; i += this.hexDumpWidth) {
if (hexDump.length > 0) {
hexDump += '\n';
}
var hexChars = '',
asciiChars = ' │';
for (var j = 0 ; j < this.hexDumpWidth ; j += 1) {
if (i + j < maxLength) {
var octet = obj[i + j];
hexChars += leftPad(octet.toString(16).toUpperCase(), this.digitWidth, '0') + ' ';
asciiChars += String.fromCharCode(octet).replace(/\n/g, '␊').replace(/\r/g, '␍');
} else if (this.digitWidth === 2) {
hexChars += ' ';
}
}
if (this.digitWidth === 2) {
hexDump += hexChars + asciiChars + '│';
} else {
hexDump += hexChars.replace(/\s+$/, '');
}
}
return hexDump;
},
inspect: function (obj, depth, output) {
this.prefix(output, obj);
var codeStr = '';
for (var i = 0 ; i < Math.min(this.hexDumpWidth, obj.length) ; i += 1) {
if (i > 0) {
codeStr += ', ';
}
var octet = obj[i];
codeStr += '0x' + leftPad(octet.toString(16).toUpperCase(), this.digitWidth, '0');
}
if (obj.length > this.hexDumpWidth) {
codeStr += ' /* ' + (obj.length - this.hexDumpWidth) + ' more */ ';
}
output.code(codeStr, 'javascript');
this.suffix(output, obj);
return output;
},
diffLimit: 512,
diff: function (actual, expected, output, diff, inspect) {
output.inline = false;
if (Math.max(actual.length, expected.length) > this.diffLimit) {
output.jsComment('Diff suppressed due to size > ' + this.diffLimit);
} else {
output.stringDiff(this.hexDump(actual), this.hexDump(expected), {type: 'Chars', markUpSpecialCharacters: false})
.replaceText(/[\x00-\x1f\x7f-\xff␊␍]/g, '.').replaceText(/[│ ]/g, function (styles, content) {
this.text(content);
});
}
return output;
}
});
[8, 16, 32].forEach(function (numBits) {
['Int', 'Uint'].forEach(function (intOrUint) {
var constructorName = intOrUint + numBits + 'Array',
Constructor = this[constructorName];
if (typeof Constructor !== 'undefined') {
expect.addType({
name: constructorName,
base: 'binaryArray',
hexDumpWidth: 128 / numBits,
digitWidth: numBits / 4,
identify: function (obj) {
return obj instanceof Constructor;
}
});
}
}, this);
}, this);
if (typeof Buffer !== 'undefined') {
expect.addType({
name: 'Buffer',
base: 'binaryArray',
identify: Buffer.isBuffer
});
}
expect.addType({
name: 'string',
identify: function (value) {
return typeof value === 'string';
},
inspect: function (value, depth, output) {
return output.singleQuotedString(value);
},
diffLimit: 4096,
diff: function (actual, expected, output, diff, inspect) {
if (Math.max(actual.length, expected.length) > this.diffLimit) {
output.jsComment('Diff suppressed due to size > ' + this.diffLimit);
return output;
}
output.stringDiff(actual, expected, {type: 'WordsWithSpace', markUpSpecialCharacters: true});
output.inline = false;
return output;
}
});
expect.addType({
name: 'number',
identify: function (value) {
return typeof value === 'number' && !isNaN(value);
},
inspect: function (value, depth, output) {
if (value === 0 && 1 / value === -Infinity) {
value = '-0';
} else {
value = String(value);
}
return output.jsNumber(String(value));
}
});
expect.addType({
name: 'NaN',
identify: function (value) {
return typeof value === 'number' && isNaN(value);
},
inspect: function (value, depth, output) {
return output.jsPrimitive(value);
}
});
expect.addType({
name: 'boolean',
identify: function (value) {
return typeof value === 'boolean';
},
inspect: function (value, depth, output) {
return output.jsPrimitive(value);
}
});
expect.addType({
name: 'undefined',
identify: function (value) {
return typeof value === 'undefined';
},
inspect: function (value, depth, output) {
return output.jsPrimitive(value);
}
});
expect.addType({
name: 'null',
identify: function (value) {
return value === null;
},
inspect: function (value, depth, output) {
return output.jsPrimitive(value);
}
});
expect.addType({
name: 'assertion',
identify: function (value) {
return value instanceof AssertionString;
}
});
};
}).call(this,require(28).Buffer)
},{"1":1,"19":19,"24":24,"28":28,"33":33,"40":40,"8":8}],18:[function(require,module,exports){
(function (process){
/*global window*/
var Promise = require(56);
var useFullStackTrace = false;
if (typeof window !== 'undefined' && typeof window.location !== 'undefined') {
useFullStackTrace = !!window.location.search.match(/[?&]full-trace=true(?:$|&)/);
}
if (typeof process !== 'undefined' && process.env && process.env.UNEXPECTED_FULL_TRACE) {
Promise.longStackTraces();
useFullStackTrace = true;
}
module.exports = useFullStackTrace;
}).call(this,require(53))
},{"53":53,"56":56}],19:[function(require,module,exports){
/* eslint-disable no-proto */
var canSetPrototype = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array);
var greedyIntervalPacker = require(36);
var setPrototypeOf = Object.setPrototypeOf || function setPrototypeOf(obj, proto) {
obj.__proto__ = proto;
return obj;
};
/* eslint-enable no-proto */
var utils = module.exports = {
objectIs: Object.is || function (a, b) {
// Polyfill from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
if (a === 0 && b === 0) {
return 1 / a === 1 / b;
}
if (a !== a) {
return b !== b;
}
return a === b;
},
isArray: function (ar) {
return Object.prototype.toString.call(ar) === '[object Array]';
},
isRegExp: function (re) {
return (Object.prototype.toString.call(re) === '[object RegExp]');
},
isError: function (err) {
return typeof err === 'object' && (Object.prototype.toString.call(err) === '[object Error]' || err instanceof Error);
},
extend: function (target) {
for (var i = 1; i < arguments.length; i += 1) {
var source = arguments[i];
if (source) {
Object.keys(source).forEach(function (key) {
target[key] = source[key];
});
}
}
return target;
},
findFirst: function (arr, predicate) {
for (var i = 0 ; i < arr.length ; i += 1) {
if (predicate(arr[i])) {
return arr[i];
}
}
return null;
},
leftPad: function (str, width, ch) {
ch = ch || ' ';
while (str.length < width) {
str = ch + str;
}
return str;
},
escapeRegExpMetaChars: function (str) {
return str.replace(/[[\]{}()*+?.\\^$|]/g, '\\$&');
},
escapeChar: function (ch) {
if (ch === '\t') {
return '\\t';
} else if (ch === '\r') {
return '\\r';
} else {
var charCode = ch.charCodeAt(0);
var hexChars = charCode.toString(16).toUpperCase();
if (charCode < 256) {
return '\\x' + utils.leftPad(hexChars, 2, '0');
} else {
return '\\u' + utils.leftPad(hexChars, 4, '0');
}
}
},
getFunctionName: function (f) {
if (typeof f.name === 'string') {
return f.name;
}
var matchFunctionName = Function.prototype.toString.call(f).match(/function ([^\(]+)/);
if (matchFunctionName) {
return matchFunctionName[1];
}
if (f === Object) {
return 'Object';
}
if (f === Function) {
return 'Function';
}
return '';
},
wrapConstructorNameAroundOutput: function (output, obj) {
var constructor = obj.constructor;
var constructorName = constructor && constructor !== Object && utils.getFunctionName(constructor);
if (constructorName && constructorName !== 'Object') {
return output.clone().text(constructorName + '(').append(output).text(')');
} else {
return output;
}
},
setPrototypeOfOrExtend: canSetPrototype ? setPrototypeOf : function extend(target, source) {
for (var prop in source) {
if (source.hasOwnProperty(prop)) {
target[prop] = source[prop];
}
}
return target;
},
uniqueStringsAndSymbols: function () { // [filterFn], item1, item2...
var filterFn;
if (typeof arguments[0] === 'function') {
filterFn = arguments[0];
}
var index = {};
var uniqueStringsAndSymbols = [];
function visit(item) {
if (Array.isArray(item)) {
item.forEach(visit);
} else if (!Object.prototype.hasOwnProperty.call(index, item) && (!filterFn || filterFn(item))) {
index[item] = true;
uniqueStringsAndSymbols.push(item);
}
}
for (var i = filterFn ? 1 : 0 ; i < arguments.length ; i += 1) {
visit(arguments[i]);
}
return uniqueStringsAndSymbols;
},
uniqueNonNumericalStringsAndSymbols: function () { // ...
return utils.uniqueStringsAndSymbols(function (stringOrSymbol) {
return typeof stringOrSymbol === 'symbol' || !utils.numericalRegExp.test(stringOrSymbol);
}, Array.prototype.slice.call(arguments));
},
forwardFlags: function (testDescriptionString, flags) {
return testDescriptionString.replace(/\[(!?)([^\]]+)\] ?/g, function (match, negate, flag) {
return Boolean(flags[flag]) !== Boolean(negate) ? flag + ' ' : '';
}).trim();
},
numericalRegExp: /^(?:0|[1-9][0-9]*)$/,
packArrows: function (changes) {
var moveSourceAndTargetByActualIndex = {};
changes.forEach(function (diffItem, index) {
if (diffItem.type === 'moveSource') {
diffItem.changeIndex = index;
(moveSourceAndTargetByActualIndex[diffItem.actualIndex] = moveSourceAndTargetByActualIndex[diffItem.actualIndex] || {}).source = diffItem;
} else if (diffItem.type === 'moveTarget') {
diffItem.changeIndex = index;
(moveSourceAndTargetByActualIndex[diffItem.actualIndex] = moveSourceAndTargetByActualIndex[diffItem.actualIndex] || {}).target = diffItem;
}
});
var moveIndices = Object.keys(moveSourceAndTargetByActualIndex);
if (moveIndices.length > 0) {
var arrowSpecs = [];
moveIndices.sort(function (a, b) {
// Order by distance between change indices descending
return Math.abs(moveSourceAndTargetByActualIndex[b].source.changeIndex - moveSourceAndTargetByActualIndex[b].target.changeIndex) - Math.abs(moveSourceAndTargetByActualIndex[a].source.changeIndex - moveSourceAndTargetByActualIndex[a].target.changeIndex);
}).forEach(function (actualIndex, i, keys) {
var moveSourceAndMoveTarget = moveSourceAndTargetByActualIndex[actualIndex];
var firstChangeIndex = Math.min(moveSourceAndMoveTarget.source.changeIndex, moveSourceAndMoveTarget.target.changeIndex);
var lastChangeIndex = Math.max(moveSourceAndMoveTarget.source.changeIndex, moveSourceAndMoveTarget.target.changeIndex);
arrowSpecs.push({
start: firstChangeIndex,
end: lastChangeIndex,
direction: moveSourceAndMoveTarget.source.changeIndex < moveSourceAndMoveTarget.target.changeIndex ? 'down' : 'up'
});
});
var packing = greedyIntervalPacker(arrowSpecs);
while (packing.length > 3) {
// The arrow packing takes up too many lanes. Turn the moveSource/moveTarget items into inserts and removes
packing.shift().forEach(function (entry) {
changes[entry.direction === 'up' ? entry.start : entry.end].type = 'insert';
changes[entry.direction === 'up' ? entry.end : entry.start].type = 'remove';
});
}
return packing;
}
}
};
},{"36":36}],20:[function(require,module,exports){
var Promise = require(56);
var workQueue = {
queue: [],
drain: function () {
this.queue.forEach(function (fn) {
fn();
});
this.queue = [];
}
};
var scheduler = Promise.setScheduler(function (fn) {
workQueue.queue.push(fn);
scheduler(function () {
workQueue.drain();
});
});
Promise.prototype._notifyUnhandledRejection = function () {
var that = this;
scheduler(function () {
if (that._isRejectionUnhandled()) {
if (workQueue.onUnhandledRejection) { // for testing
workQueue.onUnhandledRejection(that.reason());
} else {
throw that.reason();
}
}
});
};
module.exports = workQueue;
},{"56":56}],21:[function(require,module,exports){
module.exports = require(2).create()
.use(require(15))
.use(require(17))
.use(require(5));
// Add an inspect method to all the promises we return that will make the REPL, console.log, and util.inspect render it nicely in node.js:
require(56).prototype.inspect = function () {
return module.exports.createOutput(require(44).defaultFormat).appendInspected(this).toString();
};
},{"15":15,"17":17,"2":2,"44":44,"5":5,"56":56}],22:[function(require,module,exports){
'use strict';
var styles = module.exports = {
modifiers: {
reset: [0, 0],
bold: [1, 22], // 21 isn't widely supported and 22 does the same thing
dim: [2, 22],
italic: [3, 23],
underline: [4, 24],
inverse: [7, 27],
hidden: [8, 28],
strikethrough: [9, 29]
},
colors: {
black: [30, 39],
red: [31, 39],
green: [32, 39],
yellow: [33, 39],
blue: [34, 39],
magenta: [35, 39],
cyan: [36, 39],
white: [37, 39],
gray: [90, 39]
},
bgColors: {
bgBlack: [40, 49],
bgRed: [41, 49],
bgGreen: [42, 49],
bgYellow: [43, 49],
bgBlue: [44, 49],
bgMagenta: [45, 49],
bgCyan: [46, 49],
bgWhite: [47, 49]
}
};
// fix humans
styles.colors.grey = styles.colors.gray;
Object.keys(styles).forEach(function (groupName) {
var group = styles[groupName];
Object.keys(group).forEach(function (styleName) {
var style = group[styleName];
styles[styleName] = group[styleName] = {
open: '\u001b[' + style[0] + 'm',
close: '\u001b[' + style[1] + 'm'
};
});
Object.defineProperty(styles, groupName, {
value: group,
enumerable: false
});
});
},{}],23:[function(require,module,exports){
/*global setTimeout */
var arrayDiff = require(25);
var MAX_STACK_DEPTH = 1000;
function extend(target) {
for (var i = 1; i < arguments.length; i += 1) {
var source = arguments[i];
Object.keys(source).forEach(function (key) {
target[key] = source[key];
});
}
return target;
}
module.exports = function arrayChanges(actual, expected, equal, similar, includeNonNumericalProperties, arrayChangesCallback) {
if (typeof includeNonNumericalProperties === 'function') {
arrayChangesCallback = includeNonNumericalProperties;
includeNonNumericalProperties = false;
}
var mutatedArray = new Array(actual.length);
for (var k = 0; k < actual.length; k += 1) {
mutatedArray[k] = {
type: 'similar',
actualIndex: k,
value: actual[k]
};
}
similar = similar || function (a, b, aIndex, bIndex, callback) {
return callback(false);
};
arrayDiff([].concat(actual), [].concat(expected), function (a, b, aIndex, bIndex, callback) {
equal(a, b, aIndex, bIndex, function (isEqual) {
if (isEqual) {
return callback(true);
}
similar(a, b, aIndex, bIndex, function (isSimilar) {
return callback(isSimilar);
});
});
}, function (itemsDiff) {
function offsetIndex(index) {
var offsetIndex = 0;
var i;
for (i = 0; i < mutatedArray.length && offsetIndex < index; i += 1) {
if (mutatedArray[i].type !== 'remove' && mutatedArray[i].type !== 'moveSource') {
offsetIndex++;
}
}
return i;
}
var removes = itemsDiff.filter(function (diffItem) {
return diffItem.type === 'remove';
});
var removedItems = 0;
removes.forEach(function (diffItem) {
var removeIndex = removedItems + diffItem.index;
mutatedArray.slice(removeIndex, diffItem.howMany + removeIndex).forEach(function (v) {
v.type = 'remove';
});
removedItems += diffItem.howMany;
});
var moves = itemsDiff.filter(function (diffItem) {
return diffItem.type === 'move';
});
moves.forEach(function (diffItem) {
var moveFromIndex = offsetIndex(diffItem.from + 1) - 1;
var removed = mutatedArray.slice(moveFromIndex, diffItem.howMany + moveFromIndex);
var added = removed.map(function (v) {
return extend({}, v, { last: false, type: 'moveTarget' });
});
removed.forEach(function (v) {
v.type = 'moveSource';
});
var insertIndex = offsetIndex(diffItem.to);
Array.prototype.splice.apply(mutatedArray, [insertIndex, 0].concat(added));
});
var inserts = itemsDiff.filter(function (diffItem) {
return diffItem.type === 'insert';
});
inserts.forEach(function (diffItem) {
var added = new Array(diffItem.values.length);
for (var i = 0 ; i < diffItem.values.length ; i += 1) {
added[i] = {
type: 'insert',
value: diffItem.values[i]
};
}
Array.prototype.splice.apply(mutatedArray, [offsetIndex(diffItem.index), 0].concat(added));
});
var offset = 0;
mutatedArray.forEach(function (diffItem, index) {
var type = diffItem.type;
if (type === 'remove' || type === 'moveSource') {
offset -= 1;
} else if (type === 'similar') {
diffItem.expected = expected[offset + index];
diffItem.expectedIndex = offset + index;
}
});
var conflicts = mutatedArray.reduce(function (conflicts, item) {
return item.type === 'similar' || item.type === 'moveSource' || item.type === 'moveTarget' ? conflicts : conflicts + 1;
}, 0);
var end = Math.max(actual.length, expected.length);
var countConflicts = function (i, c, stackCallsRemaining, callback) {
if (i >= end || c > conflicts) {
// Do a setTimeout to let the stack unwind
return setTimeout(function () {
callback(c);
}, 0);
}
similar(actual[i], expected[i], i, i, function (areSimilar) {
if (!areSimilar) {
c += 1;
if (stackCallsRemaining === 0) {
return setTimeout(function () {
countConflicts(i + 1, c, MAX_STACK_DEPTH, callback);
});
}
return countConflicts(i + 1, c, stackCallsRemaining - 1, callback);
}
equal(actual[i], expected[i], i, i, function (areEqual) {
if (!areEqual) {
c += 1;
}
if (stackCallsRemaining === 0) {
return setTimeout(function () {
countConflicts(i + 1, c, MAX_STACK_DEPTH, callback);
});
}
return countConflicts(i + 1, c, stackCallsRemaining - 1, callback);
});
});
};
countConflicts(0, 0, MAX_STACK_DEPTH, function (c) {
if (c <= conflicts) {
mutatedArray = [];
var j;
for (j = 0; j < Math.min(actual.length, expected.length); j += 1) {
mutatedArray.push({
type: 'similar',
actualIndex: j,
expectedIndex: j,
value: actual[j],
expected: expected[j]
});
}
if (actual.length < expected.length) {
for (; j < Math.max(actual.length, expected.length); j += 1) {
mutatedArray.push({
type: 'insert',
value: expected[j]
});
}
} else {
for (; j < Math.max(actual.length, expected.length); j += 1) {
mutatedArray.push({
type: 'remove',
value: actual[j]
});
}
}
}
var setEqual = function (i, stackCallsRemaining, callback) {
if (i >= mutatedArray.length) {
return callback();
}
var diffItem = mutatedArray[i];
if (diffItem.type === 'similar') {
return equal(diffItem.value, diffItem.expected, diffItem.actualIndex, diffItem.expectedIndex, function (areEqual) {
if (areEqual) {
mutatedArray[i].type = 'equal';
}
if (stackCallsRemaining === 0) {
return setTimeout(function () {
setEqual(i + 1, MAX_STACK_DEPTH, callback);
});
}
setEqual(i + 1, stackCallsRemaining - 1, callback);
});
}
if (stackCallsRemaining === 0) {
return setTimeout(function () {
setEqual(i + 1, MAX_STACK_DEPTH, callback);
});
}
return setEqual(i + 1, stackCallsRemaining - 1, callback);
};
if (includeNonNumericalProperties) {
var nonNumericalKeys;
if (Array.isArray(includeNonNumericalProperties)) {
nonNumericalKeys = includeNonNumericalProperties;
} else {
var isSeenByNonNumericalKey = {};
nonNumericalKeys = [];
[actual, expected].forEach(function (obj) {
Object.keys(obj).forEach(function (key) {
if (!/^(?:0|[1-9][0-9]*)$/.test(key) && !isSeenByNonNumericalKey[key]) {
isSeenByNonNumericalKey[key] = true;
nonNumericalKeys.push(key);
}
});
if (Object.getOwnPropertySymbols) {
Object.getOwnPropertySymbols(obj).forEach(function (symbol) {
if (!isSeenByNonNumericalKey[symbol]) {
isSeenByNonNumericalKey[symbol] = true;
nonNumericalKeys.push(symbol);
}
});
}
});
}
nonNumericalKeys.forEach(function (key) {
if (key in actual) {
if (key in expected) {
mutatedArray.push({
type: 'similar',
expectedIndex: key,
actualIndex: key,
value: actual[key],
expected: expected[key]
});
} else {
mutatedArray.push({
type: 'remove',
actualIndex: key,
value: actual[key]
});
}
} else {
mutatedArray.push({
type: 'insert',
expectedIndex: key,
value: expected[key]
});
}
});
}
setEqual(0, MAX_STACK_DEPTH, function () {
if (mutatedArray.length > 0) {
mutatedArray[mutatedArray.length - 1].last = true;
}
arrayChangesCallback(mutatedArray);
});
});
});
};
},{"25":25}],24:[function(require,module,exports){
var arrayDiff = require(26);
function extend(target) {
for (var i = 1; i < arguments.length; i += 1) {
var source = arguments[i];
Object.keys(source).forEach(function (key) {
target[key] = source[key];
});
}
return target;
}
module.exports = function arrayChanges(actual, expected, equal, similar, includeNonNumericalProperties) {
var mutatedArray = new Array(actual.length);
for (var k = 0; k < actual.length; k += 1) {
mutatedArray[k] = {
type: 'similar',
value: actual[k],
actualIndex: k
};
}
equal = equal || function (a, b) {
return a === b;
};
similar = similar || function (a, b) {
return false;
};
var itemsDiff = arrayDiff(Array.prototype.slice.call(actual), Array.prototype.slice.call(expected), function (a, b, aIndex, bIndex) {
return equal(a, b, aIndex, bIndex) || similar(a, b, aIndex, bIndex);
});
function offsetIndex(index) {
var offsetIndex = 0;
var i;
for (i = 0; i < mutatedArray.length && offsetIndex < index; i += 1) {
if (mutatedArray[i].type !== 'remove' && mutatedArray[i].type !== 'moveSource') {
offsetIndex++;
}
}
return i;
}
var removes = itemsDiff.filter(function (diffItem) {
return diffItem.type === 'remove';
});
var removedItems = 0;
removes.forEach(function (diffItem) {
var removeIndex = removedItems + diffItem.index;
mutatedArray.slice(removeIndex, diffItem.howMany + removeIndex).forEach(function (v) {
v.type = 'remove';
});
removedItems += diffItem.howMany;
});
var moves = itemsDiff.filter(function (diffItem) {
return diffItem.type === 'move';
});
moves.forEach(function (diffItem) {
var moveFromIndex = offsetIndex(diffItem.from + 1) - 1;
var removed = mutatedArray.slice(moveFromIndex, diffItem.howMany + moveFromIndex);
var added = removed.map(function (v) {
return extend({}, v, { last: false, type: 'moveTarget' });
});
removed.forEach(function (v) {
v.type = 'moveSource';
});
var insertIndex = offsetIndex(diffItem.to);
Array.prototype.splice.apply(mutatedArray, [insertIndex, 0].concat(added));
});
var inserts = itemsDiff.filter(function (diffItem) {
return diffItem.type === 'insert';
});
inserts.forEach(function (diffItem) {
var added = new Array(diffItem.values.length);
for (var i = 0 ; i < diffItem.values.length ; i += 1) {
added[i] = {
type: 'insert',
value: diffItem.values[i],
expectedIndex: diffItem.index
};
}
var insertIndex = offsetIndex(diffItem.index);
Array.prototype.splice.apply(mutatedArray, [insertIndex, 0].concat(added));
});
var offset = 0;
mutatedArray.forEach(function (diffItem, index) {
var type = diffItem.type;
if (type === 'remove' || type === 'moveSource') {
offset -= 1;
} else if (type === 'similar') {
diffItem.expected = expected[offset + index];
diffItem.expectedIndex = offset + index;
}
});
var conflicts = mutatedArray.reduce(function (conflicts, item) {
return item.type === 'similar' || item.type === 'moveSource' || item.type === 'moveTarget' ? conflicts : conflicts + 1;
}, 0);
var c, i;
for (i = 0, c = 0; i < Math.max(actual.length, expected.length) && c <= conflicts; i += 1) {
if (
i >= actual.length || i >= expected.length || (!equal(actual[i], expected[i], i, i) && !similar(actual[i], expected[i], i, i))
) {
c += 1;
}
}
if (c <= conflicts) {
mutatedArray = [];
var j;
for (j = 0; j < Math.min(actual.length, expected.length); j += 1) {
mutatedArray.push({
type: 'similar',
value: actual[j],
expected: expected[j],
actualIndex: j,
expectedIndex: j
});
}
if (actual.length < expected.length) {
for (; j < Math.max(actual.length, expected.length); j += 1) {
mutatedArray.push({
type: 'insert',
value: expected[j],
expectedIndex: j
});
}
} else {
for (; j < Math.max(actual.length, expected.length); j += 1) {
mutatedArray.push({
type: 'remove',
value: actual[j],
actualIndex: j
});
}
}
}
mutatedArray.forEach(function (diffItem) {
if (diffItem.type === 'similar' && equal(diffItem.value, diffItem.expected, diffItem.actualIndex, diffItem.expectedIndex)) {
diffItem.type = 'equal';
}
});
if (includeNonNumericalProperties) {
var nonNumericalKeys;
if (Array.isArray(includeNonNumericalProperties)) {
nonNumericalKeys = includeNonNumericalProperties;
} else {
var isSeenByNonNumericalKey = {};
nonNumericalKeys = [];
[actual, expected].forEach(function (obj) {
Object.keys(obj).forEach(function (key) {
if (!/^(?:0|[1-9][0-9]*)$/.test(key) && !isSeenByNonNumericalKey[key]) {
isSeenByNonNumericalKey[key] = true;
nonNumericalKeys.push(key);
}
});
if (Object.getOwnPropertySymbols) {
Object.getOwnPropertySymbols(obj).forEach(function (symbol) {
if (!isSeenByNonNumericalKey[symbol]) {
isSeenByNonNumericalKey[symbol] = true;
nonNumericalKeys.push(symbol);
}
});
}
});
}
nonNumericalKeys.forEach(function (key) {
if (key in actual) {
if (key in expected) {
mutatedArray.push({
type: equal(actual[key], expected[key], key, key) ? 'equal' : 'similar',
expectedIndex: key,
actualIndex: key,
value: actual[key],
expected: expected[key]
});
} else {
mutatedArray.push({
type: 'remove',
actualIndex: key,
value: actual[key]
});
}
} else {
mutatedArray.push({
type: 'insert',
expectedIndex: key,
value: expected[key]
});
}
});
}
if (mutatedArray.length > 0) {
mutatedArray[mutatedArray.length - 1].last = true;
}
return mutatedArray;
};
},{"26":26}],25:[function(require,module,exports){
module.exports = arrayDiff;
var MAX_STACK_DEPTH = 1000;
// Based on some rough benchmarking, this algorithm is about O(2n) worst case,
// and it can compute diffs on random arrays of length 1024 in about 34ms,
// though just a few changes on an array of length 1024 takes about 0.5ms
arrayDiff.InsertDiff = InsertDiff;
arrayDiff.RemoveDiff = RemoveDiff;
arrayDiff.MoveDiff = MoveDiff;
function InsertDiff(index, values) {
this.index = index;
this.values = values;
}
InsertDiff.prototype.type = 'insert';
InsertDiff.prototype.toJSON = function() {
return {
type: this.type
, index: this.index
, values: this.values
};
};
function RemoveDiff(index, howMany) {
this.index = index;
this.howMany = howMany;
}
RemoveDiff.prototype.type = 'remove';
RemoveDiff.prototype.toJSON = function() {
return {
type: this.type
, index: this.index
, howMany: this.howMany
};
};
function MoveDiff(from, to, howMany) {
this.from = from;
this.to = to;
this.howMany = howMany;
}
MoveDiff.prototype.type = 'move';
MoveDiff.prototype.toJSON = function() {
return {
type: this.type
, from: this.from
, to: this.to
, howMany: this.howMany
};
};
function strictEqual(a, b, indexA, indexB, callback) {
return callback(a === b);
}
function arrayDiff(before, after, equalFn, callback) {
if (!equalFn) equalFn = strictEqual;
// Find all items in both the before and after array, and represent them
// as moves. Many of these "moves" may end up being discarded in the last
// pass if they are from an index to the same index, but we don't know this
// up front, since we haven't yet offset the indices.
//
// Also keep a map of all the indices accounted for in the before and after
// arrays. These maps are used next to create insert and remove diffs.
var beforeLength = before.length;
var afterLength = after.length;
var moves = [];
var beforeMarked = {};
var afterMarked = {};
function findMatching(beforeIndex, afterIndex, howMany, callback) {
beforeMarked[beforeIndex++] = afterMarked[afterIndex++] = true;
howMany++;
if (beforeIndex < beforeLength &&
afterIndex < afterLength &&
!afterMarked[afterIndex]) {
equalFn(before[beforeIndex], after[afterIndex], beforeIndex, afterIndex, function (areEqual) {
if (areEqual) {
setTimeout(function () {
findMatching(beforeIndex, afterIndex, howMany, callback);
}, 0);
} else {
callback(beforeIndex, afterIndex, howMany);
}
});
} else {
callback(beforeIndex, afterIndex, howMany);
}
}
function compare(beforeIndex, afterIndex, stackDepthRemaining, callback) {
if (afterIndex >= afterLength) {
beforeIndex++;
afterIndex = 0;
}
if (beforeIndex >= beforeLength) {
callback();
return;
}
if (!afterMarked[afterIndex]) {
equalFn(before[beforeIndex], after[afterIndex], beforeIndex, afterIndex, function (areEqual) {
if (areEqual) {
var from = beforeIndex;
var to = afterIndex;
findMatching(beforeIndex, afterIndex, 0, function (newBeforeIndex, newAfterIndex, howMany) {
moves.push(new MoveDiff(from, to, howMany));
if (stackDepthRemaining) {
compare(newBeforeIndex, 0, stackDepthRemaining - 1, callback);
} else {
setTimeout(function () {
compare(newBeforeIndex, 0, MAX_STACK_DEPTH, callback);
}, 0);
}
});
} else {
if (stackDepthRemaining) {
compare(beforeIndex, afterIndex + 1, stackDepthRemaining - 1, callback);
} else {
setTimeout(function () {
compare(beforeIndex, afterIndex + 1, MAX_STACK_DEPTH, callback);
}, 0);
}
}
});
} else {
if (stackDepthRemaining) {
compare(beforeIndex, afterIndex + 1, stackDepthRemaining - 1, callback);
} else {
setTimeout(function () {
compare(beforeIndex, afterIndex + 1, MAX_STACK_DEPTH, callback);
}, 0);
}
}
}
compare(0, 0, MAX_STACK_DEPTH, function () {
// Create a remove for all of the items in the before array that were
// not marked as being matched in the after array as well
var removes = [];
for (var beforeIndex = 0; beforeIndex < beforeLength;) {
if (beforeMarked[beforeIndex]) {
beforeIndex++;
continue;
}
var index = beforeIndex;
var howMany = 0;
while (beforeIndex < beforeLength && !beforeMarked[beforeIndex++]) {
howMany++;
}
removes.push(new RemoveDiff(index, howMany));
}
// Create an insert for all of the items in the after array that were
// not marked as being matched in the before array as well
var inserts = [];
for (var afterIndex = 0; afterIndex < afterLength;) {
if (afterMarked[afterIndex]) {
afterIndex++;
continue;
}
var index = afterIndex;
var howMany = 0;
while (afterIndex < afterLength && !afterMarked[afterIndex++]) {
howMany++;
}
var values = after.slice(index, index + howMany);
inserts.push(new InsertDiff(index, values));
}
var insertsLength = inserts.length;
var removesLength = removes.length;
var movesLength = moves.length;
var i, j;
// Offset subsequent removes and moves by removes
var count = 0;
for (i = 0; i < removesLength; i++) {
var remove = removes[i];
remove.index -= count;
count += remove.howMany;
for (j = 0; j < movesLength; j++) {
var move = moves[j];
if (move.from >= remove.index) move.from -= remove.howMany;
}
}
// Offset moves by inserts
for (i = insertsLength; i--;) {
var insert = inserts[i];
var howMany = insert.values.length;
for (j = movesLength; j--;) {
var move = moves[j];
if (move.to >= insert.index) move.to -= howMany;
}
}
// Offset the to of moves by later moves
for (i = movesLength; i-- > 1;) {
var move = moves[i];
if (move.to === move.from) continue;
for (j = i; j--;) {
var earlier = moves[j];
if (earlier.to >= move.to) earlier.to -= move.howMany;
if (earlier.to >= move.from) earlier.to += move.howMany;
}
}
// Only output moves that end up having an effect after offsetting
var outputMoves = [];
// Offset the from of moves by earlier moves
for (i = 0; i < movesLength; i++) {
var move = moves[i];
if (move.to === move.from) continue;
outputMoves.push(move);
for (j = i + 1; j < movesLength; j++) {
var later = moves[j];
if (later.from >= move.from) later.from -= move.howMany;
if (later.from >= move.to) later.from += move.howMany;
}
}
callback(removes.concat(outputMoves, inserts));
});
}
},{}],26:[function(require,module,exports){
module.exports = arrayDiff;
// Based on some rough benchmarking, this algorithm is about O(2n) worst case,
// and it can compute diffs on random arrays of length 1024 in about 34ms,
// though just a few changes on an array of length 1024 takes about 0.5ms
arrayDiff.InsertDiff = InsertDiff;
arrayDiff.RemoveDiff = RemoveDiff;
arrayDiff.MoveDiff = MoveDiff;
function InsertDiff(index, values) {
this.index = index;
this.values = values;
}
InsertDiff.prototype.type = 'insert';
InsertDiff.prototype.toJSON = function() {
return {
type: this.type
, index: this.index
, values: this.values
};
};
function RemoveDiff(index, howMany) {
this.index = index;
this.howMany = howMany;
}
RemoveDiff.prototype.type = 'remove';
RemoveDiff.prototype.toJSON = function() {
return {
type: this.type
, index: this.index
, howMany: this.howMany
};
};
function MoveDiff(from, to, howMany) {
this.from = from;
this.to = to;
this.howMany = howMany;
}
MoveDiff.prototype.type = 'move';
MoveDiff.prototype.toJSON = function() {
return {
type: this.type
, from: this.from
, to: this.to
, howMany: this.howMany
};
};
function strictEqual(a, b) {
return a === b;
}
function arrayDiff(before, after, equalFn) {
if (!equalFn) equalFn = strictEqual;
// Find all items in both the before and after array, and represent them
// as moves. Many of these "moves" may end up being discarded in the last
// pass if they are from an index to the same index, but we don't know this
// up front, since we haven't yet offset the indices.
//
// Also keep a map of all the indices accounted for in the before and after
// arrays. These maps are used next to create insert and remove diffs.
var beforeLength = before.length;
var afterLength = after.length;
var moves = [];
var beforeMarked = {};
var afterMarked = {};
for (var beforeIndex = 0; beforeIndex < beforeLength; beforeIndex++) {
var beforeItem = before[beforeIndex];
for (var afterIndex = 0; afterIndex < afterLength; afterIndex++) {
if (afterMarked[afterIndex]) continue;
if (!equalFn(beforeItem, after[afterIndex], beforeIndex, afterIndex)) continue;
var from = beforeIndex;
var to = afterIndex;
var howMany = 0;
do {
beforeMarked[beforeIndex++] = afterMarked[afterIndex++] = true;
howMany++;
} while (
beforeIndex < beforeLength &&
afterIndex < afterLength &&
equalFn(before[beforeIndex], after[afterIndex], beforeIndex, afterIndex) &&
!afterMarked[afterIndex]
);
moves.push(new MoveDiff(from, to, howMany));
beforeIndex--;
break;
}
}
// Create a remove for all of the items in the before array that were
// not marked as being matched in the after array as well
var removes = [];
for (beforeIndex = 0; beforeIndex < beforeLength;) {
if (beforeMarked[beforeIndex]) {
beforeIndex++;
continue;
}
var index = beforeIndex;
var howMany = 0;
while (beforeIndex < beforeLength && !beforeMarked[beforeIndex++]) {
howMany++;
}
removes.push(new RemoveDiff(index, howMany));
}
// Create an insert for all of the items in the after array that were
// not marked as being matched in the before array as well
var inserts = [];
for (afterIndex = 0; afterIndex < afterLength;) {
if (afterMarked[afterIndex]) {
afterIndex++;
continue;
}
var index = afterIndex;
var howMany = 0;
while (afterIndex < afterLength && !afterMarked[afterIndex++]) {
howMany++;
}
var values = after.slice(index, index + howMany);
inserts.push(new InsertDiff(index, values));
}
var insertsLength = inserts.length;
var removesLength = removes.length;
var movesLength = moves.length;
var i, j;
// Offset subsequent removes and moves by removes
var count = 0;
for (i = 0; i < removesLength; i++) {
var remove = removes[i];
remove.index -= count;
count += remove.howMany;
for (j = 0; j < movesLength; j++) {
var move = moves[j];
if (move.from >= remove.index) move.from -= remove.howMany;
}
}
// Offset moves by inserts
for (i = insertsLength; i--;) {
var insert = inserts[i];
var howMany = insert.values.length;
for (j = movesLength; j--;) {
var move = moves[j];
if (move.to >= insert.index) move.to -= howMany;
}
}
// Offset the to of moves by later moves
for (i = movesLength; i-- > 1;) {
var move = moves[i];
if (move.to === move.from) continue;
for (j = i; j--;) {
var earlier = moves[j];
if (earlier.to >= move.to) earlier.to -= move.howMany;
if (earlier.to >= move.from) earlier.to += move.howMany;
}
}
// Only output moves that end up having an effect after offsetting
var outputMoves = [];
// Offset the from of moves by earlier moves
for (i = 0; i < movesLength; i++) {
var move = moves[i];
if (move.to === move.from) continue;
outputMoves.push(move);
for (j = i + 1; j < movesLength; j++) {
var later = moves[j];
if (later.from >= move.from) later.from -= move.howMany;
if (later.from >= move.to) later.from += move.howMany;
}
}
return removes.concat(outputMoves, inserts);
}
},{}],27:[function(require,module,exports){
'use strict'
exports.byteLength = byteLength
exports.toByteArray = toByteArray
exports.fromByteArray = fromByteArray
var lookup = []
var revLookup = []
var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
for (var i = 0, len = code.length; i < len; ++i) {
lookup[i] = code[i]
revLookup[code.charCodeAt(i)] = i
}
revLookup['-'.charCodeAt(0)] = 62
revLookup['_'.charCodeAt(0)] = 63
function placeHoldersCount (b64) {
var len = b64.length
if (len % 4 > 0) {
throw new Error('Invalid string. Length must be a multiple of 4')
}
// the number of equal signs (place holders)
// if there are two placeholders, than the two characters before it
// represent one byte
// if there is only one, then the three characters before it represent 2 bytes
// this is just a cheap hack to not do indexOf twice
return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0
}
function byteLength (b64) {
// base64 is 4/3 + up to two characters of the original data
return b64.length * 3 / 4 - placeHoldersCount(b64)
}
function toByteArray (b64) {
var i, j, l, tmp, placeHolders, arr
var len = b64.length
placeHolders = placeHoldersCount(b64)
arr = new Arr(len * 3 / 4 - placeHolders)
// if there are placeholders, only get up to the last complete 4 chars
l = placeHolders > 0 ? len - 4 : len
var L = 0
for (i = 0, j = 0; i < l; i += 4, j += 3) {
tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]
arr[L++] = (tmp >> 16) & 0xFF
arr[L++] = (tmp >> 8) & 0xFF
arr[L++] = tmp & 0xFF
}
if (placeHolders === 2) {
tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4)
arr[L++] = tmp & 0xFF
} else if (placeHolders === 1) {
tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2)
arr[L++] = (tmp >> 8) & 0xFF
arr[L++] = tmp & 0xFF
}
return arr
}
function tripletToBase64 (num) {
return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
}
function encodeChunk (uint8, start, end) {
var tmp
var output = []
for (var i = start; i < end; i += 3) {
tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
output.push(tripletToBase64(tmp))
}
return output.join('')
}
function fromByteArray (uint8) {
var tmp
var len = uint8.length
var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
var output = ''
var parts = []
var maxChunkLength = 16383 // must be multiple of 3
// go through the array every three bytes, we'll deal with trailing stuff later
for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
}
// pad the end with zeros, but make sure to not forget the extra bytes
if (extraBytes === 1) {
tmp = uint8[len - 1]
output += lookup[tmp >> 2]
output += lookup[(tmp << 4) & 0x3F]
output += '=='
} else if (extraBytes === 2) {
tmp = (uint8[len - 2] << 8) + (uint8[len - 1])
output += lookup[tmp >> 10]
output += lookup[(tmp >> 4) & 0x3F]
output += lookup[(tmp << 2) & 0x3F]
output += '='
}
parts.push(output)
return parts.join('')
}
},{}],28:[function(require,module,exports){
/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <[email protected]> <http://feross.org>
* @license MIT
*/
/* eslint-disable no-proto */
'use strict'
var base64 = require(27)
var ieee754 = require(38)
exports.Buffer = Buffer
exports.SlowBuffer = SlowBuffer
exports.INSPECT_MAX_BYTES = 50
var K_MAX_LENGTH = 0x7fffffff
exports.kMaxLength = K_MAX_LENGTH
/**
* If `Buffer.TYPED_ARRAY_SUPPORT`:
* === true Use Uint8Array implementation (fastest)
* === false Print warning and recommend using `buffer` v4.x which has an Object
* implementation (most compatible, even IE6)
*
* Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
* Opera 11.6+, iOS 4.2+.
*
* We report that the browser does not support typed arrays if the are not subclassable
* using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
* (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
* for __proto__ and has a buggy typed array implementation.
*/
Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
typeof console.error === 'function') {
console.error(
'This browser lacks typed array (Uint8Array) support which is required by ' +
'`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
)
}
function typedArraySupport () {
// Can typed array instances can be augmented?
try {
var arr = new Uint8Array(1)
arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}
return arr.foo() === 42
} catch (e) {
return false
}
}
function createBuffer (length) {
if (length > K_MAX_LENGTH) {
throw new RangeError('Invalid typed array length')
}
// Return an augmented `Uint8Array` instance
var buf = new Uint8Array(length)
buf.__proto__ = Buffer.prototype
return buf
}
/**
* The Buffer constructor returns instances of `Uint8Array` that have their
* prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
* `Uint8Array`, so the returned instances will have all the node `Buffer` methods
* and the `Uint8Array` methods. Square bracket notation works as expected -- it
* returns a single octet.
*
* The `Uint8Array` prototype remains unmodified.
*/
function Buffer (arg, encodingOrOffset, length) {
// Common case.
if (typeof arg === 'number') {
if (typeof encodingOrOffset === 'string') {
throw new Error(
'If encoding is specified then the first argument must be a string'
)
}
return allocUnsafe(arg)
}
return from(arg, encodingOrOffset, length)
}
// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
if (typeof Symbol !== 'undefined' && Symbol.species &&
Buffer[Symbol.species] === Buffer) {
Object.defineProperty(Buffer, Symbol.species, {
value: null,
configurable: true,
enumerable: false,
writable: false
})
}
Buffer.poolSize = 8192 // not used by this implementation
function from (value, encodingOrOffset, length) {
if (typeof value === 'number') {
throw new TypeError('"value" argument must not be a number')
}
if (value instanceof ArrayBuffer) {
return fromArrayBuffer(value, encodingOrOffset, length)
}
if (typeof value === 'string') {
return fromString(value, encodingOrOffset)
}
return fromObject(value)
}
/**
* Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
* if value is a number.
* Buffer.from(str[, encoding])
* Buffer.from(array)
* Buffer.from(buffer)
* Buffer.from(arrayBuffer[, byteOffset[, length]])
**/
Buffer.from = function (value, encodingOrOffset, length) {
return from(value, encodingOrOffset, length)
}
// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
// https://github.com/feross/buffer/pull/148
Buffer.prototype.__proto__ = Uint8Array.prototype
Buffer.__proto__ = Uint8Array
function assertSize (size) {
if (typeof size !== 'number') {
throw new TypeError('"size" argument must be a number')
} else if (size < 0) {
throw new RangeError('"size" argument must not be negative')
}
}
function alloc (size, fill, encoding) {
assertSize(size)
if (size <= 0) {
return createBuffer(size)
}
if (fill !== undefined) {
// Only pay attention to encoding if it's a string. This
// prevents accidentally sending in a number that would
// be interpretted as a start offset.
return typeof encoding === 'string'
? createBuffer(size).fill(fill, encoding)
: createBuffer(size).fill(fill)
}
return createBuffer(size)
}
/**
* Creates a new filled Buffer instance.
* alloc(size[, fill[, encoding]])
**/
Buffer.alloc = function (size, fill, encoding) {
return alloc(size, fill, encoding)
}
function allocUnsafe (size) {
assertSize(size)
return createBuffer(size < 0 ? 0 : checked(size) | 0)
}
/**
* Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
* */
Buffer.allocUnsafe = function (size) {
return allocUnsafe(size)
}
/**
* Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
*/
Buffer.allocUnsafeSlow = function (size) {
return allocUnsafe(size)
}
function fromString (string, encoding) {
if (typeof encoding !== 'string' || encoding === '') {
encoding = 'utf8'
}
if (!Buffer.isEncoding(encoding)) {
throw new TypeError('"encoding" must be a valid string encoding')
}
var length = byteLength(string, encoding) | 0
var buf = createBuffer(length)
var actual = buf.write(string, encoding)
if (actual !== length) {
// Writing a hex string, for example, that contains invalid characters will
// cause everything after the first invalid character to be ignored. (e.g.
// 'abxxcd' will be treated as 'ab')
buf = buf.slice(0, actual)
}
return buf
}
function fromArrayLike (array) {
var length = array.length < 0 ? 0 : checked(array.length) | 0
var buf = createBuffer(length)
for (var i = 0; i < length; i += 1) {
buf[i] = array[i] & 255
}
return buf
}
function fromArrayBuffer (array, byteOffset, length) {
if (byteOffset < 0 || array.byteLength < byteOffset) {
throw new RangeError('\'offset\' is out of bounds')
}
if (array.byteLength < byteOffset + (length || 0)) {
throw new RangeError('\'length\' is out of bounds')
}
var buf
if (byteOffset === undefined && length === undefined) {
buf = new Uint8Array(array)
} else if (length === undefined) {
buf = new Uint8Array(array, byteOffset)
} else {
buf = new Uint8Array(array, byteOffset, length)
}
// Return an augmented `Uint8Array` instance
buf.__proto__ = Buffer.prototype
return buf
}
function fromObject (obj) {
if (Buffer.isBuffer(obj)) {
var len = checked(obj.length) | 0
var buf = createBuffer(len)
if (buf.length === 0) {
return buf
}
obj.copy(buf, 0, 0, len)
return buf
}
if (obj) {
if (isArrayBufferView(obj) || 'length' in obj) {
if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
return createBuffer(0)
}
return fromArrayLike(obj)
}
if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
return fromArrayLike(obj.data)
}
}
throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
}
function checked (length) {
// Note: cannot use `length < K_MAX_LENGTH` here because that fails when
// length is NaN (which is otherwise coerced to zero.)
if (length >= K_MAX_LENGTH) {
throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
}
return length | 0
}
function SlowBuffer (length) {
if (+length != length) { // eslint-disable-line eqeqeq
length = 0
}
return Buffer.alloc(+length)
}
Buffer.isBuffer = function isBuffer (b) {
return b != null && b._isBuffer === true
}
Buffer.compare = function compare (a, b) {
if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
throw new TypeError('Arguments must be Buffers')
}
if (a === b) return 0
var x = a.length
var y = b.length
for (var i = 0, len = Math.min(x, y); i < len; ++i) {
if (a[i] !== b[i]) {
x = a[i]
y = b[i]
break
}
}
if (x < y) return -1
if (y < x) return 1
return 0
}
Buffer.isEncoding = function isEncoding (encoding) {
switch (String(encoding).toLowerCase()) {
case 'hex':
case 'utf8':
case 'utf-8':
case 'ascii':
case 'latin1':
case 'binary':
case 'base64':
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return true
default:
return false
}
}
Buffer.concat = function concat (list, length) {
if (!Array.isArray(list)) {
throw new TypeError('"list" argument must be an Array of Buffers')
}
if (list.length === 0) {
return Buffer.alloc(0)
}
var i
if (length === undefined) {
length = 0
for (i = 0; i < list.length; ++i) {
length += list[i].length
}
}
var buffer = Buffer.allocUnsafe(length)
var pos = 0
for (i = 0; i < list.length; ++i) {
var buf = list[i]
if (!Buffer.isBuffer(buf)) {
throw new TypeError('"list" argument must be an Array of Buffers')
}
buf.copy(buffer, pos)
pos += buf.length
}
return buffer
}
function byteLength (string, encoding) {
if (Buffer.isBuffer(string)) {
return string.length
}
if (isArrayBufferView(string) || string instanceof ArrayBuffer) {
return string.byteLength
}
if (typeof string !== 'string') {
string = '' + string
}
var len = string.length
if (len === 0) return 0
// Use a for loop to avoid recursion
var loweredCase = false
for (;;) {
switch (encoding) {
case 'ascii':
case 'latin1':
case 'binary':
return len
case 'utf8':
case 'utf-8':
case undefined:
return utf8ToBytes(string).length
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return len * 2
case 'hex':
return len >>> 1
case 'base64':
return base64ToBytes(string).length
default:
if (loweredCase) return utf8ToBytes(string).length // assume utf8
encoding = ('' + encoding).toLowerCase()
loweredCase = true
}
}
}
Buffer.byteLength = byteLength
function slowToString (encoding, start, end) {
var loweredCase = false
// No need to verify that "this.length <= MAX_UINT32" since it's a read-only
// property of a typed array.
// This behaves neither like String nor Uint8Array in that we set start/end
// to their upper/lower bounds if the value passed is out of range.
// undefined is handled specially as per ECMA-262 6th Edition,
// Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
if (start === undefined || start < 0) {
start = 0
}
// Return early if start > this.length. Done here to prevent potential uint32
// coercion fail below.
if (start > this.length) {
return ''
}
if (end === undefined || end > this.length) {
end = this.length
}
if (end <= 0) {
return ''
}
// Force coersion to uint32. This will also coerce falsey/NaN values to 0.
end >>>= 0
start >>>= 0
if (end <= start) {
return ''
}
if (!encoding) encoding = 'utf8'
while (true) {
switch (encoding) {
case 'hex':
return hexSlice(this, start, end)
case 'utf8':
case 'utf-8':
return utf8Slice(this, start, end)
case 'ascii':
return asciiSlice(this, start, end)
case 'latin1':
case 'binary':
return latin1Slice(this, start, end)
case 'base64':
return base64Slice(this, start, end)
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return utf16leSlice(this, start, end)
default:
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
encoding = (encoding + '').toLowerCase()
loweredCase = true
}
}
}
// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
// to detect a Buffer instance. It's not possible to use `instanceof Buffer`
// reliably in a browserify context because there could be multiple different
// copies of the 'buffer' package in use. This method works even for Buffer
// instances that were created from another copy of the `buffer` package.
// See: https://github.com/feross/buffer/issues/154
Buffer.prototype._isBuffer = true
function swap (b, n, m) {
var i = b[n]
b[n] = b[m]
b[m] = i
}
Buffer.prototype.swap16 = function swap16 () {
var len = this.length
if (len % 2 !== 0) {
throw new RangeError('Buffer size must be a multiple of 16-bits')
}
for (var i = 0; i < len; i += 2) {
swap(this, i, i + 1)
}
return this
}
Buffer.prototype.swap32 = function swap32 () {
var len = this.length
if (len % 4 !== 0) {
throw new RangeError('Buffer size must be a multiple of 32-bits')
}
for (var i = 0; i < len; i += 4) {
swap(this, i, i + 3)
swap(this, i + 1, i + 2)
}
return this
}
Buffer.prototype.swap64 = function swap64 () {
var len = this.length
if (len % 8 !== 0) {
throw new RangeError('Buffer size must be a multiple of 64-bits')
}
for (var i = 0; i < len; i += 8) {
swap(this, i, i + 7)
swap(this, i + 1, i + 6)
swap(this, i + 2, i + 5)
swap(this, i + 3, i + 4)
}
return this
}
Buffer.prototype.toString = function toString () {
var length = this.length
if (length === 0) return ''
if (arguments.length === 0) return utf8Slice(this, 0, length)
return slowToString.apply(this, arguments)
}
Buffer.prototype.equals = function equals (b) {
if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
if (this === b) return true
return Buffer.compare(this, b) === 0
}
Buffer.prototype.inspect = function inspect () {
var str = ''
var max = exports.INSPECT_MAX_BYTES
if (this.length > 0) {
str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
if (this.length > max) str += ' ... '
}
return '<Buffer ' + str + '>'
}
Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
if (!Buffer.isBuffer(target)) {
throw new TypeError('Argument must be a Buffer')
}
if (start === undefined) {
start = 0
}
if (end === undefined) {
end = target ? target.length : 0
}
if (thisStart === undefined) {
thisStart = 0
}
if (thisEnd === undefined) {
thisEnd = this.length
}
if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
throw new RangeError('out of range index')
}
if (thisStart >= thisEnd && start >= end) {
return 0
}
if (thisStart >= thisEnd) {
return -1
}
if (start >= end) {
return 1
}
start >>>= 0
end >>>= 0
thisStart >>>= 0
thisEnd >>>= 0
if (this === target) return 0
var x = thisEnd - thisStart
var y = end - start
var len = Math.min(x, y)
var thisCopy = this.slice(thisStart, thisEnd)
var targetCopy = target.slice(start, end)
for (var i = 0; i < len; ++i) {
if (thisCopy[i] !== targetCopy[i]) {
x = thisCopy[i]
y = targetCopy[i]
break
}
}
if (x < y) return -1
if (y < x) return 1
return 0
}
// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
//
// Arguments:
// - buffer - a Buffer to search
// - val - a string, Buffer, or number
// - byteOffset - an index into `buffer`; will be clamped to an int32
// - encoding - an optional encoding, relevant is val is a string
// - dir - true for indexOf, false for lastIndexOf
function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
// Empty buffer means no match
if (buffer.length === 0) return -1
// Normalize byteOffset
if (typeof byteOffset === 'string') {
encoding = byteOffset
byteOffset = 0
} else if (byteOffset > 0x7fffffff) {
byteOffset = 0x7fffffff
} else if (byteOffset < -0x80000000) {
byteOffset = -0x80000000
}
byteOffset = +byteOffset // Coerce to Number.
if (numberIsNaN(byteOffset)) {
// byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
byteOffset = dir ? 0 : (buffer.length - 1)
}
// Normalize byteOffset: negative offsets start from the end of the buffer
if (byteOffset < 0) byteOffset = buffer.length + byteOffset
if (byteOffset >= buffer.length) {
if (dir) return -1
else byteOffset = buffer.length - 1
} else if (byteOffset < 0) {
if (dir) byteOffset = 0
else return -1
}
// Normalize val
if (typeof val === 'string') {
val = Buffer.from(val, encoding)
}
// Finally, search either indexOf (if dir is true) or lastIndexOf
if (Buffer.isBuffer(val)) {
// Special case: looking for empty string/buffer always fails
if (val.length === 0) {
return -1
}
return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
} else if (typeof val === 'number') {
val = val & 0xFF // Search for a byte value [0-255]
if (typeof Uint8Array.prototype.indexOf === 'function') {
if (dir) {
return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
} else {
return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
}
}
return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
}
throw new TypeError('val must be string, number or Buffer')
}
function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
var indexSize = 1
var arrLength = arr.length
var valLength = val.length
if (encoding !== undefined) {
encoding = String(encoding).toLowerCase()
if (encoding === 'ucs2' || encoding === 'ucs-2' ||
encoding === 'utf16le' || encoding === 'utf-16le') {
if (arr.length < 2 || val.length < 2) {
return -1
}
indexSize = 2
arrLength /= 2
valLength /= 2
byteOffset /= 2
}
}
function read (buf, i) {
if (indexSize === 1) {
return buf[i]
} else {
return buf.readUInt16BE(i * indexSize)
}
}
var i
if (dir) {
var foundIndex = -1
for (i = byteOffset; i < arrLength; i++) {
if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
if (foundIndex === -1) foundIndex = i
if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
} else {
if (foundIndex !== -1) i -= i - foundIndex
foundIndex = -1
}
}
} else {
if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
for (i = byteOffset; i >= 0; i--) {
var found = true
for (var j = 0; j < valLength; j++) {
if (read(arr, i + j) !== read(val, j)) {
found = false
break
}
}
if (found) return i
}
}
return -1
}
Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
return this.indexOf(val, byteOffset, encoding) !== -1
}
Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
}
Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
}
function hexWrite (buf, string, offset, length) {
offset = Number(offset) || 0
var remaining = buf.length - offset
if (!length) {
length = remaining
} else {
length = Number(length)
if (length > remaining) {
length = remaining
}
}
// must be an even number of digits
var strLen = string.length
if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
if (length > strLen / 2) {
length = strLen / 2
}
for (var i = 0; i < length; ++i) {
var parsed = parseInt(string.substr(i * 2, 2), 16)
if (numberIsNaN(parsed)) return i
buf[offset + i] = parsed
}
return i
}
function utf8Write (buf, string, offset, length) {
return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
}
function asciiWrite (buf, string, offset, length) {
return blitBuffer(asciiToBytes(string), buf, offset, length)
}
function latin1Write (buf, string, offset, length) {
return asciiWrite(buf, string, offset, length)
}
function base64Write (buf, string, offset, length) {
return blitBuffer(base64ToBytes(string), buf, offset, length)
}
function ucs2Write (buf, string, offset, length) {
return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
}
Buffer.prototype.write = function write (string, offset, length, encoding) {
// Buffer#write(string)
if (offset === undefined) {
encoding = 'utf8'
length = this.length
offset = 0
// Buffer#write(string, encoding)
} else if (length === undefined && typeof offset === 'string') {
encoding = offset
length = this.length
offset = 0
// Buffer#write(string, offset[, length][, encoding])
} else if (isFinite(offset)) {
offset = offset >>> 0
if (isFinite(length)) {
length = length >>> 0
if (encoding === undefined) encoding = 'utf8'
} else {
encoding = length
length = undefined
}
} else {
throw new Error(
'Buffer.write(string, encoding, offset[, length]) is no longer supported'
)
}
var remaining = this.length - offset
if (length === undefined || length > remaining) length = remaining
if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
throw new RangeError('Attempt to write outside buffer bounds')
}
if (!encoding) encoding = 'utf8'
var loweredCase = false
for (;;) {
switch (encoding) {
case 'hex':
return hexWrite(this, string, offset, length)
case 'utf8':
case 'utf-8':
return utf8Write(this, string, offset, length)
case 'ascii':
return asciiWrite(this, string, offset, length)
case 'latin1':
case 'binary':
return latin1Write(this, string, offset, length)
case 'base64':
// Warning: maxLength not taken into account in base64Write
return base64Write(this, string, offset, length)
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return ucs2Write(this, string, offset, length)
default:
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
encoding = ('' + encoding).toLowerCase()
loweredCase = true
}
}
}
Buffer.prototype.toJSON = function toJSON () {
return {
type: 'Buffer',
data: Array.prototype.slice.call(this._arr || this, 0)
}
}
function base64Slice (buf, start, end) {
if (start === 0 && end === buf.length) {
return base64.fromByteArray(buf)
} else {
return base64.fromByteArray(buf.slice(start, end))
}
}
function utf8Slice (buf, start, end) {
end = Math.min(buf.length, end)
var res = []
var i = start
while (i < end) {
var firstByte = buf[i]
var codePoint = null
var bytesPerSequence = (firstByte > 0xEF) ? 4
: (firstByte > 0xDF) ? 3
: (firstByte > 0xBF) ? 2
: 1
if (i + bytesPerSequence <= end) {
var secondByte, thirdByte, fourthByte, tempCodePoint
switch (bytesPerSequence) {
case 1:
if (firstByte < 0x80) {
codePoint = firstByte
}
break
case 2:
secondByte = buf[i + 1]
if ((secondByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
if (tempCodePoint > 0x7F) {
codePoint = tempCodePoint
}
}
break
case 3:
secondByte = buf[i + 1]
thirdByte = buf[i + 2]
if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
codePoint = tempCodePoint
}
}
break
case 4:
secondByte = buf[i + 1]
thirdByte = buf[i + 2]
fourthByte = buf[i + 3]
if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
codePoint = tempCodePoint
}
}
}
}
if (codePoint === null) {
// we did not generate a valid codePoint so insert a
// replacement char (U+FFFD) and advance only 1 byte
codePoint = 0xFFFD
bytesPerSequence = 1
} else if (codePoint > 0xFFFF) {
// encode to utf16 (surrogate pair dance)
codePoint -= 0x10000
res.push(codePoint >>> 10 & 0x3FF | 0xD800)
codePoint = 0xDC00 | codePoint & 0x3FF
}
res.push(codePoint)
i += bytesPerSequence
}
return decodeCodePointsArray(res)
}
// Based on http://stackoverflow.com/a/22747272/680742, the browser with
// the lowest limit is Chrome, with 0x10000 args.
// We go 1 magnitude less, for safety
var MAX_ARGUMENTS_LENGTH = 0x1000
function decodeCodePointsArray (codePoints) {
var len = codePoints.length
if (len <= MAX_ARGUMENTS_LENGTH) {
return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
}
// Decode in chunks to avoid "call stack size exceeded".
var res = ''
var i = 0
while (i < len) {
res += String.fromCharCode.apply(
String,
codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
)
}
return res
}
function asciiSlice (buf, start, end) {
var ret = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; ++i) {
ret += String.fromCharCode(buf[i] & 0x7F)
}
return ret
}
function latin1Slice (buf, start, end) {
var ret = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; ++i) {
ret += String.fromCharCode(buf[i])
}
return ret
}
function hexSlice (buf, start, end) {
var len = buf.length
if (!start || start < 0) start = 0
if (!end || end < 0 || end > len) end = len
var out = ''
for (var i = start; i < end; ++i) {
out += toHex(buf[i])
}
return out
}
function utf16leSlice (buf, start, end) {
var bytes = buf.slice(start, end)
var res = ''
for (var i = 0; i < bytes.length; i += 2) {
res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
}
return res
}
Buffer.prototype.slice = function slice (start, end) {
var len = this.length
start = ~~start
end = end === undefined ? len : ~~end
if (start < 0) {
start += len
if (start < 0) start = 0
} else if (start > len) {
start = len
}
if (end < 0) {
end += len
if (end < 0) end = 0
} else if (end > len) {
end = len
}
if (end < start) end = start
var newBuf = this.subarray(start, end)
// Return an augmented `Uint8Array` instance
newBuf.__proto__ = Buffer.prototype
return newBuf
}
/*
* Need to make sure that buffer isn't trying to write out of bounds.
*/
function checkOffset (offset, ext, length) {
if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
}
Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var val = this[offset]
var mul = 1
var i = 0
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul
}
return val
}
Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) {
checkOffset(offset, byteLength, this.length)
}
var val = this[offset + --byteLength]
var mul = 1
while (byteLength > 0 && (mul *= 0x100)) {
val += this[offset + --byteLength] * mul
}
return val
}
Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 1, this.length)
return this[offset]
}
Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 2, this.length)
return this[offset] | (this[offset + 1] << 8)
}
Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 2, this.length)
return (this[offset] << 8) | this[offset + 1]
}
Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return ((this[offset]) |
(this[offset + 1] << 8) |
(this[offset + 2] << 16)) +
(this[offset + 3] * 0x1000000)
}
Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset] * 0x1000000) +
((this[offset + 1] << 16) |
(this[offset + 2] << 8) |
this[offset + 3])
}
Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var val = this[offset]
var mul = 1
var i = 0
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul
}
mul *= 0x80
if (val >= mul) val -= Math.pow(2, 8 * byteLength)
return val
}
Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var i = byteLength
var mul = 1
var val = this[offset + --i]
while (i > 0 && (mul *= 0x100)) {
val += this[offset + --i] * mul
}
mul *= 0x80
if (val >= mul) val -= Math.pow(2, 8 * byteLength)
return val
}
Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 1, this.length)
if (!(this[offset] & 0x80)) return (this[offset])
return ((0xff - this[offset] + 1) * -1)
}
Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 2, this.length)
var val = this[offset] | (this[offset + 1] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
}
Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 2, this.length)
var val = this[offset + 1] | (this[offset] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
}
Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset]) |
(this[offset + 1] << 8) |
(this[offset + 2] << 16) |
(this[offset + 3] << 24)
}
Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset] << 24) |
(this[offset + 1] << 16) |
(this[offset + 2] << 8) |
(this[offset + 3])
}
Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, true, 23, 4)
}
Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, false, 23, 4)
}
Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, true, 52, 8)
}
Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, false, 52, 8)
}
function checkInt (buf, value, offset, ext, max, min) {
if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
if (offset + ext > buf.length) throw new RangeError('Index out of range')
}
Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) {
var maxBytes = Math.pow(2, 8 * byteLength) - 1
checkInt(this, value, offset, byteLength, maxBytes, 0)
}
var mul = 1
var i = 0
this[offset] = value & 0xFF
while (++i < byteLength && (mul *= 0x100)) {
this[offset + i] = (value / mul) & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) {
var maxBytes = Math.pow(2, 8 * byteLength) - 1
checkInt(this, value, offset, byteLength, maxBytes, 0)
}
var i = byteLength - 1
var mul = 1
this[offset + i] = value & 0xFF
while (--i >= 0 && (mul *= 0x100)) {
this[offset + i] = (value / mul) & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
this[offset] = (value & 0xff)
return offset + 1
}
Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
return offset + 2
}
Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
this[offset] = (value >>> 8)
this[offset + 1] = (value & 0xff)
return offset + 2
}
Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
this[offset + 3] = (value >>> 24)
this[offset + 2] = (value >>> 16)
this[offset + 1] = (value >>> 8)
this[offset] = (value & 0xff)
return offset + 4
}
Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = (value & 0xff)
return offset + 4
}
Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) {
var limit = Math.pow(2, (8 * byteLength) - 1)
checkInt(this, value, offset, byteLength, limit - 1, -limit)
}
var i = 0
var mul = 1
var sub = 0
this[offset] = value & 0xFF
while (++i < byteLength && (mul *= 0x100)) {
if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
sub = 1
}
this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) {
var limit = Math.pow(2, (8 * byteLength) - 1)
checkInt(this, value, offset, byteLength, limit - 1, -limit)
}
var i = byteLength - 1
var mul = 1
var sub = 0
this[offset + i] = value & 0xFF
while (--i >= 0 && (mul *= 0x100)) {
if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
sub = 1
}
this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
if (value < 0) value = 0xff + value + 1
this[offset] = (value & 0xff)
return offset + 1
}
Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
return offset + 2
}
Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
this[offset] = (value >>> 8)
this[offset + 1] = (value & 0xff)
return offset + 2
}
Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
this[offset + 2] = (value >>> 16)
this[offset + 3] = (value >>> 24)
return offset + 4
}
Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
if (value < 0) value = 0xffffffff + value + 1
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = (value & 0xff)
return offset + 4
}
function checkIEEE754 (buf, value, offset, ext, max, min) {
if (offset + ext > buf.length) throw new RangeError('Index out of range')
if (offset < 0) throw new RangeError('Index out of range')
}
function writeFloat (buf, value, offset, littleEndian, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) {
checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
}
ieee754.write(buf, value, offset, littleEndian, 23, 4)
return offset + 4
}
Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
return writeFloat(this, value, offset, true, noAssert)
}
Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
return writeFloat(this, value, offset, false, noAssert)
}
function writeDouble (buf, value, offset, littleEndian, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) {
checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
}
ieee754.write(buf, value, offset, littleEndian, 52, 8)
return offset + 8
}
Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
return writeDouble(this, value, offset, true, noAssert)
}
Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
return writeDouble(this, value, offset, false, noAssert)
}
// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
Buffer.prototype.copy = function copy (target, targetStart, start, end) {
if (!start) start = 0
if (!end && end !== 0) end = this.length
if (targetStart >= target.length) targetStart = target.length
if (!targetStart) targetStart = 0
if (end > 0 && end < start) end = start
// Copy 0 bytes; we're done
if (end === start) return 0
if (target.length === 0 || this.length === 0) return 0
// Fatal error conditions
if (targetStart < 0) {
throw new RangeError('targetStart out of bounds')
}
if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
if (end < 0) throw new RangeError('sourceEnd out of bounds')
// Are we oob?
if (end > this.length) end = this.length
if (target.length - targetStart < end - start) {
end = target.length - targetStart + start
}
var len = end - start
var i
if (this === target && start < targetStart && targetStart < end) {
// descending copy from end
for (i = len - 1; i >= 0; --i) {
target[i + targetStart] = this[i + start]
}
} else if (len < 1000) {
// ascending copy from start
for (i = 0; i < len; ++i) {
target[i + targetStart] = this[i + start]
}
} else {
Uint8Array.prototype.set.call(
target,
this.subarray(start, start + len),
targetStart
)
}
return len
}
// Usage:
// buffer.fill(number[, offset[, end]])
// buffer.fill(buffer[, offset[, end]])
// buffer.fill(string[, offset[, end]][, encoding])
Buffer.prototype.fill = function fill (val, start, end, encoding) {
// Handle string cases:
if (typeof val === 'string') {
if (typeof start === 'string') {
encoding = start
start = 0
end = this.length
} else if (typeof end === 'string') {
encoding = end
end = this.length
}
if (val.length === 1) {
var code = val.charCodeAt(0)
if (code < 256) {
val = code
}
}
if (encoding !== undefined && typeof encoding !== 'string') {
throw new TypeError('encoding must be a string')
}
if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
throw new TypeError('Unknown encoding: ' + encoding)
}
} else if (typeof val === 'number') {
val = val & 255
}
// Invalid ranges are not set to a default, so can range check early.
if (start < 0 || this.length < start || this.length < end) {
throw new RangeError('Out of range index')
}
if (end <= start) {
return this
}
start = start >>> 0
end = end === undefined ? this.length : end >>> 0
if (!val) val = 0
var i
if (typeof val === 'number') {
for (i = start; i < end; ++i) {
this[i] = val
}
} else {
var bytes = Buffer.isBuffer(val)
? val
: new Buffer(val, encoding)
var len = bytes.length
for (i = 0; i < end - start; ++i) {
this[i + start] = bytes[i % len]
}
}
return this
}
// HELPER FUNCTIONS
// ================
var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
function base64clean (str) {
// Node strips out invalid characters like \n and \t from the string, base64-js does not
str = str.trim().replace(INVALID_BASE64_RE, '')
// Node converts strings with length < 2 to ''
if (str.length < 2) return ''
// Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
while (str.length % 4 !== 0) {
str = str + '='
}
return str
}
function toHex (n) {
if (n < 16) return '0' + n.toString(16)
return n.toString(16)
}
function utf8ToBytes (string, units) {
units = units || Infinity
var codePoint
var length = string.length
var leadSurrogate = null
var bytes = []
for (var i = 0; i < length; ++i) {
codePoint = string.charCodeAt(i)
// is surrogate component
if (codePoint > 0xD7FF && codePoint < 0xE000) {
// last char was a lead
if (!leadSurrogate) {
// no lead yet
if (codePoint > 0xDBFF) {
// unexpected trail
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
continue
} else if (i + 1 === length) {
// unpaired lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
continue
}
// valid lead
leadSurrogate = codePoint
continue
}
// 2 leads in a row
if (codePoint < 0xDC00) {
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
leadSurrogate = codePoint
continue
}
// valid surrogate pair
codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
} else if (leadSurrogate) {
// valid bmp char, but last char was a lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
}
leadSurrogate = null
// encode utf8
if (codePoint < 0x80) {
if ((units -= 1) < 0) break
bytes.push(codePoint)
} else if (codePoint < 0x800) {
if ((units -= 2) < 0) break
bytes.push(
codePoint >> 0x6 | 0xC0,
codePoint & 0x3F | 0x80
)
} else if (codePoint < 0x10000) {
if ((units -= 3) < 0) break
bytes.push(
codePoint >> 0xC | 0xE0,
codePoint >> 0x6 & 0x3F | 0x80,
codePoint & 0x3F | 0x80
)
} else if (codePoint < 0x110000) {
if ((units -= 4) < 0) break
bytes.push(
codePoint >> 0x12 | 0xF0,
codePoint >> 0xC & 0x3F | 0x80,
codePoint >> 0x6 & 0x3F | 0x80,
codePoint & 0x3F | 0x80
)
} else {
throw new Error('Invalid code point')
}
}
return bytes
}
function asciiToBytes (str) {
var byteArray = []
for (var i = 0; i < str.length; ++i) {
// Node's code seems to be doing this and not & 0x7F..
byteArray.push(str.charCodeAt(i) & 0xFF)
}
return byteArray
}
function utf16leToBytes (str, units) {
var c, hi, lo
var byteArray = []
for (var i = 0; i < str.length; ++i) {
if ((units -= 2) < 0) break
c = str.charCodeAt(i)
hi = c >> 8
lo = c % 256
byteArray.push(lo)
byteArray.push(hi)
}
return byteArray
}
function base64ToBytes (str) {
return base64.toByteArray(base64clean(str))
}
function blitBuffer (src, dst, offset, length) {
for (var i = 0; i < length; ++i) {
if ((i + offset >= dst.length) || (i >= src.length)) break
dst[i + offset] = src[i]
}
return i
}
// Node 0.10 supports `ArrayBuffer` but lacks `ArrayBuffer.isView`
function isArrayBufferView (obj) {
return (typeof ArrayBuffer.isView === 'function') && ArrayBuffer.isView(obj)
}
function numberIsNaN (obj) {
return obj !== obj // eslint-disable-line no-self-compare
}
},{"27":27,"38":38}],29:[function(require,module,exports){
/**
* @author Markus Ekholm
* @copyright 2012-2015 (c) Markus Ekholm <markus at botten dot org >
* @license Copyright (c) 2012-2015, Markus Ekholm
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the <organization> nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL MARKUS EKHOLM BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* EXPORTS
*/
exports.rgb_to_lab = rgb_to_lab;
/**
* IMPORTS
*/
var pow = Math.pow;
var sqrt = Math.sqrt;
/**
* API FUNCTIONS
*/
/**
* Returns c converted to labcolor.
* @param {rgbcolor} c should have fields R,G,B
* @return {labcolor} c converted to labcolor
*/
function rgb_to_lab(c)
{
return xyz_to_lab(rgb_to_xyz(c))
}
/**
* Returns c converted to xyzcolor.
* @param {rgbcolor} c should have fields R,G,B
* @return {xyzcolor} c converted to xyzcolor
*/
function rgb_to_xyz(c)
{
// Based on http://www.easyrgb.com/index.php?X=MATH&H=02
var R = ( c.R / 255 );
var G = ( c.G / 255 );
var B = ( c.B / 255 );
if ( R > 0.04045 ) R = pow(( ( R + 0.055 ) / 1.055 ),2.4);
else R = R / 12.92;
if ( G > 0.04045 ) G = pow(( ( G + 0.055 ) / 1.055 ),2.4);
else G = G / 12.92;
if ( B > 0.04045 ) B = pow(( ( B + 0.055 ) / 1.055 ), 2.4);
else B = B / 12.92;
R *= 100;
G *= 100;
B *= 100;
// Observer. = 2°, Illuminant = D65
var X = R * 0.4124 + G * 0.3576 + B * 0.1805;
var Y = R * 0.2126 + G * 0.7152 + B * 0.0722;
var Z = R * 0.0193 + G * 0.1192 + B * 0.9505;
return {'X' : X, 'Y' : Y, 'Z' : Z};
}
/**
* Returns c converted to labcolor.
* @param {xyzcolor} c should have fields X,Y,Z
* @return {labcolor} c converted to labcolor
*/
function xyz_to_lab(c)
{
// Based on http://www.easyrgb.com/index.php?X=MATH&H=07
var ref_Y = 100.000;
var ref_Z = 108.883;
var ref_X = 95.047; // Observer= 2°, Illuminant= D65
var Y = c.Y / ref_Y;
var Z = c.Z / ref_Z;
var X = c.X / ref_X;
if ( X > 0.008856 ) X = pow(X, 1/3);
else X = ( 7.787 * X ) + ( 16 / 116 );
if ( Y > 0.008856 ) Y = pow(Y, 1/3);
else Y = ( 7.787 * Y ) + ( 16 / 116 );
if ( Z > 0.008856 ) Z = pow(Z, 1/3);
else Z = ( 7.787 * Z ) + ( 16 / 116 );
var L = ( 116 * Y ) - 16;
var a = 500 * ( X - Y );
var b = 200 * ( Y - Z );
return {'L' : L , 'a' : a, 'b' : b};
}
// Local Variables:
// allout-layout: t
// js-indent-level: 2
// End:
},{}],30:[function(require,module,exports){
/**
* @author Markus Ekholm
* @copyright 2012-2015 (c) Markus Ekholm <markus at botten dot org >
* @license Copyright (c) 2012-2015, Markus Ekholm
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the <organization> nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL MARKUS EKHOLM BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* EXPORTS
*/
exports.ciede2000 = ciede2000;
/**
* IMPORTS
*/
var sqrt = Math.sqrt;
var pow = Math.pow;
var cos = Math.cos;
var atan2 = Math.atan2;
var sin = Math.sin;
var abs = Math.abs;
var exp = Math.exp;
var PI = Math.PI;
/**
* API FUNCTIONS
*/
/**
* Returns diff between c1 and c2 using the CIEDE2000 algorithm
* @param {labcolor} c1 Should have fields L,a,b
* @param {labcolor} c2 Should have fields L,a,b
* @return {float} Difference between c1 and c2
*/
function ciede2000(c1,c2)
{
/**
* Implemented as in "The CIEDE2000 Color-Difference Formula:
* Implementation Notes, Supplementary Test Data, and Mathematical Observations"
* by Gaurav Sharma, Wencheng Wu and Edul N. Dalal.
*/
// Get L,a,b values for color 1
var L1 = c1.L;
var a1 = c1.a;
var b1 = c1.b;
// Get L,a,b values for color 2
var L2 = c2.L;
var a2 = c2.a;
var b2 = c2.b;
// Weight factors
var kL = 1;
var kC = 1;
var kH = 1;
/**
* Step 1: Calculate C1p, C2p, h1p, h2p
*/
var C1 = sqrt(pow(a1, 2) + pow(b1, 2)) //(2)
var C2 = sqrt(pow(a2, 2) + pow(b2, 2)) //(2)
var a_C1_C2 = (C1+C2)/2.0; //(3)
var G = 0.5 * (1 - sqrt(pow(a_C1_C2 , 7.0) /
(pow(a_C1_C2, 7.0) + pow(25.0, 7.0)))); //(4)
var a1p = (1.0 + G) * a1; //(5)
var a2p = (1.0 + G) * a2; //(5)
var C1p = sqrt(pow(a1p, 2) + pow(b1, 2)); //(6)
var C2p = sqrt(pow(a2p, 2) + pow(b2, 2)); //(6)
var hp_f = function(x,y) //(7)
{
if(x== 0 && y == 0) return 0;
else{
var tmphp = degrees(atan2(x,y));
if(tmphp >= 0) return tmphp
else return tmphp + 360;
}
}
var h1p = hp_f(b1, a1p); //(7)
var h2p = hp_f(b2, a2p); //(7)
/**
* Step 2: Calculate dLp, dCp, dHp
*/
var dLp = L2 - L1; //(8)
var dCp = C2p - C1p; //(9)
var dhp_f = function(C1, C2, h1p, h2p) //(10)
{
if(C1*C2 == 0) return 0;
else if(abs(h2p-h1p) <= 180) return h2p-h1p;
else if((h2p-h1p) > 180) return (h2p-h1p)-360;
else if((h2p-h1p) < -180) return (h2p-h1p)+360;
else throw(new Error());
}
var dhp = dhp_f(C1,C2, h1p, h2p); //(10)
var dHp = 2*sqrt(C1p*C2p)*sin(radians(dhp)/2.0); //(11)
/**
* Step 3: Calculate CIEDE2000 Color-Difference
*/
var a_L = (L1 + L2) / 2.0; //(12)
var a_Cp = (C1p + C2p) / 2.0; //(13)
var a_hp_f = function(C1, C2, h1p, h2p) { //(14)
if(C1*C2 == 0) return h1p+h2p
else if(abs(h1p-h2p)<= 180) return (h1p+h2p)/2.0;
else if((abs(h1p-h2p) > 180) && ((h1p+h2p) < 360)) return (h1p+h2p+360)/2.0;
else if((abs(h1p-h2p) > 180) && ((h1p+h2p) >= 360)) return (h1p+h2p-360)/2.0;
else throw(new Error());
}
var a_hp = a_hp_f(C1,C2,h1p,h2p); //(14)
var T = 1-0.17*cos(radians(a_hp-30))+0.24*cos(radians(2*a_hp))+
0.32*cos(radians(3*a_hp+6))-0.20*cos(radians(4*a_hp-63)); //(15)
var d_ro = 30 * exp(-(pow((a_hp-275)/25,2))); //(16)
var RC = sqrt((pow(a_Cp, 7.0)) / (pow(a_Cp, 7.0) + pow(25.0, 7.0)));//(17)
var SL = 1 + ((0.015 * pow(a_L - 50, 2)) /
sqrt(20 + pow(a_L - 50, 2.0)));//(18)
var SC = 1 + 0.045 * a_Cp;//(19)
var SH = 1 + 0.015 * a_Cp * T;//(20)
var RT = -2 * RC * sin(radians(2 * d_ro));//(21)
var dE = sqrt(pow(dLp /(SL * kL), 2) + pow(dCp /(SC * kC), 2) +
pow(dHp /(SH * kH), 2) + RT * (dCp /(SC * kC)) *
(dHp / (SH * kH))); //(22)
return dE;
}
/**
* INTERNAL FUNCTIONS
*/
function degrees(n) { return n*(180/PI); }
function radians(n) { return n*(PI/180); }
// Local Variables:
// allout-layout: t
// js-indent-level: 2
// End:
},{}],31:[function(require,module,exports){
'use strict';
var diff = require(30);
var convert = require(29);
var palette = require(32);
var color = module.exports = {};
color.diff = diff.ciede2000;
color.rgb_to_lab = convert.rgb_to_lab;
color.map_palette = palette.map_palette;
color.palette_map_key = palette.palette_map_key;
color.closest = function(target, relative) {
var key = color.palette_map_key(target);
var result = color.map_palette([target], relative, 'closest');
return result[key];
};
color.furthest = function(target, relative) {
var key = color.palette_map_key(target);
var result = color.map_palette([target], relative, 'furthest');
return result[key];
};
},{"29":29,"30":30,"32":32}],32:[function(require,module,exports){
/**
* @author Markus Ekholm
* @copyright 2012-2015 (c) Markus Ekholm <markus at botten dot org >
* @license Copyright (c) 2012-2015, Markus Ekholm
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the <organization> nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL MARKUS EKHOLM BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* EXPORTS
*/
exports.map_palette = map_palette;
exports.palette_map_key = palette_map_key;
/**
* IMPORTS
*/
var color_diff = require(30);
var color_convert = require(29);
/**
* API FUNCTIONS
*/
/**
* Returns the hash key used for a {rgbcolor} in a {palettemap}
* @param {rgbcolor} c should have fields R,G,B
* @return {string}
*/
function palette_map_key(c)
{
return "R" + c.R + "B" + c.B + "G" + c.G;
}
/**
* Returns a mapping from each color in a to the closest color in b
* @param [{rgbcolor}] a each element should have fields R,G,B
* @param [{rgbcolor}] b each element should have fields R,G,B
* @param 'type' should be the string 'closest' or 'furthest'
* @return {palettemap}
*/
function map_palette(a, b, type)
{
var c = {};
type = type || 'closest';
for (var idx1 = 0; idx1 < a.length; idx1 += 1){
var color1 = a[idx1];
var best_color = undefined;
var best_color_diff = undefined;
for (var idx2 = 0; idx2 < b.length; idx2 += 1)
{
var color2 = b[idx2];
var current_color_diff = diff(color1,color2);
if((best_color == undefined) || ((type === 'closest') && (current_color_diff < best_color_diff)))
{
best_color = color2;
best_color_diff = current_color_diff;
continue;
}
if((type === 'furthest') && (current_color_diff > best_color_diff))
{
best_color = color2;
best_color_diff = current_color_diff;
continue;
}
}
c[palette_map_key(color1)] = best_color;
}
return c;
}
/**
* INTERNAL FUNCTIONS
*/
function diff(c1,c2)
{
c1 = color_convert.rgb_to_lab(c1);
c2 = color_convert.rgb_to_lab(c2);
return color_diff.ciede2000(c1,c2);
}
// Local Variables:
// allout-layout: t
// js-indent-level: 2
// End:
},{"29":29,"30":30}],33:[function(require,module,exports){
'use strict';
var repeating = require(54);
// detect either spaces or tabs but not both to properly handle tabs
// for indentation and spaces for alignment
var INDENT_RE = /^(?:( )+|\t+)/;
function getMostUsed(indents) {
var result = 0;
var maxUsed = 0;
var maxWeight = 0;
for (var n in indents) {
var indent = indents[n];
var u = indent[0];
var w = indent[1];
if (u > maxUsed || u === maxUsed && w > maxWeight) {
maxUsed = u;
maxWeight = w;
result = +n;
}
}
return result;
}
module.exports = function (str) {
if (typeof str !== 'string') {
throw new TypeError('Expected a string');
}
// used to see if tabs or spaces are the most used
var tabs = 0;
var spaces = 0;
// remember the size of previous line's indentation
var prev = 0;
// remember how many indents/unindents as occurred for a given size
// and how much lines follow a given indentation
//
// indents = {
// 3: [1, 0],
// 4: [1, 5],
// 5: [1, 0],
// 12: [1, 0],
// }
var indents = {};
// pointer to the array of last used indent
var current;
// whether the last action was an indent (opposed to an unindent)
var isIndent;
str.split(/\n/g).forEach(function (line) {
if (!line) {
// ignore empty lines
return;
}
var indent;
var matches = line.match(INDENT_RE);
if (!matches) {
indent = 0;
} else {
indent = matches[0].length;
if (matches[1]) {
spaces++;
} else {
tabs++;
}
}
var diff = indent - prev;
prev = indent;
if (diff) {
// an indent or unindent has been detected
isIndent = diff > 0;
current = indents[isIndent ? diff : -diff];
if (current) {
current[0]++;
} else {
current = indents[diff] = [1, 0];
}
} else if (current) {
// if the last action was an indent, increment the weight
current[1] += +isIndent;
}
});
var amount = getMostUsed(indents);
var type;
var actual;
if (!amount) {
type = null;
actual = '';
} else if (spaces >= tabs) {
type = 'space';
actual = repeating(' ', amount);
} else {
type = 'tab';
actual = repeating('\t', amount);
}
return {
amount: amount,
type: type,
indent: actual
};
};
},{"54":54}],34:[function(require,module,exports){
/* See LICENSE file for terms of use */
/*
* Text diff implementation.
*
* This library supports the following APIS:
* JsDiff.diffChars: Character by character diff
* JsDiff.diffWords: Word (as defined by \b regex) diff which ignores whitespace
* JsDiff.diffLines: Line based diff
*
* JsDiff.diffCss: Diff targeted at CSS content
*
* These methods are based on the implementation proposed in
* "An O(ND) Difference Algorithm and its Variations" (Myers, 1986).
* http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.6927
*/
(function(global, undefined) {
var JsDiff = (function() {
/*jshint maxparams: 5*/
function map(arr, mapper, that) {
if (Array.prototype.map) {
return Array.prototype.map.call(arr, mapper, that);
}
var other = new Array(arr.length);
for (var i = 0, n = arr.length; i < n; i++) {
other[i] = mapper.call(that, arr[i], i, arr);
}
return other;
}
function clonePath(path) {
return { newPos: path.newPos, components: path.components.slice(0) };
}
function removeEmpty(array) {
var ret = [];
for (var i = 0; i < array.length; i++) {
if (array[i]) {
ret.push(array[i]);
}
}
return ret;
}
function escapeHTML(s) {
var n = s;
n = n.replace(/&/g, '&');
n = n.replace(/</g, '<');
n = n.replace(/>/g, '>');
n = n.replace(/"/g, '"');
return n;
}
var Diff = function(ignoreWhitespace) {
this.ignoreWhitespace = ignoreWhitespace;
};
Diff.prototype = {
diff: function(oldString, newString) {
// Handle the identity case (this is due to unrolling editLength == 0
if (newString === oldString) {
return [{ value: newString }];
}
if (!newString) {
return [{ value: oldString, removed: true }];
}
if (!oldString) {
return [{ value: newString, added: true }];
}
newString = this.tokenize(newString);
oldString = this.tokenize(oldString);
var newLen = newString.length, oldLen = oldString.length;
var maxEditLength = newLen + oldLen;
var bestPath = [{ newPos: -1, components: [] }];
// Seed editLength = 0
var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0);
if (bestPath[0].newPos+1 >= newLen && oldPos+1 >= oldLen) {
return bestPath[0].components;
}
for (var editLength = 1; editLength <= maxEditLength; editLength++) {
for (var diagonalPath = -1*editLength; diagonalPath <= editLength; diagonalPath+=2) {
var basePath;
var addPath = bestPath[diagonalPath-1],
removePath = bestPath[diagonalPath+1];
oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
if (addPath) {
// No one else is going to attempt to use this value, clear it
bestPath[diagonalPath-1] = undefined;
}
var canAdd = addPath && addPath.newPos+1 < newLen;
var canRemove = removePath && 0 <= oldPos && oldPos < oldLen;
if (!canAdd && !canRemove) {
bestPath[diagonalPath] = undefined;
continue;
}
// Select the diagonal that we want to branch from. We select the prior
// path whose position in the new string is the farthest from the origin
// and does not pass the bounds of the diff graph
if (!canAdd || (canRemove && addPath.newPos < removePath.newPos)) {
basePath = clonePath(removePath);
this.pushComponent(basePath.components, oldString[oldPos], undefined, true);
} else {
basePath = clonePath(addPath);
basePath.newPos++;
this.pushComponent(basePath.components, newString[basePath.newPos], true, undefined);
}
var oldPos = this.extractCommon(basePath, newString, oldString, diagonalPath);
if (basePath.newPos+1 >= newLen && oldPos+1 >= oldLen) {
return basePath.components;
} else {
bestPath[diagonalPath] = basePath;
}
}
}
},
pushComponent: function(components, value, added, removed) {
var last = components[components.length-1];
if (last && last.added === added && last.removed === removed) {
// We need to clone here as the component clone operation is just
// as shallow array clone
components[components.length-1] =
{value: this.join(last.value, value), added: added, removed: removed };
} else {
components.push({value: value, added: added, removed: removed });
}
},
extractCommon: function(basePath, newString, oldString, diagonalPath) {
var newLen = newString.length,
oldLen = oldString.length,
newPos = basePath.newPos,
oldPos = newPos - diagonalPath;
while (newPos+1 < newLen && oldPos+1 < oldLen && this.equals(newString[newPos+1], oldString[oldPos+1])) {
newPos++;
oldPos++;
this.pushComponent(basePath.components, newString[newPos], undefined, undefined);
}
basePath.newPos = newPos;
return oldPos;
},
equals: function(left, right) {
var reWhitespace = /\S/;
if (this.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right)) {
return true;
} else {
return left === right;
}
},
join: function(left, right) {
return left + right;
},
tokenize: function(value) {
return value;
}
};
var CharDiff = new Diff();
var WordDiff = new Diff(true);
var WordWithSpaceDiff = new Diff();
WordDiff.tokenize = WordWithSpaceDiff.tokenize = function(value) {
return removeEmpty(value.split(/(\s+|\b)/));
};
var CssDiff = new Diff(true);
CssDiff.tokenize = function(value) {
return removeEmpty(value.split(/([{}:;,]|\s+)/));
};
var LineDiff = new Diff();
LineDiff.tokenize = function(value) {
var retLines = [],
lines = value.split(/^/m);
for(var i = 0; i < lines.length; i++) {
var line = lines[i],
lastLine = lines[i - 1];
// Merge lines that may contain windows new lines
if (line == '\n' && lastLine && lastLine[lastLine.length - 1] === '\r') {
retLines[retLines.length - 1] += '\n';
} else if (line) {
retLines.push(line);
}
}
return retLines;
};
return {
Diff: Diff,
diffChars: function(oldStr, newStr) { return CharDiff.diff(oldStr, newStr); },
diffWords: function(oldStr, newStr) { return WordDiff.diff(oldStr, newStr); },
diffWordsWithSpace: function(oldStr, newStr) { return WordWithSpaceDiff.diff(oldStr, newStr); },
diffLines: function(oldStr, newStr) { return LineDiff.diff(oldStr, newStr); },
diffCss: function(oldStr, newStr) { return CssDiff.diff(oldStr, newStr); },
createPatch: function(fileName, oldStr, newStr, oldHeader, newHeader) {
var ret = [];
ret.push('Index: ' + fileName);
ret.push('===================================================================');
ret.push('--- ' + fileName + (typeof oldHeader === 'undefined' ? '' : '\t' + oldHeader));
ret.push('+++ ' + fileName + (typeof newHeader === 'undefined' ? '' : '\t' + newHeader));
var diff = LineDiff.diff(oldStr, newStr);
if (!diff[diff.length-1].value) {
diff.pop(); // Remove trailing newline add
}
diff.push({value: '', lines: []}); // Append an empty value to make cleanup easier
function contextLines(lines) {
return map(lines, function(entry) { return ' ' + entry; });
}
function eofNL(curRange, i, current) {
var last = diff[diff.length-2],
isLast = i === diff.length-2,
isLastOfType = i === diff.length-3 && (current.added !== last.added || current.removed !== last.removed);
// Figure out if this is the last line for the given file and missing NL
if (!/\n$/.test(current.value) && (isLast || isLastOfType)) {
curRange.push('\\ No newline at end of file');
}
}
var oldRangeStart = 0, newRangeStart = 0, curRange = [],
oldLine = 1, newLine = 1;
for (var i = 0; i < diff.length; i++) {
var current = diff[i],
lines = current.lines || current.value.replace(/\n$/, '').split('\n');
current.lines = lines;
if (current.added || current.removed) {
if (!oldRangeStart) {
var prev = diff[i-1];
oldRangeStart = oldLine;
newRangeStart = newLine;
if (prev) {
curRange = contextLines(prev.lines.slice(-4));
oldRangeStart -= curRange.length;
newRangeStart -= curRange.length;
}
}
curRange.push.apply(curRange, map(lines, function(entry) { return (current.added?'+':'-') + entry; }));
eofNL(curRange, i, current);
if (current.added) {
newLine += lines.length;
} else {
oldLine += lines.length;
}
} else {
if (oldRangeStart) {
// Close out any changes that have been output (or join overlapping)
if (lines.length <= 8 && i < diff.length-2) {
// Overlapping
curRange.push.apply(curRange, contextLines(lines));
} else {
// end the range and output
var contextSize = Math.min(lines.length, 4);
ret.push(
'@@ -' + oldRangeStart + ',' + (oldLine-oldRangeStart+contextSize)
+ ' +' + newRangeStart + ',' + (newLine-newRangeStart+contextSize)
+ ' @@');
ret.push.apply(ret, curRange);
ret.push.apply(ret, contextLines(lines.slice(0, contextSize)));
if (lines.length <= 4) {
eofNL(ret, i, current);
}
oldRangeStart = 0; newRangeStart = 0; curRange = [];
}
}
oldLine += lines.length;
newLine += lines.length;
}
}
return ret.join('\n') + '\n';
},
applyPatch: function(oldStr, uniDiff) {
var diffstr = uniDiff.split('\n');
var diff = [];
var remEOFNL = false,
addEOFNL = false;
for (var i = (diffstr[0][0]==='I'?4:0); i < diffstr.length; i++) {
if(diffstr[i][0] === '@') {
var meh = diffstr[i].split(/@@ -(\d+),(\d+) \+(\d+),(\d+) @@/);
diff.unshift({
start:meh[3],
oldlength:meh[2],
oldlines:[],
newlength:meh[4],
newlines:[]
});
} else if(diffstr[i][0] === '+') {
diff[0].newlines.push(diffstr[i].substr(1));
} else if(diffstr[i][0] === '-') {
diff[0].oldlines.push(diffstr[i].substr(1));
} else if(diffstr[i][0] === ' ') {
diff[0].newlines.push(diffstr[i].substr(1));
diff[0].oldlines.push(diffstr[i].substr(1));
} else if(diffstr[i][0] === '\\') {
if (diffstr[i-1][0] === '+') {
remEOFNL = true;
} else if(diffstr[i-1][0] === '-') {
addEOFNL = true;
}
}
}
var str = oldStr.split('\n');
for (var i = diff.length - 1; i >= 0; i--) {
var d = diff[i];
for (var j = 0; j < d.oldlength; j++) {
if(str[d.start-1+j] !== d.oldlines[j]) {
return false;
}
}
Array.prototype.splice.apply(str,[d.start-1,+d.oldlength].concat(d.newlines));
}
if (remEOFNL) {
while (!str[str.length-1]) {
str.pop();
}
} else if (addEOFNL) {
str.push('');
}
return str.join('\n');
},
convertChangesToXML: function(changes){
var ret = [];
for ( var i = 0; i < changes.length; i++) {
var change = changes[i];
if (change.added) {
ret.push('<ins>');
} else if (change.removed) {
ret.push('<del>');
}
ret.push(escapeHTML(change.value));
if (change.added) {
ret.push('</ins>');
} else if (change.removed) {
ret.push('</del>');
}
}
return ret.join('');
},
// See: http://code.google.com/p/google-diff-match-patch/wiki/API
convertChangesToDMP: function(changes){
var ret = [], change;
for ( var i = 0; i < changes.length; i++) {
change = changes[i];
ret.push([(change.added ? 1 : change.removed ? -1 : 0), change.value]);
}
return ret;
}
};
})();
if (typeof module !== 'undefined') {
module.exports = JsDiff;
}
else if (typeof define === 'function') {
define([], function() { return JsDiff; });
}
else if (typeof global.JsDiff === 'undefined') {
global.JsDiff = JsDiff;
}
})(this);
},{}],35:[function(require,module,exports){
module.exports = function (a, b) {
var c = b.start - a.start;
if (c !== 0) { return c; }
return (a.end - a.start) - (b.end - b.start);
};
},{}],36:[function(require,module,exports){
var intersectsWithSome = require(37).intersectsWithSome;
var byDescStartAndLength = require(35);
module.exports = function greedyIntervalPacker(intervals, options) {
options = options || {};
if (!Array.isArray(intervals)) {
throw new Error('The interval packer requires an array of objects with start and end properties.');
}
if (intervals.length === 0) {
return [];
}
intervals.forEach(function (interval) {
if (
typeof interval !== 'object' ||
typeof interval.start !== 'number' ||
typeof interval.end !== 'number' ||
interval.end <= interval.start
) {
throw new Error('Intervals must be objects with integer properties start and end where start < end.');
}
});
intervals = [].concat(intervals).sort(byDescStartAndLength);
var currentPartition;
var partitions = [];
var currentPartitionEnd = -Infinity;
while (intervals.length > 0) {
var interval = intervals.pop();
if (currentPartitionEnd <= interval.start) {
currentPartition = [[]];
partitions.push(currentPartition);
}
var i = 0;
while (
i < currentPartition.length &&
intersectsWithSome(currentPartition[i], interval)
) {
i += 1;
}
(currentPartition[i] = currentPartition[i] || []).push(interval);
currentPartitionEnd = Math.max(currentPartitionEnd, interval.end);
}
if (!options.groupPartitions) {
return partitions.reduce(function (result, partition) {
partition.forEach(function (partitionGroup, i) {
result[i] = result[i] || [];
Array.prototype.push.apply(result[i], partitionGroup);
return result;
});
return result;
}, []);
} else {
return partitions;
}
};
},{"35":35,"37":37}],37:[function(require,module,exports){
var intersection = {
intersects: function intersects(x, y) {
return (x.start < y.end && y.start < x.end) || x.start === y.start;
},
intersectsWithSome: function intersectsWithSome(intervals, interval) {
function intersectWithInterval(other) {
return intersection.intersects(interval, other);
}
return intervals.some(intersectWithInterval);
}
};
module.exports = intersection;
},{}],38:[function(require,module,exports){
exports.read = function (buffer, offset, isLE, mLen, nBytes) {
var e, m
var eLen = nBytes * 8 - mLen - 1
var eMax = (1 << eLen) - 1
var eBias = eMax >> 1
var nBits = -7
var i = isLE ? (nBytes - 1) : 0
var d = isLE ? -1 : 1
var s = buffer[offset + i]
i += d
e = s & ((1 << (-nBits)) - 1)
s >>= (-nBits)
nBits += eLen
for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
m = e & ((1 << (-nBits)) - 1)
e >>= (-nBits)
nBits += mLen
for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
if (e === 0) {
e = 1 - eBias
} else if (e === eMax) {
return m ? NaN : ((s ? -1 : 1) * Infinity)
} else {
m = m + Math.pow(2, mLen)
e = e - eBias
}
return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
}
exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
var e, m, c
var eLen = nBytes * 8 - mLen - 1
var eMax = (1 << eLen) - 1
var eBias = eMax >> 1
var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
var i = isLE ? 0 : (nBytes - 1)
var d = isLE ? 1 : -1
var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
value = Math.abs(value)
if (isNaN(value) || value === Infinity) {
m = isNaN(value) ? 1 : 0
e = eMax
} else {
e = Math.floor(Math.log(value) / Math.LN2)
if (value * (c = Math.pow(2, -e)) < 1) {
e--
c *= 2
}
if (e + eBias >= 1) {
value += rt / c
} else {
value += rt * Math.pow(2, 1 - eBias)
}
if (value * c >= 2) {
e++
c /= 2
}
if (e + eBias >= eMax) {
m = 0
e = eMax
} else if (e + eBias >= 1) {
m = (value * c - 1) * Math.pow(2, mLen)
e = e + eBias
} else {
m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
e = 0
}
}
for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
e = (e << mLen) | m
eLen += mLen
for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
buffer[offset + i - d] |= s * 128
}
},{}],39:[function(require,module,exports){
'use strict';
var numberIsNan = require(52);
module.exports = Number.isFinite || function (val) {
return !(typeof val !== 'number' || numberIsNan(val) || val === Infinity || val === -Infinity);
};
},{"52":52}],40:[function(require,module,exports){
/* eslint-disable no-nested-ternary */
'use strict';
var arr = [];
var charCodeCache = [];
module.exports = function (a, b) {
if (a === b) {
return 0;
}
var aLen = a.length;
var bLen = b.length;
if (aLen === 0) {
return bLen;
}
if (bLen === 0) {
return aLen;
}
var bCharCode;
var ret;
var tmp;
var tmp2;
var i = 0;
var j = 0;
while (i < aLen) {
charCodeCache[i] = a.charCodeAt(i);
arr[i] = ++i;
}
while (j < bLen) {
bCharCode = b.charCodeAt(j);
tmp = j++;
ret = j;
for (i = 0; i < aLen; i++) {
tmp2 = bCharCode === charCodeCache[i] ? tmp : tmp + 1;
tmp = arr[i];
ret = arr[i] = tmp > ret ? tmp2 > ret ? ret + 1 : tmp2 : tmp2 > tmp ? tmp + 1 : tmp2;
}
}
return ret;
};
},{}],41:[function(require,module,exports){
var utils = require(51);
var TextSerializer = require(45);
var colorDiff = require(31);
var rgbRegexp = require(49);
var themeMapper = require(50);
var cacheSize = 0;
var maxColorCacheSize = 1024;
var ansiStyles = utils.extend({}, require(22));
Object.keys(ansiStyles).forEach(function (styleName) {
ansiStyles[styleName.toLowerCase()] = ansiStyles[styleName];
});
function AnsiSerializer(theme) {
this.theme = theme;
}
AnsiSerializer.prototype = new TextSerializer();
AnsiSerializer.prototype.format = 'ansi';
var colorPalettes = {
16: {
'#000000': 'black',
'#ff0000': 'red',
'#00ff00': 'green',
'#ffff00': 'yellow',
'#0000ff': 'blue',
'#ff00ff': 'magenta',
'#00ffff': 'cyan',
'#ffffff': 'white',
'#808080': 'gray'
},
256: {}
};
var diffPalettes = {};
function convertColorToObject(color) {
if (color.length < 6) {
// Allow CSS shorthand
color = color.replace(/^#?([0-9a-f])([0-9a-f])([0-9a-f])$/i, '$1$1$2$2$3$3');
}
// Split color into red, green, and blue components
var hexMatch = color.match(/^#?([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])$/i);
if (hexMatch) {
return {
R: parseInt(hexMatch[1], 16),
G: parseInt(hexMatch[2], 16),
B: parseInt(hexMatch[3], 16)
};
}
}
function toHexColor(colorObject) {
var hexString = (Math.round(colorObject.R) * 0x10000 + Math.round(colorObject.G) * 0x100 + Math.round(colorObject.B)).toString(16);
return '#' + ('00000'.substr(0, 6 - hexString.length)) + hexString;
}
function firstUp(text) {
return text.substring(0, 1).toUpperCase() + text.substring(1);
}
diffPalettes[16] = Object.keys(colorPalettes[16]).map(convertColorToObject);
diffPalettes['bg16'] = Object.keys(colorPalettes[16]).filter(function (color) {
return color !== "#808080";
}).map(convertColorToObject);
diffPalettes[256] = [].concat(diffPalettes[16]);
var nextAnsiColorNumber = 16;
function registerNext256PaletteEntry(obj) {
diffPalettes[256].push(obj);
colorPalettes[256][toHexColor(obj)] = nextAnsiColorNumber;
nextAnsiColorNumber += 1;
}
for (var r = 0 ; r < 6 ; r += 1) {
for (var g = 0 ; g < 6 ; g += 1) {
for (var b = 0 ; b < 6 ; b += 1) {
registerNext256PaletteEntry({
R: Math.round(r * 256 / 6),
G: Math.round(g * 256 / 6),
B: Math.round(b * 256 / 6)
});
}
}
}
[
0x08, 0x12, 0x1c, 0x26, 0x30, 0x3a, 0x44, 0x4e, 0x58, 0x60, 0x66, 0x76,
0x80, 0x8a, 0x94, 0x9e, 0xa8, 0xb2, 0xbc, 0xc6, 0xd0, 0xda, 0xe4, 0xee
].forEach(function (value) {
registerNext256PaletteEntry({R: value, G: value, B: value});
});
AnsiSerializer.prototype.text = function (options) {
var content = String(options.content);
if (content === '') {
return '';
}
var styles = themeMapper(this.theme, options.styles);
if (styles.length > 0) {
for (var i = styles.length -1; i >= 0; i -= 1) {
var styleName = styles[i];
if (ansiStyles[styleName]) {
content = ansiStyles[styleName].open + content + ansiStyles[styleName].close;
} else if (rgbRegexp.test(styleName)) {
var originalStyleName = styleName;
var isBackgroundColor = styleName.substring(0, 2) === 'bg';
var colorName = isBackgroundColor ? styleName.substring(2) : styleName;
var color16Hex = toHexColor(colorDiff.closest(convertColorToObject(colorName),
diffPalettes[isBackgroundColor ? 'bg16' : 16]));
var closestColor16 = colorPalettes[16][color16Hex];
var color256Hex = toHexColor(colorDiff.closest(convertColorToObject(colorName), diffPalettes[256]));
var closest256ColorIndex = colorPalettes[256][color256Hex];
if (isBackgroundColor) {
styleName = 'bg' + firstUp(closestColor16);
} else {
styleName = closestColor16;
}
var open = ansiStyles[styleName].open;
var close = ansiStyles[styleName].close;
if (color16Hex !== color256Hex) {
open += '\x1b[' + (isBackgroundColor ? 48 : 38) + ';5;' + closest256ColorIndex + 'm';
}
if (cacheSize < maxColorCacheSize) {
ansiStyles[originalStyleName] = {open: open, close: close};
cacheSize += 1;
}
content = open + content + close;
}
}
}
return content;
};
module.exports = AnsiSerializer;
},{"22":22,"31":31,"45":45,"49":49,"50":50,"51":51}],42:[function(require,module,exports){
var cssStyles = require(46);
var flattenBlocksInLines = require(48);
var rgbRegexp = require(49);
var themeMapper = require(50);
function ColoredConsoleSerializer(theme) {
this.theme = theme;
}
ColoredConsoleSerializer.prototype.format = 'coloredConsole';
ColoredConsoleSerializer.prototype.serialize = function (lines) {
var formatString = '';
var styleStrings = [];
this.serializeLines(flattenBlocksInLines(lines)).forEach(function (entry) {
if (entry) {
formatString += entry[0];
if (entry.length > 1) {
styleStrings.push(entry[1]);
}
}
});
return [formatString].concat(styleStrings);
};
ColoredConsoleSerializer.prototype.serializeLines = function (lines) {
var result = [];
lines.forEach(function (line, i) {
if (i > 0) {
result.push(['%c\n ', '']);
}
Array.prototype.push.apply(result, this.serializeLine(line));
}, this);
return result;
};
ColoredConsoleSerializer.prototype.serializeLine = function (line) {
var result = [];
line.forEach(function (outputEntry) {
if (this[outputEntry.style]) {
result.push(this[outputEntry.style](outputEntry.args));
}
}, this);
return result;
};
ColoredConsoleSerializer.prototype.block = function (content) {
return this.serializeLines(content);
};
ColoredConsoleSerializer.prototype.text = function (options) {
var content = String(options.content);
if (content === '') {
return '';
}
var styles = themeMapper(this.theme, options.styles);
var result = ['%c' + content.replace(/%/g, '%%')];
var styleProperties = [];
if (styles.length > 0) {
for (var i = 0; i < styles.length; i += 1) {
var styleName = styles[i];
if (rgbRegexp.test(styleName)) {
if (styleName.substring(0, 2) === 'bg') {
styleProperties.push('background-color: ' + styleName.substring(2));
} else {
styleProperties.push('color: ' + styleName);
}
} else if (cssStyles[styleName]) {
styleProperties.push(cssStyles[styleName]);
}
}
}
result.push(styleProperties.join('; '));
return result;
};
ColoredConsoleSerializer.prototype.raw = function (options) {
return String(options.content(this));
};
module.exports = ColoredConsoleSerializer;
},{"46":46,"48":48,"49":49,"50":50}],43:[function(require,module,exports){
var cssStyles = require(46);
var rgbRegexp = require(49);
var themeMapper = require(50);
function HtmlSerializer(theme) {
this.theme = theme;
}
HtmlSerializer.prototype.format = 'html';
HtmlSerializer.prototype.serialize = function (lines) {
return '<div style="font-family: monospace; white-space: nowrap">' + this.serializeLines(lines) + '</div>';
};
HtmlSerializer.prototype.serializeLines = function (lines) {
return lines.map(function (line) {
return '<div>' + (this.serializeLine(line).join('') || ' ') + '</div>';
}, this).join('');
};
HtmlSerializer.prototype.serializeLine = function (line) {
return line.map(function (outputEntry) {
return this[outputEntry.style] ?
this[outputEntry.style](outputEntry.args) :
'';
}, this);
};
HtmlSerializer.prototype.block = function (content) {
return '<div style="display: inline-block; vertical-align: top">' +
this.serializeLines(content) +
'</div>';
};
HtmlSerializer.prototype.text = function (options) {
var content = String(options.content);
if (content === '') {
return '';
}
content = content
.replace(/&/g, '&')
.replace(/ /g, ' ')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"');
var styles = themeMapper(this.theme, options.styles);
if (styles.length > 0) {
var styleProperties = [];
for (var j = 0; j < styles.length; j += 1) {
var styleName = styles[j];
if (rgbRegexp.test(styleName)) {
if (styleName.substring(0, 2) === 'bg') {
styleProperties.push('background-color: ' + styleName.substring(2));
} else {
styleProperties.push('color: ' + styleName);
}
} else if (cssStyles[styleName]) {
styleProperties.push(cssStyles[styleName]);
}
}
if (styleProperties.length > 0) {
content = '<span style="' + styleProperties.join('; ') + '">' + content + '</span>';
}
}
return content;
};
HtmlSerializer.prototype.raw = function (options) {
return String(options.content(this));
};
module.exports = HtmlSerializer;
},{"46":46,"49":49,"50":50}],44:[function(require,module,exports){
(function (process){
/*global window*/
var utils = require(51);
var extend = utils.extend;
var duplicateText = require(47);
var rgbRegexp = require(49);
var cssStyles = require(46);
var builtInStyleNames = [
'bold', 'dim', 'italic', 'underline', 'inverse', 'hidden',
'strikeThrough', 'black', 'red', 'green', 'yellow', 'blue',
'magenta', 'cyan', 'white', 'gray', 'bgBlack', 'bgRed',
'bgGreen', 'bgYellow', 'bgBlue', 'bgMagenta', 'bgCyan',
'bgWhite'
];
function MagicPen(options) {
if (!(this instanceof MagicPen)) {
return new MagicPen(options);
}
options = options || {};
if (typeof options === "string") {
options = {format: options };
}
var indentationWidth = 'indentationWidth' in options ?
options.indentationWidth : 2;
this.indentationWidth = Math.max(indentationWidth, 0);
this.indentationLevel = 0;
this.output = [[]];
this.styles = Object.create(null);
this.installedPlugins = [];
// Ready to be cloned individually:
this._themes = {};
Object.keys(MagicPen.serializers).forEach(function (serializerName) {
this._themes[serializerName] = { styles: {} };
}, this);
this.preferredWidth = (!process.browser && process.stdout.columns) || 80;
if (options.format) {
this.format = options.format;
}
}
if (typeof exports === 'object' && typeof exports.nodeName !== 'string' && require(55)) {
MagicPen.defaultFormat = 'ansi'; // colored console
} else if (typeof window !== 'undefined' && typeof window.navigator !== 'undefined') {
if (window._phantom || window.mochaPhantomJS || (window.__karma__ && window.__karma__.config.captureConsole)) {
MagicPen.defaultFormat = 'ansi'; // colored console
} else {
MagicPen.defaultFormat = 'html'; // Browser
}
} else {
MagicPen.defaultFormat = 'text'; // Plain text
}
MagicPen.prototype.newline = MagicPen.prototype.nl = function (count) {
if (typeof count === 'undefined') {
count = 1;
}
if (count === 0) {
return this;
}
for (var i = 0; i < count; i += 1) {
this.output.push([]);
}
return this;
};
MagicPen.serializers = {};
[
require(45),
require(43),
require(41),
require(42)
].forEach(function (serializer) {
MagicPen.serializers[serializer.prototype.format] = serializer;
});
function hasSameTextStyling(a, b) {
if (!a || !b || a.style !== 'text' || b.style !== 'text') {
return false;
}
return utils.arrayEquals(a.args.styles, b.args.styles);
}
function normalizeLine(line) {
if (line.length === 0) {
return line;
}
var result = [line[0]];
for (var i = 1; i < line.length; i += 1) {
var lastEntry = result[result.length - 1];
var entry = line[i];
if (entry.style === 'text' && entry.args.content === '') {
continue;
}
if (hasSameTextStyling(lastEntry, entry)) {
result[result.length - 1] = {
style: lastEntry.style,
args: {
content: lastEntry.args.content + entry.args.content,
styles: lastEntry.args.styles
}
};
} else {
result.push(entry);
}
}
return result;
}
MagicPen.prototype.write = function (options) {
if (this.styles[options.style]) {
this.styles[options.style].apply(this, options.args);
return this;
}
var lastLine = this.output[this.output.length - 1];
var lastEntry = lastLine[lastLine.length - 1];
if (hasSameTextStyling(lastEntry, options)) {
lastLine[lastLine.length - 1] = {
style: lastEntry.style,
args: {
content: lastEntry.args.content + options.args.content,
styles: lastEntry.args.styles
}
};
} else {
lastLine.push(options);
}
return this;
};
MagicPen.prototype.indentLines = function () {
this.indentationLevel += 1;
return this;
};
MagicPen.prototype.indent = MagicPen.prototype.i = function () {
for (var i = 0; i < this.indentationLevel; i += 1) {
this.space(this.indentationWidth);
}
return this;
};
MagicPen.prototype.outdentLines = function () {
this.indentationLevel = Math.max(0, this.indentationLevel - 1);
return this;
};
MagicPen.prototype.addStyle = function (style, handler, allowRedefinition) {
if (this[style] === false || ((this.hasOwnProperty(style) || MagicPen.prototype[style]) && !Object.prototype.hasOwnProperty.call(this.styles, style) && builtInStyleNames.indexOf(style) === -1)) {
throw new Error('"' + style + '" style cannot be defined, it clashes with a built-in attribute');
}
// Refuse to redefine a built-in style or a style already defined directly on this pen unless allowRedefinition is true:
if (this.hasOwnProperty(style) || builtInStyleNames.indexOf(style) !== -1) {
var existingType = typeof this[style];
if (existingType === 'function') {
if (!allowRedefinition) {
throw new Error('"' + style + '" style is already defined, set 3rd arg (allowRedefinition) to true to define it anyway');
}
}
}
if (this._stylesHaveNotBeenClonedYet) {
this.styles = Object.create(this.styles);
this._stylesHaveNotBeenClonedYet = false;
}
this.styles[style] = handler;
this[style] = function () {
handler.apply(this, arguments);
return this;
};
return this;
};
MagicPen.prototype.toString = function (format) {
if (format && this.format && format !== this.format) {
throw new Error('A pen with format: ' + this.format + ' cannot be serialized to: ' + format);
}
format = this.format || format || 'text';
if (format === 'auto') {
format = MagicPen.defaultFormat;
}
var theme = this._themes[format] || {};
var serializer = new MagicPen.serializers[format](theme);
return serializer.serialize(this.output);
};
MagicPen.prototype.text = function () {
var content = arguments[0];
if (content === '') {
return this;
}
var styles = new Array(arguments.length - 1);
for (var i = 1; i < arguments.length; i += 1) {
styles[i - 1] = arguments[i];
}
content = String(content);
if (content.indexOf('\n') !== -1) {
var lines = content.split(/\n/);
lines.forEach(function (lineContent, index) {
if (lineContent.length) {
this.write({
style: 'text',
args: { content: lineContent, styles: styles }
});
}
if (index < lines.length - 1) {
this.nl();
}
}, this);
return this;
} else {
return this.write({
style: 'text',
args: { content: content, styles: styles }
});
}
};
MagicPen.prototype.removeFormatting = function () {
var result = this.clone();
this.output.forEach(function (line, index) {
result.output[index] = normalizeLine(line.map(function (outputEntry) {
return outputEntry.style === 'text' ?
{ style: 'text', args: { content: outputEntry.args.content, styles: [] } } :
outputEntry;
}));
});
result.indentationLevel = this.indentationLevel;
return result;
};
MagicPen.prototype.getContentFromArguments = function (args) {
var clone;
if (args[0].isMagicPen) {
this.ensureCompatibleFormat(args[0].format);
return args[0];
} else if (typeof args[0] === 'function') {
clone = this.clone();
args[0].call(clone, clone);
return clone;
} else if (typeof args[0] === 'string' && args.length === 1) {
clone = this.clone();
clone.text(args[0]);
return clone;
} else if (typeof args[0] === 'string') {
clone = this.clone();
clone[args[0]].apply(clone, Array.prototype.slice.call(args, 1));
return clone;
} else {
throw new Error('Requires the arguments to be:\n' +
'a pen or\n' +
'a callback appending content to a pen or\n' +
'a style and arguments for that style or\n' +
'just a string.');
}
};
MagicPen.prototype.isMultiline = function () {
return this.output.length > 1 || this.size().height > 1;
};
MagicPen.prototype.isAtStartOfLine = function () {
return this.output.length === 0 || this.output[this.output.length - 1].length === 0;
};
MagicPen.prototype.isBlock = function () {
return this.output.length === 1 &&
this.output[0].length === 1 &&
this.output[0][0].style === 'block';
};
MagicPen.prototype.ensureCompatibleFormat = function (format) {
if (format && this.format && format !== this.format) {
throw new Error('This pen is only compatible with the format: ' + this.format);
}
};
MagicPen.prototype.block = function () {
var pen = this.getContentFromArguments(arguments);
var blockOutput = pen.output.map(function (line) {
return [].concat(line);
});
return this.write({ style: 'block', args: blockOutput });
};
function isRawOutput(options) {
return options &&
typeof options === 'object' &&
typeof options.width === 'number' &&
typeof options.height === 'number' && (
typeof options.content === 'function' ||
typeof options.content === 'string'
);
}
MagicPen.prototype.alt = function (options) {
var format = this.format;
if (!format) {
throw new Error('The alt method is only supported on pen where the format has already been set');
}
var outputProperty = options[format];
if (typeof outputProperty === 'undefined') {
if (options.fallback) {
return this.append(options.fallback);
} else {
// Nothing to do for this format, just NOOP:
return this;
}
}
if (typeof outputProperty === 'string' || isRawOutput(outputProperty)) {
return this.raw(outputProperty);
} else {
return this.append(outputProperty);
}
};
MagicPen.prototype.raw = function (options) {
var format = this.format;
if (!format) {
throw new Error('The alt method is only supported on pen where the format has already been set');
}
if (typeof options === 'string') {
return this.write({ style: 'raw', args: {
height: 0,
width: 0,
content: function () {
return options;
}
}});
}
if (isRawOutput(options)) {
if (typeof options.content === 'string') {
options = extend({}, options);
var content = options.content;
options.content = function () {
return content;
};
}
return this.write({ style: 'raw', args: options });
}
throw new Error('Raw ' + this.format + ' content needs to adhere to one of the following forms:\n' +
'a string of raw content\n' +
'a function returning a string of raw content or\n' +
'an object with the following form { width: <number>, height: <number>, content: <string function() {}|string> }');
};
function amend(output, pen) {
var lastLine = output[output.length - 1].slice();
var newOutput = output.slice(0, -1);
var lastEntry = lastLine[lastLine.length - 1];
if (lastEntry && lastEntry.style === 'block') {
lastLine[lastLine.length - 1] = {
style: 'block',
args: amend(lastEntry.args, pen)
};
newOutput[output.length - 1] = lastLine;
} else {
Array.prototype.push.apply(lastLine, pen.output[0]);
newOutput[output.length - 1] = normalizeLine(lastLine);
newOutput.push.apply(newOutput, pen.output.slice(1));
}
return newOutput;
}
MagicPen.prototype.amend = function () {
var pen = this.getContentFromArguments(arguments);
if (pen.isEmpty()) {
return this;
}
this.output = amend(this.output, pen);
return this;
};
MagicPen.prototype.append = function () {
var pen = this.getContentFromArguments(arguments);
if (pen.isEmpty()) {
return this;
}
var lastLine = this.output[this.output.length - 1];
Array.prototype.push.apply(lastLine, pen.output[0]);
this.output[this.output.length - 1] = normalizeLine(lastLine);
this.output.push.apply(this.output, pen.output.slice(1));
return this;
};
MagicPen.prototype.prependLinesWith = function () {
var pen = this.getContentFromArguments(arguments);
if (pen.isEmpty()) {
return this;
}
if (pen.output.length > 1) {
throw new Error('PrependLinesWith only supports a pen with single line content');
}
var height = this.size().height;
var output = this.clone();
output.block(function () {
for (var i = 0; i < height; i += 1) {
if (0 < i) {
this.nl();
}
this.append(pen);
}
});
output.block(this);
this.output = output.output;
return this;
};
MagicPen.prototype.space = MagicPen.prototype.sp = function (count) {
if (count === 0) {
return this;
}
if (typeof count === 'undefined') {
count = 1;
}
return this.text(duplicateText(' ', count));
};
builtInStyleNames.forEach(function (textStyle) {
MagicPen.prototype[textStyle] = MagicPen.prototype[textStyle.toLowerCase()] = function (content) {
return this.text(content, textStyle);
};
});
MagicPen.prototype.clone = function (format) {
if (!this.isEmpty()) {
this.ensureCompatibleFormat(format);
}
function MagicPenClone() {}
MagicPenClone.prototype = this;
var clonedPen = new MagicPenClone();
clonedPen.styles = this.styles;
clonedPen._stylesHaveNotBeenClonedYet = true;
clonedPen.indentationLevel = 0;
clonedPen.output = [[]];
clonedPen.installedPlugins = [];
clonedPen._themes = this._themes;
clonedPen._themesHaveNotBeenClonedYet = true;
clonedPen.format = format || this.format;
clonedPen.parent = this;
return clonedPen;
};
MagicPen.prototype.isMagicPen = true;
MagicPen.prototype.size = function () {
return utils.calculateSize(this.output);
};
MagicPen.prototype.use = function (plugin) {
var existingPlugin = utils.findFirst(this.installedPlugins, function (installedPlugin) {
if (installedPlugin === plugin) {
return true;
} else if (typeof plugin === 'function' && typeof installedPlugin === 'function') {
var pluginName = utils.getFunctionName(plugin);
return pluginName !== '' && pluginName === utils.getFunctionName(installedPlugin);
} else {
return installedPlugin.name === plugin.name;
}
});
if (existingPlugin) {
if (existingPlugin === plugin || (typeof plugin.version !== 'undefined' && plugin.version === existingPlugin.version)) {
// No-op
return this;
} else {
throw new Error("Another instance of the plugin '" + plugin.name + "' " +
"is already installed" +
(typeof existingPlugin.version !== 'undefined' ?
' (version ' + existingPlugin.version +
(typeof plugin.version !== 'undefined' ?
', trying to install ' + plugin.version : '') +
')' : '') +
". Please check your node_modules folder for unmet peerDependencies.");
}
}
if ((typeof plugin !== 'function' && (typeof plugin !== 'object' || typeof plugin.installInto !== 'function')) ||
(typeof plugin.name !== 'undefined' && typeof plugin.name !== 'string') ||
(typeof plugin.dependencies !== 'undefined' && !Array.isArray(plugin.dependencies))) {
throw new Error('Plugins must be functions or adhere to the following interface\n' +
'{\n' +
' name: <an optional plugin name>,\n' +
' version: <an optional semver version string>,\n' +
' dependencies: <an optional list of dependencies>,\n' +
' installInto: <a function that will update the given magicpen instance>\n' +
'}');
}
if (plugin.dependencies) {
var instance = this;
var thisAndParents = [];
do {
thisAndParents.push(instance);
instance = instance.parent;
} while (instance);
var unfulfilledDependencies = plugin.dependencies.filter(function (dependency) {
return !thisAndParents.some(function (instance) {
return instance.installedPlugins.some(function (plugin) {
return plugin.name === dependency;
});
});
});
if (unfulfilledDependencies.length === 1) {
throw new Error(plugin.name + ' requires plugin ' + unfulfilledDependencies[0]);
} else if (unfulfilledDependencies.length > 1) {
throw new Error(plugin.name + ' requires plugins ' +
unfulfilledDependencies.slice(0, -1).join(', ') +
' and ' + unfulfilledDependencies[unfulfilledDependencies.length - 1]);
}
}
this.installedPlugins.push(plugin);
if (typeof plugin === 'function') {
plugin(this);
} else {
plugin.installInto(this);
}
return this; // for chaining
};
MagicPen.prototype.installPlugin = MagicPen.prototype.use; // Legacy alias
function replaceText(output, outputArray, regexp, cb) {
var replacedOutput = output;
outputArray.forEach(function (line, i) {
if (0 < i) {
replacedOutput.nl();
}
line.forEach(function (outputEntry, j) {
if (outputEntry.style === 'block') {
return replacedOutput.output[replacedOutput.output.length - 1].push({
style: 'block',
args: replaceText(output.clone(), outputEntry.args, regexp, cb)
});
} else if (outputEntry.style !== 'text') {
return replacedOutput.output[replacedOutput.output.length - 1].push(outputEntry);
}
if (regexp.global) {
regexp.lastIndex = 0;
}
var m;
var first = true;
var lastIndex = 0;
var text = outputEntry.args.content;
var styles = outputEntry.args.styles;
while ((m = regexp.exec(text)) !== null && (regexp.global || first)) {
if (lastIndex < m.index) {
replacedOutput.text.apply(replacedOutput, [text.substring(lastIndex, m.index)].concat(styles));
}
cb.apply(replacedOutput, [styles].concat(m));
first = false;
lastIndex = m.index + m[0].length;
}
if (lastIndex === 0) {
var lastLine;
if (replacedOutput.output.length === 0) {
lastLine = replacedOutput.output[0] = [];
} else {
lastLine = replacedOutput.output[replacedOutput.output.length - 1];
}
lastLine.push(outputEntry);
} else if (lastIndex < text.length) {
replacedOutput.text.apply(replacedOutput, [text.substring(lastIndex, text.length)].concat(styles));
}
}, this);
}, this);
return replacedOutput.output.map(normalizeLine);
}
MagicPen.prototype.isEmpty = function () {
return this.output.length === 1 && this.output[0].length === 0;
};
MagicPen.prototype.replaceText = function (regexp, cb) {
if (this.isEmpty()) {
return this;
}
if (typeof regexp === 'string') {
regexp = new RegExp(utils.escapeRegExp(regexp), 'g');
}
if (typeof cb === 'string') {
var text = cb;
cb = function (styles, _) {
var args = [text].concat(styles);
this.text.apply(this, args);
};
}
if (arguments.length === 1) {
cb = regexp;
regexp = /.*/;
}
this.output = replaceText(this.clone(), this.output, regexp, cb);
return this;
};
MagicPen.prototype.theme = function (format) {
format = format || this.format;
if (!format) {
throw new Error("Could not detect which format you want to retrieve " +
"theme information for. Set the format of the pen or " +
"provide it as an argument to the theme method.");
}
return this._themes[format];
};
MagicPen.prototype.installTheme = function (formats, theme) {
var that = this;
if (arguments.length === 1) {
theme = formats;
formats = Object.keys(MagicPen.serializers);
}
if (typeof formats === 'string') {
formats = [formats];
}
if (
typeof theme !== 'object' ||
!Array.isArray(formats) ||
formats.some(function (format) {
return typeof format !== 'string';
})
) {
throw new Error("Themes must be installed the following way:\n" +
"Install theme for all formats: pen.installTheme({ comment: 'gray' })\n" +
"Install theme for a specific format: pen.installTheme('ansi', { comment: 'gray' }) or\n" +
"Install theme for a list of formats: pen.installTheme(['ansi', 'html'], { comment: 'gray' })");
}
if (!theme.styles || typeof theme.styles !== 'object') {
theme = {
styles: theme
};
}
if (that._themesHaveNotBeenClonedYet) {
var clonedThemes = {};
Object.keys(that._themes).forEach(function (format) {
clonedThemes[format] = Object.create(that._themes[format]);
});
that._themes = clonedThemes;
that._themesHaveNotBeenClonedYet = false;
}
Object.keys(theme.styles).forEach(function (themeKey) {
if (rgbRegexp.test(themeKey) || cssStyles[themeKey]) {
throw new Error("Invalid theme key: '" + themeKey + "' you can't map build styles.");
}
if (!that[themeKey]) {
that.addStyle(themeKey, function (content) {
this.text(content, themeKey);
});
}
});
formats.forEach(function (format) {
var baseTheme = that._themes[format] || { styles: {} };
var extendedTheme = extend({}, baseTheme, theme);
extendedTheme.styles = extend({}, baseTheme.styles, theme.styles);
that._themes[format] = extendedTheme;
});
return this;
};
module.exports = MagicPen;
}).call(this,require(53))
},{"41":41,"42":42,"43":43,"45":45,"46":46,"47":47,"49":49,"51":51,"53":53,"55":55}],45:[function(require,module,exports){
var flattenBlocksInLines = require(48);
function TextSerializer() {}
TextSerializer.prototype.format = 'text';
TextSerializer.prototype.serialize = function (lines) {
lines = flattenBlocksInLines(lines);
return lines.map(this.serializeLine, this).join('\n');
};
TextSerializer.prototype.serializeLine = function (line) {
return line.map(function (outputEntry) {
return this[outputEntry.style] ?
String(this[outputEntry.style](outputEntry.args)) :
'';
}, this).join('');
};
TextSerializer.prototype.text = function (options) {
return String(options.content);
};
TextSerializer.prototype.block = function (content) {
return this.serialize(content);
};
TextSerializer.prototype.raw = function (options) {
return String(options.content(this));
};
module.exports = TextSerializer;
},{"48":48}],46:[function(require,module,exports){
var cssStyles = {
bold: 'font-weight: bold',
dim: 'opacity: 0.7',
italic: 'font-style: italic',
underline: 'text-decoration: underline',
inverse: '-webkit-filter: invert(%100); filter: invert(100%)',
hidden: 'visibility: hidden',
strikeThrough: 'text-decoration: line-through',
black: 'color: black',
red: 'color: red',
green: 'color: green',
yellow: 'color: yellow',
blue: 'color: blue',
magenta: 'color: magenta',
cyan: 'color: cyan',
white: 'color: white',
gray: 'color: gray',
bgBlack: 'background-color: black',
bgRed: 'background-color: red',
bgGreen: 'background-color: green',
bgYellow: 'background-color: yellow',
bgBlue: 'background-color: blue',
bgMagenta: 'background-color: magenta',
bgCyan: 'background-color: cyan',
bgWhite: 'background-color: white'
};
Object.keys(cssStyles).forEach(function (styleName) {
cssStyles[styleName.toLowerCase()] = cssStyles[styleName];
});
module.exports = cssStyles;
},{}],47:[function(require,module,exports){
var whitespaceCacheLength = 256;
var whitespaceCache = [''];
for (var i = 1; i <= whitespaceCacheLength; i += 1) {
whitespaceCache[i] = whitespaceCache[i - 1] + ' ';
}
function duplicateText(content, times) {
if (times < 0) {
return '';
}
var result = '';
if (content === ' ') {
if (times <= whitespaceCacheLength) {
return whitespaceCache[times];
}
var segment = whitespaceCache[whitespaceCacheLength];
var numberOfSegments = Math.floor(times / whitespaceCacheLength);
for (var i = 0; i < numberOfSegments; i += 1) {
result += segment;
}
result += whitespaceCache[times % whitespaceCacheLength];
} else {
for (var j = 0; j < times; j += 1) {
result += content;
}
}
return result;
}
module.exports = duplicateText;
},{}],48:[function(require,module,exports){
var utils = require(51);
var duplicateText = require(47);
function createPadding(length) {
return { style: 'text', args: { content: duplicateText(' ', length), styles: [] } };
}
function lineContainsBlocks(line) {
return line.some(function (outputEntry) {
return outputEntry.style === 'block' ||
(outputEntry.style === 'text' && String(outputEntry.args.content).indexOf('\n') !== -1);
});
}
function flattenBlocksInOutputEntry(outputEntry) {
switch (outputEntry.style) {
case 'text': return String(outputEntry.args.content).split('\n').map(function (line) {
if (line === '') {
return [];
}
var args = { content: line, styles: outputEntry.args.styles };
return [{ style: 'text', args: args }];
});
case 'block': return flattenBlocksInLines(outputEntry.args);
default: return [];
}
}
function flattenBlocksInLine(line) {
if (line.length === 0) {
return [[]];
}
if (!lineContainsBlocks(line)) {
return [line];
}
var result = [];
var linesLengths = [];
var startIndex = 0;
line.forEach(function (outputEntry, blockIndex) {
var blockLines = flattenBlocksInOutputEntry(outputEntry);
var blockLinesLengths = blockLines.map(function (line) {
return utils.calculateLineSize(line).width;
});
var longestLineLength = Math.max.apply(null, blockLinesLengths);
blockLines.forEach(function (blockLine, index) {
var resultLine = result[index];
if (!resultLine) {
result[index] = resultLine = [];
linesLengths[index] = 0;
}
if (blockLine.length) {
var paddingLength = startIndex - linesLengths[index];
resultLine.push(createPadding(paddingLength));
Array.prototype.push.apply(resultLine, blockLine);
linesLengths[index] = startIndex + blockLinesLengths[index];
}
});
startIndex += longestLineLength;
}, this);
return result;
}
function flattenBlocksInLines(lines) {
var result = [];
lines.forEach(function (line) {
flattenBlocksInLine(line).forEach(function (line) {
result.push(line);
});
});
return result;
}
module.exports = flattenBlocksInLines;
},{"47":47,"51":51}],49:[function(require,module,exports){
module.exports = /^(?:bg)?#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i;
},{}],50:[function(require,module,exports){
module.exports = function (theme, styles) {
if (styles.length === 1) {
var count = 0;
var stack = [];
var themeMapping = styles[0];
var themeStyles = theme.styles || {};
while(typeof themeMapping === 'string' && themeStyles[themeMapping]) {
themeMapping = themeStyles[themeMapping];
count += 1;
if (100 < count) {
var index = stack.indexOf(themeMapping);
stack.push(themeMapping);
if (index !== -1) {
throw new Error('Your theme contains a loop: ' + stack.slice(index).join(' -> '));
}
}
}
return Array.isArray(themeMapping) ? themeMapping : [themeMapping];
}
return styles;
};
},{}],51:[function(require,module,exports){
var utils = {
extend: function (target) {
for (var i = 1; i < arguments.length; i += 1) {
var source = arguments[i];
Object.keys(source).forEach(function (key) {
target[key] = source[key];
});
}
return target;
},
calculateOutputEntrySize: function (outputEntry) {
if (outputEntry.size) {
return outputEntry.size;
}
var size;
switch (outputEntry.style) {
case 'text':
size = { width: String(outputEntry.args.content).length, height: 1 };
break;
case 'block':
size = utils.calculateSize(outputEntry.args);
break;
case 'raw':
var arg = outputEntry.args;
size = { width: arg.width, height: arg.height };
break;
default: size = { width: 0, height: 0 };
}
outputEntry.size = size;
return size;
},
calculateLineSize: function (line) {
var size = { height: 1, width: 0 };
line.forEach(function (outputEntry) {
var outputEntrySize = utils.calculateOutputEntrySize(outputEntry);
size.width += outputEntrySize.width;
size.height = Math.max(outputEntrySize.height, size.height);
});
return size;
},
calculateSize: function (lines) {
var size = { height: 0, width: 0 };
lines.forEach(function (line) {
var lineSize = utils.calculateLineSize(line);
size.height += lineSize.height;
size.width = Math.max(size.width, lineSize.width);
});
return size;
},
arrayEquals: function (a, b) {
if (a === b) {
return true;
}
if (!a || a.length !== b.length) {
return false;
}
for (var i = 0; i < a.length; i += 1) {
if (a[i] !== b[i]) {
return false;
}
}
return true;
},
escapeRegExp: function (text){
return text.replace(/([.*+?^${}()|\[\]\/\\])/g, "\\$1");
},
findFirst: function (arr, predicate, thisObj) {
var scope = thisObj || null;
for (var i = 0 ; i < arr.length ; i += 1) {
if (predicate.call(scope, arr[i], i, arr)) {
return arr[i];
}
}
return null;
},
getFunctionName: function (f) {
if (typeof f.name === 'string') {
return f.name;
}
var matchFunctionName = Function.prototype.toString.call(f).match(/function ([^\(]+)/);
if (matchFunctionName) {
return matchFunctionName[1];
}
if (f === Object) {
return 'Object';
}
if (f === Function) {
return 'Function';
}
}
};
module.exports = utils;
},{}],52:[function(require,module,exports){
'use strict';
module.exports = Number.isNaN || function (x) {
return x !== x;
};
},{}],53:[function(require,module,exports){
// shim for using process in browser
var process = module.exports = {};
// cached from whatever global is present so that test runners that stub it
// don't break things. But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals. It's inside a
// function because try/catches deoptimize in certain engines.
var cachedSetTimeout;
var cachedClearTimeout;
function defaultSetTimout() {
throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout () {
throw new Error('clearTimeout has not been defined');
}
(function () {
try {
if (typeof setTimeout === 'function') {
cachedSetTimeout = setTimeout;
} else {
cachedSetTimeout = defaultSetTimout;
}
} catch (e) {
cachedSetTimeout = defaultSetTimout;
}
try {
if (typeof clearTimeout === 'function') {
cachedClearTimeout = clearTimeout;
} else {
cachedClearTimeout = defaultClearTimeout;
}
} catch (e) {
cachedClearTimeout = defaultClearTimeout;
}
} ())
function runTimeout(fun) {
if (cachedSetTimeout === setTimeout) {
//normal enviroments in sane situations
return setTimeout(fun, 0);
}
// if setTimeout wasn't available but was latter defined
if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
cachedSetTimeout = setTimeout;
return setTimeout(fun, 0);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedSetTimeout(fun, 0);
} catch(e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedSetTimeout.call(null, fun, 0);
} catch(e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
return cachedSetTimeout.call(this, fun, 0);
}
}
}
function runClearTimeout(marker) {
if (cachedClearTimeout === clearTimeout) {
//normal enviroments in sane situations
return clearTimeout(marker);
}
// if clearTimeout wasn't available but was latter defined
if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
cachedClearTimeout = clearTimeout;
return clearTimeout(marker);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedClearTimeout(marker);
} catch (e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedClearTimeout.call(null, marker);
} catch (e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
// Some versions of I.E. have different rules for clearTimeout vs setTimeout
return cachedClearTimeout.call(this, marker);
}
}
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
if (!draining || !currentQueue) {
return;
}
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = runTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
runClearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
runTimeout(drainQueue);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.prependListener = noop;
process.prependOnceListener = noop;
process.listeners = function (name) { return [] }
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
},{}],54:[function(require,module,exports){
'use strict';
var isFinite = require(39);
module.exports = function (str, n) {
if (typeof str !== 'string') {
throw new TypeError('Expected a string as the first argument');
}
if (n < 0 || !isFinite(n)) {
throw new TypeError('Expected a finite positive number');
}
var ret = '';
do {
if (n & 1) {
ret += str;
}
str += str;
} while (n = n >> 1);
return ret;
};
},{"39":39}],55:[function(require,module,exports){
(function (process){
'use strict';
var argv = process.argv;
module.exports = (function () {
if (argv.indexOf('--no-color') !== -1 ||
argv.indexOf('--no-colors') !== -1 ||
argv.indexOf('--color=false') !== -1) {
return false;
}
if (argv.indexOf('--color') !== -1 ||
argv.indexOf('--colors') !== -1 ||
argv.indexOf('--color=true') !== -1 ||
argv.indexOf('--color=always') !== -1) {
return true;
}
if (process.stdout && !process.stdout.isTTY) {
return false;
}
if (process.platform === 'win32') {
return true;
}
if ('COLORTERM' in process.env) {
return true;
}
if (process.env.TERM === 'dumb') {
return false;
}
if (/^screen|^xterm|^vt100|color|ansi|cygwin|linux/i.test(process.env.TERM)) {
return true;
}
return false;
})();
}).call(this,require(53))
},{"53":53}],56:[function(require,module,exports){
(function (process,global){
/* @preserve
* The MIT License (MIT)
*
* Copyright (c) 2014 Petka Antonov
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
/**
* bluebird build version 2.9.34-longstack2
* Features enabled: core, race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, cancel, using, filter, any, each, timers
*/
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.Promise=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof _dereq_=="function"&&_dereq_;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof _dereq_=="function"&&_dereq_;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise) {
var SomePromiseArray = Promise._SomePromiseArray;
function any(promises) {
var ret = new SomePromiseArray(promises);
var promise = ret.promise();
ret.setHowMany(1);
ret.setUnwrap();
ret.init();
return promise;
}
Promise.any = function (promises) {
return any(promises);
};
Promise.prototype.any = function () {
return any(this);
};
};
},{}],2:[function(_dereq_,module,exports){
"use strict";
var firstLineError;
try {throw new Error(); } catch (e) {firstLineError = e;}
var schedule = _dereq_("./schedule.js");
var Queue = _dereq_("./queue.js");
var util = _dereq_("./util.js");
function Async() {
this._isTickUsed = false;
this._lateQueue = new Queue(16);
this._normalQueue = new Queue(16);
this._trampolineEnabled = true;
var self = this;
this.drainQueues = function () {
self._drainQueues();
};
this._schedule =
schedule.isStatic ? schedule(this.drainQueues) : schedule;
}
Async.prototype.disableTrampolineIfNecessary = function() {
if (util.hasDevTools) {
this._trampolineEnabled = false;
}
};
Async.prototype.enableTrampoline = function() {
if (!this._trampolineEnabled) {
this._trampolineEnabled = true;
this._schedule = function(fn) {
setTimeout(fn, 0);
};
}
};
Async.prototype.haveItemsQueued = function () {
return this._normalQueue.length() > 0;
};
Async.prototype.throwLater = function(fn, arg) {
if (arguments.length === 1) {
arg = fn;
fn = function () { throw arg; };
}
if (typeof setTimeout !== "undefined") {
setTimeout(function() {
fn(arg);
}, 0);
} else try {
this._schedule(function() {
fn(arg);
});
} catch (e) {
throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/m3OTXk\u000a");
}
};
function AsyncInvokeLater(fn, receiver, arg) {
this._lateQueue.push(fn, receiver, arg);
this._queueTick();
}
function AsyncInvoke(fn, receiver, arg) {
this._normalQueue.push(fn, receiver, arg);
this._queueTick();
}
function AsyncSettlePromises(promise) {
this._normalQueue._pushOne(promise);
this._queueTick();
}
if (!util.hasDevTools) {
Async.prototype.invokeLater = AsyncInvokeLater;
Async.prototype.invoke = AsyncInvoke;
Async.prototype.settlePromises = AsyncSettlePromises;
} else {
if (schedule.isStatic) {
schedule = function(fn) { setTimeout(fn, 0); };
}
Async.prototype.invokeLater = function (fn, receiver, arg) {
if (this._trampolineEnabled) {
AsyncInvokeLater.call(this, fn, receiver, arg);
} else {
this._schedule(function() {
setTimeout(function() {
fn.call(receiver, arg);
}, 100);
});
}
};
Async.prototype.invoke = function (fn, receiver, arg) {
if (this._trampolineEnabled) {
AsyncInvoke.call(this, fn, receiver, arg);
} else {
this._schedule(function() {
fn.call(receiver, arg);
});
}
};
Async.prototype.settlePromises = function(promise) {
if (this._trampolineEnabled) {
AsyncSettlePromises.call(this, promise);
} else {
this._schedule(function() {
promise._settlePromises();
});
}
};
}
Async.prototype.invokeFirst = function (fn, receiver, arg) {
this._normalQueue.unshift(fn, receiver, arg);
this._queueTick();
};
Async.prototype._drainQueue = function(queue) {
while (queue.length() > 0) {
var fn = queue.shift();
if (typeof fn !== "function") {
fn._settlePromises();
continue;
}
var receiver = queue.shift();
var arg = queue.shift();
fn.call(receiver, arg);
}
};
Async.prototype._drainQueues = function () {
this._drainQueue(this._normalQueue);
this._reset();
this._drainQueue(this._lateQueue);
};
Async.prototype._queueTick = function () {
if (!this._isTickUsed) {
this._isTickUsed = true;
this._schedule(this.drainQueues);
}
};
Async.prototype._reset = function () {
this._isTickUsed = false;
};
module.exports = new Async();
module.exports.firstLineError = firstLineError;
},{"./queue.js":28,"./schedule.js":31,"./util.js":38}],3:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise, INTERNAL, tryConvertToPromise) {
var rejectThis = function(_, e) {
this._reject(e);
};
var targetRejected = function(e, context) {
context.promiseRejectionQueued = true;
context.bindingPromise._then(rejectThis, rejectThis, null, this, e);
};
var bindingResolved = function(thisArg, context) {
if (this._isPending()) {
this._resolveCallback(context.target);
}
};
var bindingRejected = function(e, context) {
if (!context.promiseRejectionQueued) this._reject(e);
};
Promise.prototype.bind = function (thisArg) {
var maybePromise = tryConvertToPromise(thisArg);
var ret = new Promise(INTERNAL);
ret._propagateFrom(this, 1);
var target = this._target();
ret._setBoundTo(maybePromise);
if (maybePromise instanceof Promise) {
var context = {
promiseRejectionQueued: false,
promise: ret,
target: target,
bindingPromise: maybePromise
};
target._then(INTERNAL, targetRejected, ret._progress, ret, context);
maybePromise._then(
bindingResolved, bindingRejected, ret._progress, ret, context);
} else {
ret._resolveCallback(target);
}
return ret;
};
Promise.prototype._setBoundTo = function (obj) {
if (obj !== undefined) {
this._bitField = this._bitField | 131072;
this._boundTo = obj;
} else {
this._bitField = this._bitField & (~131072);
}
};
Promise.prototype._isBound = function () {
return (this._bitField & 131072) === 131072;
};
Promise.bind = function (thisArg, value) {
var maybePromise = tryConvertToPromise(thisArg);
var ret = new Promise(INTERNAL);
ret._setBoundTo(maybePromise);
if (maybePromise instanceof Promise) {
maybePromise._then(function() {
ret._resolveCallback(value);
}, ret._reject, ret._progress, ret, null);
} else {
ret._resolveCallback(value);
}
return ret;
};
};
},{}],4:[function(_dereq_,module,exports){
"use strict";
var old;
if (typeof Promise !== "undefined") old = Promise;
function noConflict() {
try { if (Promise === bluebird) Promise = old; }
catch (e) {}
return bluebird;
}
var bluebird = _dereq_("./promise.js")();
bluebird.noConflict = noConflict;
module.exports = bluebird;
},{"./promise.js":23}],5:[function(_dereq_,module,exports){
"use strict";
var cr = Object.create;
if (cr) {
var callerCache = cr(null);
var getterCache = cr(null);
callerCache[" size"] = getterCache[" size"] = 0;
}
module.exports = function(Promise) {
var util = _dereq_("./util.js");
var canEvaluate = util.canEvaluate;
var isIdentifier = util.isIdentifier;
var getMethodCaller;
var getGetter;
if (!true) {
var makeMethodCaller = function (methodName) {
return new Function("ensureMethod", " \n\
return function(obj) { \n\
'use strict' \n\
var len = this.length; \n\
ensureMethod(obj, 'methodName'); \n\
switch(len) { \n\
case 1: return obj.methodName(this[0]); \n\
case 2: return obj.methodName(this[0], this[1]); \n\
case 3: return obj.methodName(this[0], this[1], this[2]); \n\
case 0: return obj.methodName(); \n\
default: \n\
return obj.methodName.apply(obj, this); \n\
} \n\
}; \n\
".replace(/methodName/g, methodName))(ensureMethod);
};
var makeGetter = function (propertyName) {
return new Function("obj", " \n\
'use strict'; \n\
return obj.propertyName; \n\
".replace("propertyName", propertyName));
};
var getCompiled = function(name, compiler, cache) {
var ret = cache[name];
if (typeof ret !== "function") {
if (!isIdentifier(name)) {
return null;
}
ret = compiler(name);
cache[name] = ret;
cache[" size"]++;
if (cache[" size"] > 512) {
var keys = Object.keys(cache);
for (var i = 0; i < 256; ++i) delete cache[keys[i]];
cache[" size"] = keys.length - 256;
}
}
return ret;
};
getMethodCaller = function(name) {
return getCompiled(name, makeMethodCaller, callerCache);
};
getGetter = function(name) {
return getCompiled(name, makeGetter, getterCache);
};
}
function ensureMethod(obj, methodName) {
var fn;
if (obj != null) fn = obj[methodName];
if (typeof fn !== "function") {
var message = "Object " + util.classString(obj) + " has no method '" +
util.toString(methodName) + "'";
throw new Promise.TypeError(message);
}
return fn;
}
function caller(obj) {
var methodName = this.pop();
var fn = ensureMethod(obj, methodName);
return fn.apply(obj, this);
}
Promise.prototype.call = function (methodName) {
var $_len = arguments.length;var args = new Array($_len - 1); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];}
if (!true) {
if (canEvaluate) {
var maybeCaller = getMethodCaller(methodName);
if (maybeCaller !== null) {
return this._then(
maybeCaller, undefined, undefined, args, undefined);
}
}
}
args.push(methodName);
return this._then(caller, undefined, undefined, args, undefined);
};
function namedGetter(obj) {
return obj[this];
}
function indexedGetter(obj) {
var index = +this;
if (index < 0) index = Math.max(0, index + obj.length);
return obj[index];
}
Promise.prototype.get = function (propertyName) {
var isIndex = (typeof propertyName === "number");
var getter;
if (!isIndex) {
if (canEvaluate) {
var maybeGetter = getGetter(propertyName);
getter = maybeGetter !== null ? maybeGetter : namedGetter;
} else {
getter = namedGetter;
}
} else {
getter = indexedGetter;
}
return this._then(getter, undefined, undefined, propertyName, undefined);
};
};
},{"./util.js":38}],6:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise) {
var errors = _dereq_("./errors.js");
var async = _dereq_("./async.js");
var CancellationError = errors.CancellationError;
Promise.prototype._cancel = function (reason) {
if (!this.isCancellable()) return this;
var parent;
var promiseToReject = this;
while ((parent = promiseToReject._cancellationParent) !== undefined &&
parent.isCancellable()) {
promiseToReject = parent;
}
this._unsetCancellable();
promiseToReject._target()._rejectCallback(reason, false, true);
};
Promise.prototype.cancel = function (reason) {
if (!this.isCancellable()) return this;
if (reason === undefined) reason = new CancellationError();
async.invokeLater(this._cancel, this, reason);
return this;
};
Promise.prototype.cancellable = function () {
if (this._cancellable()) return this;
async.enableTrampoline();
this._setCancellable();
this._cancellationParent = undefined;
return this;
};
Promise.prototype.uncancellable = function () {
var ret = this.then();
ret._unsetCancellable();
return ret;
};
Promise.prototype.fork = function (didFulfill, didReject, didProgress) {
var ret = this._then(didFulfill, didReject, didProgress,
undefined, undefined);
ret._setCancellable();
ret._cancellationParent = undefined;
return ret;
};
};
},{"./async.js":2,"./errors.js":13}],7:[function(_dereq_,module,exports){
"use strict";
module.exports = function() {
var async = _dereq_("./async.js");
var util = _dereq_("./util.js");
var bluebirdFramePattern =
/[\\\/]bluebird[\\\/]js[\\\/](main|debug|zalgo|instrumented)/;
var stackFramePattern = null;
var formatStack = null;
var indentStackFrames = false;
var warn;
function CapturedTrace(parent) {
this._parent = parent;
var length = this._length = 1 + (parent === undefined ? 0 : parent._length);
captureStackTrace(this, CapturedTrace);
if (length > 32) this.uncycle();
}
util.inherits(CapturedTrace, Error);
CapturedTrace.prototype.uncycle = function() {
var length = this._length;
if (length < 2) return;
var nodes = [];
var stackToIndex = {};
for (var i = 0, node = this; node !== undefined; ++i) {
nodes.push(node);
node = node._parent;
}
length = this._length = i;
for (var i = length - 1; i >= 0; --i) {
var stack = nodes[i].stack;
if (stackToIndex[stack] === undefined) {
stackToIndex[stack] = i;
}
}
for (var i = 0; i < length; ++i) {
var currentStack = nodes[i].stack;
var index = stackToIndex[currentStack];
if (index !== undefined && index !== i) {
if (index > 0) {
nodes[index - 1]._parent = undefined;
nodes[index - 1]._length = 1;
}
nodes[i]._parent = undefined;
nodes[i]._length = 1;
var cycleEdgeNode = i > 0 ? nodes[i - 1] : this;
if (index < length - 1) {
cycleEdgeNode._parent = nodes[index + 1];
cycleEdgeNode._parent.uncycle();
cycleEdgeNode._length =
cycleEdgeNode._parent._length + 1;
} else {
cycleEdgeNode._parent = undefined;
cycleEdgeNode._length = 1;
}
var currentChildLength = cycleEdgeNode._length + 1;
for (var j = i - 2; j >= 0; --j) {
nodes[j]._length = currentChildLength;
currentChildLength++;
}
return;
}
}
};
CapturedTrace.prototype.parent = function() {
return this._parent;
};
CapturedTrace.prototype.hasParent = function() {
return this._parent !== undefined;
};
CapturedTrace.prototype.attachExtraTrace = function(error) {
if (error.__stackCleaned__) return;
this.uncycle();
var parsed = CapturedTrace.parseStackAndMessage(error);
var message = parsed.message;
var stacks = [parsed.stack];
var trace = this;
while (trace !== undefined) {
stacks.push(cleanStack(trace.stack.split("\n")));
trace = trace._parent;
}
removeCommonRoots(stacks);
removeDuplicateOrEmptyJumps(stacks);
util.notEnumerableProp(error, "stack", reconstructStack(message, stacks));
util.notEnumerableProp(error, "__stackCleaned__", true);
};
function reconstructStack(message, stacks) {
for (var i = 0; i < stacks.length - 1; ++i) {
stacks[i].push("From previous event:");
stacks[i] = stacks[i].join("\n");
}
if (i < stacks.length) {
stacks[i] = stacks[i].join("\n");
}
return message + "\n" + stacks.join("\n");
}
function removeDuplicateOrEmptyJumps(stacks) {
for (var i = 0; i < stacks.length; ++i) {
if (stacks[i].length === 0 ||
((i + 1 < stacks.length) && stacks[i][0] === stacks[i+1][0])) {
stacks.splice(i, 1);
i--;
}
}
}
function removeCommonRoots(stacks) {
var current = stacks[0];
for (var i = 1; i < stacks.length; ++i) {
var prev = stacks[i];
var currentLastIndex = current.length - 1;
var currentLastLine = current[currentLastIndex];
var commonRootMeetPoint = -1;
for (var j = prev.length - 1; j >= 0; --j) {
if (prev[j] === currentLastLine) {
commonRootMeetPoint = j;
break;
}
}
for (var j = commonRootMeetPoint; j >= 0; --j) {
var line = prev[j];
if (current[currentLastIndex] === line) {
current.pop();
currentLastIndex--;
} else {
break;
}
}
current = prev;
}
}
function cleanStack(stack) {
var ret = [];
for (var i = 0; i < stack.length; ++i) {
var line = stack[i];
var isTraceLine = stackFramePattern.test(line) ||
" (No stack trace)" === line;
var isInternalFrame = isTraceLine && shouldIgnore(line);
if (isTraceLine && !isInternalFrame) {
if (indentStackFrames && line.charAt(0) !== " ") {
line = " " + line;
}
ret.push(line);
}
}
return ret;
}
function stackFramesAsArray(error) {
var stack = error.stack.replace(/\s+$/g, "").split("\n");
for (var i = 0; i < stack.length; ++i) {
var line = stack[i];
if (" (No stack trace)" === line || stackFramePattern.test(line)) {
break;
}
}
if (i > 0) {
stack = stack.slice(i);
}
return stack;
}
CapturedTrace.parseStackAndMessage = function(error) {
var stack = error.stack;
var message = error.toString();
stack = typeof stack === "string" && stack.length > 0
? stackFramesAsArray(error) : [" (No stack trace)"];
return {
message: message,
stack: cleanStack(stack)
};
};
CapturedTrace.formatAndLogError = function(error, title) {
if (typeof console !== "undefined") {
var message;
if (typeof error === "object" || typeof error === "function") {
var stack = error.stack;
message = title + formatStack(stack, error);
} else {
message = title + String(error);
}
if (typeof warn === "function") {
warn(message);
} else if (typeof console.log === "function" ||
typeof console.log === "object") {
console.log(message);
}
}
};
CapturedTrace.unhandledRejection = function (reason) {
CapturedTrace.formatAndLogError(reason, "^--- With additional stack trace: ");
};
CapturedTrace.isSupported = function () {
return typeof captureStackTrace === "function";
};
CapturedTrace.fireRejectionEvent =
function(name, localHandler, reason, promise) {
var localEventFired = false;
try {
if (typeof localHandler === "function") {
localEventFired = true;
if (name === "rejectionHandled") {
localHandler(promise);
} else {
localHandler(reason, promise);
}
}
} catch (e) {
async.throwLater(e);
}
var globalEventFired = false;
try {
globalEventFired = fireGlobalEvent(name, reason, promise);
} catch (e) {
globalEventFired = true;
async.throwLater(e);
}
var domEventFired = false;
if (fireDomEvent) {
try {
domEventFired = fireDomEvent(name.toLowerCase(), {
reason: reason,
promise: promise
});
} catch (e) {
domEventFired = true;
async.throwLater(e);
}
}
if (!globalEventFired && !localEventFired && !domEventFired &&
name === "unhandledRejection") {
CapturedTrace.formatAndLogError(reason, "Unhandled rejection ");
}
};
function formatNonError(obj) {
var str;
if (typeof obj === "function") {
str = "[function " +
(obj.name || "anonymous") +
"]";
} else {
str = obj.toString();
var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/;
if (ruselessToString.test(str)) {
try {
var newStr = JSON.stringify(obj);
str = newStr;
}
catch(e) {
}
}
if (str.length === 0) {
str = "(empty array)";
}
}
return ("(<" + snip(str) + ">, no stack trace)");
}
function snip(str) {
var maxChars = 41;
if (str.length < maxChars) {
return str;
}
return str.substr(0, maxChars - 3) + "...";
}
var shouldIgnore = function() { return false; };
var parseLineInfoRegex = /[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;
function parseLineInfo(line) {
var matches = line.match(parseLineInfoRegex);
if (matches) {
return {
fileName: matches[1],
line: parseInt(matches[2], 10)
};
}
}
CapturedTrace.setBounds = function(firstLineError, lastLineError) {
if (!CapturedTrace.isSupported()) return;
var firstStackLines = firstLineError.stack.split("\n");
var lastStackLines = lastLineError.stack.split("\n");
var firstIndex = -1;
var lastIndex = -1;
var firstFileName;
var lastFileName;
for (var i = 0; i < firstStackLines.length; ++i) {
var result = parseLineInfo(firstStackLines[i]);
if (result) {
firstFileName = result.fileName;
firstIndex = result.line;
break;
}
}
for (var i = 0; i < lastStackLines.length; ++i) {
var result = parseLineInfo(lastStackLines[i]);
if (result) {
lastFileName = result.fileName;
lastIndex = result.line;
break;
}
}
if (firstIndex < 0 || lastIndex < 0 || !firstFileName || !lastFileName ||
firstFileName !== lastFileName || firstIndex >= lastIndex) {
return;
}
shouldIgnore = function(line) {
if (bluebirdFramePattern.test(line)) return true;
var info = parseLineInfo(line);
if (info) {
if (info.fileName === firstFileName &&
(firstIndex <= info.line && info.line <= lastIndex)) {
return true;
}
}
return false;
};
};
var captureStackTrace = (function stackDetection() {
var v8stackFramePattern = /^\s*at\s*/;
var v8stackFormatter = function(stack, error) {
if (typeof stack === "string") return stack;
if (error.name !== undefined &&
error.message !== undefined) {
return error.toString();
}
return formatNonError(error);
};
if (typeof Error.stackTraceLimit === "number" &&
typeof Error.captureStackTrace === "function") {
Error.stackTraceLimit = Error.stackTraceLimit + 6;
stackFramePattern = v8stackFramePattern;
formatStack = v8stackFormatter;
var captureStackTrace = Error.captureStackTrace;
shouldIgnore = function(line) {
return bluebirdFramePattern.test(line);
};
return function(receiver, ignoreUntil) {
Error.stackTraceLimit = Error.stackTraceLimit + 6;
captureStackTrace(receiver, ignoreUntil);
Error.stackTraceLimit = Error.stackTraceLimit - 6;
};
}
var err = new Error();
if (typeof err.stack === "string" &&
err.stack.split("\n")[0].indexOf("stackDetection@") >= 0) {
stackFramePattern = /@/;
formatStack = v8stackFormatter;
indentStackFrames = true;
return function captureStackTrace(o) {
o.stack = new Error().stack;
};
}
var hasStackAfterThrow;
try { throw new Error(); }
catch(e) {
hasStackAfterThrow = ("stack" in e);
}
if (!("stack" in err) && hasStackAfterThrow &&
typeof Error.stackTraceLimit === "number") {
stackFramePattern = v8stackFramePattern;
formatStack = v8stackFormatter;
return function captureStackTrace(o) {
Error.stackTraceLimit = Error.stackTraceLimit + 6;
try { throw new Error(); }
catch(e) { o.stack = e.stack; }
Error.stackTraceLimit = Error.stackTraceLimit - 6;
};
}
formatStack = function(stack, error) {
if (typeof stack === "string") return stack;
if ((typeof error === "object" ||
typeof error === "function") &&
error.name !== undefined &&
error.message !== undefined) {
return error.toString();
}
return formatNonError(error);
};
return null;
})([]);
var fireDomEvent;
var fireGlobalEvent = (function() {
if (util.isNode) {
return function(name, reason, promise) {
if (name === "rejectionHandled") {
return process.emit(name, promise);
} else {
return process.emit(name, reason, promise);
}
};
} else {
var customEventWorks = false;
var anyEventWorks = true;
try {
var ev = new self.CustomEvent("test");
customEventWorks = ev instanceof CustomEvent;
} catch (e) {}
if (!customEventWorks) {
try {
var event = document.createEvent("CustomEvent");
event.initCustomEvent("testingtheevent", false, true, {});
self.dispatchEvent(event);
} catch (e) {
anyEventWorks = false;
}
}
if (anyEventWorks) {
fireDomEvent = function(type, detail) {
var event;
if (customEventWorks) {
event = new self.CustomEvent(type, {
detail: detail,
bubbles: false,
cancelable: true
});
} else if (self.dispatchEvent) {
event = document.createEvent("CustomEvent");
event.initCustomEvent(type, false, true, detail);
}
return event ? !self.dispatchEvent(event) : false;
};
}
var toWindowMethodNameMap = {};
toWindowMethodNameMap["unhandledRejection"] = ("on" +
"unhandledRejection").toLowerCase();
toWindowMethodNameMap["rejectionHandled"] = ("on" +
"rejectionHandled").toLowerCase();
return function(name, reason, promise) {
var methodName = toWindowMethodNameMap[name];
var method = self[methodName];
if (!method) return false;
if (name === "rejectionHandled") {
method.call(self, promise);
} else {
method.call(self, reason, promise);
}
return true;
};
}
})();
if (typeof console !== "undefined" && typeof console.warn !== "undefined") {
warn = function (message) {
console.warn(message);
};
if (util.isNode && process.stderr.isTTY) {
warn = function(message) {
process.stderr.write("\u001b[31m" + message + "\u001b[39m\n");
};
} else if (!util.isNode && typeof (new Error().stack) === "string") {
warn = function(message) {
console.warn("%c" + message, "color: red");
};
}
}
return CapturedTrace;
};
},{"./async.js":2,"./util.js":38}],8:[function(_dereq_,module,exports){
"use strict";
module.exports = function(NEXT_FILTER) {
var util = _dereq_("./util.js");
var errors = _dereq_("./errors.js");
var tryCatch = util.tryCatch;
var errorObj = util.errorObj;
var keys = _dereq_("./es5.js").keys;
var TypeError = errors.TypeError;
function CatchFilter(instances, callback, promise) {
this._instances = instances;
this._callback = callback;
this._promise = promise;
}
function safePredicate(predicate, e) {
var safeObject = {};
var retfilter = tryCatch(predicate).call(safeObject, e);
if (retfilter === errorObj) return retfilter;
var safeKeys = keys(safeObject);
if (safeKeys.length) {
errorObj.e = new TypeError("Catch filter must inherit from Error or be a simple predicate function\u000a\u000a See http://goo.gl/o84o68\u000a");
return errorObj;
}
return retfilter;
}
CatchFilter.prototype.doFilter = function (e) {
var cb = this._callback;
var promise = this._promise;
var boundTo = promise._boundValue();
for (var i = 0, len = this._instances.length; i < len; ++i) {
var item = this._instances[i];
var itemIsErrorType = item === Error ||
(item != null && item.prototype instanceof Error);
if (itemIsErrorType && e instanceof item) {
var ret = tryCatch(cb).call(boundTo, e);
if (ret === errorObj) {
NEXT_FILTER.e = ret.e;
return NEXT_FILTER;
}
return ret;
} else if (typeof item === "function" && !itemIsErrorType) {
var shouldHandle = safePredicate(item, e);
if (shouldHandle === errorObj) {
e = errorObj.e;
break;
} else if (shouldHandle) {
var ret = tryCatch(cb).call(boundTo, e);
if (ret === errorObj) {
NEXT_FILTER.e = ret.e;
return NEXT_FILTER;
}
return ret;
}
}
}
NEXT_FILTER.e = e;
return NEXT_FILTER;
};
return CatchFilter;
};
},{"./errors.js":13,"./es5.js":14,"./util.js":38}],9:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise, CapturedTrace, isDebugging) {
var contextStack = [];
function Context() {
this._trace = new CapturedTrace(peekContext());
}
Context.prototype._pushContext = function () {
if (!isDebugging()) return;
if (this._trace !== undefined) {
contextStack.push(this._trace);
}
};
Context.prototype._popContext = function () {
if (!isDebugging()) return;
if (this._trace !== undefined) {
contextStack.pop();
}
};
function createContext() {
if (isDebugging()) return new Context();
}
function peekContext() {
var lastIndex = contextStack.length - 1;
if (lastIndex >= 0) {
return contextStack[lastIndex];
}
return undefined;
}
Promise.prototype._peekContext = peekContext;
Promise.prototype._pushContext = Context.prototype._pushContext;
Promise.prototype._popContext = Context.prototype._popContext;
return createContext;
};
},{}],10:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise, CapturedTrace) {
var getDomain = Promise._getDomain;
var async = _dereq_("./async.js");
var Warning = _dereq_("./errors.js").Warning;
var util = _dereq_("./util.js");
var canAttachTrace = util.canAttachTrace;
var unhandledRejectionHandled;
var possiblyUnhandledRejection;
var debugging = false || (util.isNode &&
(!!process.env["BLUEBIRD_DEBUG"] ||
process.env["NODE_ENV"] === "development"));
if (debugging) {
async.disableTrampolineIfNecessary();
}
Promise.prototype._ignoreRejections = function() {
this._unsetRejectionIsUnhandled();
this._bitField = this._bitField | 16777216;
};
Promise.prototype._ensurePossibleRejectionHandled = function () {
if ((this._bitField & 16777216) !== 0) return;
this._setRejectionIsUnhandled();
async.invokeLater(this._notifyUnhandledRejection, this, undefined);
};
Promise.prototype._notifyUnhandledRejectionIsHandled = function () {
CapturedTrace.fireRejectionEvent("rejectionHandled",
unhandledRejectionHandled, undefined, this);
};
Promise.prototype._notifyUnhandledRejection = function () {
if (this._isRejectionUnhandled()) {
var reason = this._getCarriedStackTrace() || this._settledValue;
this._setUnhandledRejectionIsNotified();
CapturedTrace.fireRejectionEvent("unhandledRejection",
possiblyUnhandledRejection, reason, this);
}
};
Promise.prototype._setUnhandledRejectionIsNotified = function () {
this._bitField = this._bitField | 524288;
};
Promise.prototype._unsetUnhandledRejectionIsNotified = function () {
this._bitField = this._bitField & (~524288);
};
Promise.prototype._isUnhandledRejectionNotified = function () {
return (this._bitField & 524288) > 0;
};
Promise.prototype._setRejectionIsUnhandled = function () {
this._bitField = this._bitField | 2097152;
};
Promise.prototype._unsetRejectionIsUnhandled = function () {
this._bitField = this._bitField & (~2097152);
if (this._isUnhandledRejectionNotified()) {
this._unsetUnhandledRejectionIsNotified();
this._notifyUnhandledRejectionIsHandled();
}
};
Promise.prototype._isRejectionUnhandled = function () {
return (this._bitField & 2097152) > 0;
};
Promise.prototype._setCarriedStackTrace = function (capturedTrace) {
this._bitField = this._bitField | 1048576;
this._fulfillmentHandler0 = capturedTrace;
};
Promise.prototype._isCarryingStackTrace = function () {
return (this._bitField & 1048576) > 0;
};
Promise.prototype._getCarriedStackTrace = function () {
return this._isCarryingStackTrace()
? this._fulfillmentHandler0
: undefined;
};
Promise.prototype._captureStackTrace = function (force) {
if (debugging || (force && CapturedTrace.isSupported())) {
this._traceForced = force;
this._trace = new CapturedTrace(this._peekContext());
}
return this;
};
Promise.prototype._attachExtraTrace = function (error, ignoreSelf) {
if ((debugging || this._traceForced) && canAttachTrace(error)) {
var trace = this._trace;
if (trace !== undefined) {
if (ignoreSelf) trace = trace._parent;
}
if (trace !== undefined) {
trace.attachExtraTrace(error);
} else if (!error.__stackCleaned__) {
var parsed = CapturedTrace.parseStackAndMessage(error);
util.notEnumerableProp(error, "stack",
parsed.message + "\n" + parsed.stack.join("\n"));
util.notEnumerableProp(error, "__stackCleaned__", true);
}
}
};
Promise.prototype._warn = function(message) {
var warning = new Warning(message);
var ctx = this._peekContext();
if (ctx) {
ctx.attachExtraTrace(warning);
} else {
var parsed = CapturedTrace.parseStackAndMessage(warning);
warning.stack = parsed.message + "\n" + parsed.stack.join("\n");
}
CapturedTrace.formatAndLogError(warning, "");
};
Promise.onPossiblyUnhandledRejection = function (fn) {
var domain = getDomain();
possiblyUnhandledRejection =
typeof fn === "function" ? (domain === null ? fn : domain.bind(fn))
: undefined;
};
Promise.onUnhandledRejectionHandled = function (fn) {
var domain = getDomain();
unhandledRejectionHandled =
typeof fn === "function" ? (domain === null ? fn : domain.bind(fn))
: undefined;
};
Promise.longStackTraces = function () {
if (async.haveItemsQueued() &&
debugging === false
) {
throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/DT1qyG\u000a");
}
debugging = CapturedTrace.isSupported();
if (debugging) {
async.disableTrampolineIfNecessary();
}
};
Promise.hasLongStackTraces = function () {
return debugging && CapturedTrace.isSupported();
};
if (!CapturedTrace.isSupported()) {
Promise.longStackTraces = function(){};
debugging = false;
}
return function() {
return debugging;
};
};
},{"./async.js":2,"./errors.js":13,"./util.js":38}],11:[function(_dereq_,module,exports){
"use strict";
var util = _dereq_("./util.js");
var isPrimitive = util.isPrimitive;
module.exports = function(Promise) {
var returner = function () {
return this;
};
var thrower = function () {
throw this;
};
var returnUndefined = function() {};
var throwUndefined = function() {
throw undefined;
};
var wrapper = function (value, action) {
if (action === 1) {
return function () {
throw value;
};
} else if (action === 2) {
return function () {
return value;
};
}
};
Promise.prototype["return"] =
Promise.prototype.thenReturn = function (value) {
if (value === undefined) return this.then(returnUndefined);
if (isPrimitive(value)) {
return this._then(
wrapper(value, 2),
undefined,
undefined,
undefined,
undefined
);
}
return this._then(returner, undefined, undefined, value, undefined);
};
Promise.prototype["throw"] =
Promise.prototype.thenThrow = function (reason) {
if (reason === undefined) return this.then(throwUndefined);
if (isPrimitive(reason)) {
return this._then(
wrapper(reason, 1),
undefined,
undefined,
undefined,
undefined
);
}
return this._then(thrower, undefined, undefined, reason, undefined);
};
};
},{"./util.js":38}],12:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise, INTERNAL) {
var PromiseReduce = Promise.reduce;
Promise.prototype.each = function (fn) {
return PromiseReduce(this, fn, null, INTERNAL);
};
Promise.each = function (promises, fn) {
return PromiseReduce(promises, fn, null, INTERNAL);
};
};
},{}],13:[function(_dereq_,module,exports){
"use strict";
var es5 = _dereq_("./es5.js");
var Objectfreeze = es5.freeze;
var util = _dereq_("./util.js");
var inherits = util.inherits;
var notEnumerableProp = util.notEnumerableProp;
function subError(nameProperty, defaultMessage) {
function SubError(message) {
if (!(this instanceof SubError)) return new SubError(message);
notEnumerableProp(this, "message",
typeof message === "string" ? message : defaultMessage);
notEnumerableProp(this, "name", nameProperty);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
} else {
Error.call(this);
}
}
inherits(SubError, Error);
return SubError;
}
var _TypeError, _RangeError;
var Warning = subError("Warning", "warning");
var CancellationError = subError("CancellationError", "cancellation error");
var TimeoutError = subError("TimeoutError", "timeout error");
var AggregateError = subError("AggregateError", "aggregate error");
try {
_TypeError = TypeError;
_RangeError = RangeError;
} catch(e) {
_TypeError = subError("TypeError", "type error");
_RangeError = subError("RangeError", "range error");
}
var methods = ("join pop push shift unshift slice filter forEach some " +
"every map indexOf lastIndexOf reduce reduceRight sort reverse").split(" ");
for (var i = 0; i < methods.length; ++i) {
if (typeof Array.prototype[methods[i]] === "function") {
AggregateError.prototype[methods[i]] = Array.prototype[methods[i]];
}
}
es5.defineProperty(AggregateError.prototype, "length", {
value: 0,
configurable: false,
writable: true,
enumerable: true
});
AggregateError.prototype["isOperational"] = true;
var level = 0;
AggregateError.prototype.toString = function() {
var indent = Array(level * 4 + 1).join(" ");
var ret = "\n" + indent + "AggregateError of:" + "\n";
level++;
indent = Array(level * 4 + 1).join(" ");
for (var i = 0; i < this.length; ++i) {
var str = this[i] === this ? "[Circular AggregateError]" : this[i] + "";
var lines = str.split("\n");
for (var j = 0; j < lines.length; ++j) {
lines[j] = indent + lines[j];
}
str = lines.join("\n");
ret += str + "\n";
}
level--;
return ret;
};
function OperationalError(message) {
if (!(this instanceof OperationalError))
return new OperationalError(message);
notEnumerableProp(this, "name", "OperationalError");
notEnumerableProp(this, "message", message);
this.cause = message;
this["isOperational"] = true;
if (message instanceof Error) {
notEnumerableProp(this, "message", message.message);
notEnumerableProp(this, "stack", message.stack);
} else if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
}
}
inherits(OperationalError, Error);
var errorTypes = Error["__BluebirdErrorTypes__"];
if (!errorTypes) {
errorTypes = Objectfreeze({
CancellationError: CancellationError,
TimeoutError: TimeoutError,
OperationalError: OperationalError,
RejectionError: OperationalError,
AggregateError: AggregateError
});
notEnumerableProp(Error, "__BluebirdErrorTypes__", errorTypes);
}
module.exports = {
Error: Error,
TypeError: _TypeError,
RangeError: _RangeError,
CancellationError: errorTypes.CancellationError,
OperationalError: errorTypes.OperationalError,
TimeoutError: errorTypes.TimeoutError,
AggregateError: errorTypes.AggregateError,
Warning: Warning
};
},{"./es5.js":14,"./util.js":38}],14:[function(_dereq_,module,exports){
var isES5 = (function(){
"use strict";
return this === undefined;
})();
if (isES5) {
module.exports = {
freeze: Object.freeze,
defineProperty: Object.defineProperty,
getDescriptor: Object.getOwnPropertyDescriptor,
keys: Object.keys,
names: Object.getOwnPropertyNames,
getPrototypeOf: Object.getPrototypeOf,
isArray: Array.isArray,
isES5: isES5,
propertyIsWritable: function(obj, prop) {
var descriptor = Object.getOwnPropertyDescriptor(obj, prop);
return !!(!descriptor || descriptor.writable || descriptor.set);
}
};
} else {
var has = {}.hasOwnProperty;
var str = {}.toString;
var proto = {}.constructor.prototype;
var ObjectKeys = function (o) {
var ret = [];
for (var key in o) {
if (has.call(o, key)) {
ret.push(key);
}
}
return ret;
};
var ObjectGetDescriptor = function(o, key) {
return {value: o[key]};
};
var ObjectDefineProperty = function (o, key, desc) {
o[key] = desc.value;
return o;
};
var ObjectFreeze = function (obj) {
return obj;
};
var ObjectGetPrototypeOf = function (obj) {
try {
return Object(obj).constructor.prototype;
}
catch (e) {
return proto;
}
};
var ArrayIsArray = function (obj) {
try {
return str.call(obj) === "[object Array]";
}
catch(e) {
return false;
}
};
module.exports = {
isArray: ArrayIsArray,
keys: ObjectKeys,
names: ObjectKeys,
defineProperty: ObjectDefineProperty,
getDescriptor: ObjectGetDescriptor,
freeze: ObjectFreeze,
getPrototypeOf: ObjectGetPrototypeOf,
isES5: isES5,
propertyIsWritable: function() {
return true;
}
};
}
},{}],15:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise, INTERNAL) {
var PromiseMap = Promise.map;
Promise.prototype.filter = function (fn, options) {
return PromiseMap(this, fn, options, INTERNAL);
};
Promise.filter = function (promises, fn, options) {
return PromiseMap(promises, fn, options, INTERNAL);
};
};
},{}],16:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise, NEXT_FILTER, tryConvertToPromise) {
var util = _dereq_("./util.js");
var isPrimitive = util.isPrimitive;
var thrower = util.thrower;
function returnThis() {
return this;
}
function throwThis() {
throw this;
}
function return$(r) {
return function() {
return r;
};
}
function throw$(r) {
return function() {
throw r;
};
}
function promisedFinally(ret, reasonOrValue, isFulfilled) {
var then;
if (isPrimitive(reasonOrValue)) {
then = isFulfilled ? return$(reasonOrValue) : throw$(reasonOrValue);
} else {
then = isFulfilled ? returnThis : throwThis;
}
return ret._then(then, thrower, undefined, reasonOrValue, undefined);
}
function finallyHandler(reasonOrValue) {
var promise = this.promise;
var handler = this.handler;
var ret = promise._isBound()
? handler.call(promise._boundValue())
: handler();
if (ret !== undefined) {
var maybePromise = tryConvertToPromise(ret, promise);
if (maybePromise instanceof Promise) {
maybePromise = maybePromise._target();
return promisedFinally(maybePromise, reasonOrValue,
promise.isFulfilled());
}
}
if (promise.isRejected()) {
NEXT_FILTER.e = reasonOrValue;
return NEXT_FILTER;
} else {
return reasonOrValue;
}
}
function tapHandler(value) {
var promise = this.promise;
var handler = this.handler;
var ret = promise._isBound()
? handler.call(promise._boundValue(), value)
: handler(value);
if (ret !== undefined) {
var maybePromise = tryConvertToPromise(ret, promise);
if (maybePromise instanceof Promise) {
maybePromise = maybePromise._target();
return promisedFinally(maybePromise, value, true);
}
}
return value;
}
Promise.prototype._passThroughHandler = function (handler, isFinally) {
if (typeof handler !== "function") return this.then();
var promiseAndHandler = {
promise: this,
handler: handler
};
return this._then(
isFinally ? finallyHandler : tapHandler,
isFinally ? finallyHandler : undefined, undefined,
promiseAndHandler, undefined);
};
Promise.prototype.lastly =
Promise.prototype["finally"] = function (handler) {
return this._passThroughHandler(handler, true);
};
Promise.prototype.tap = function (handler) {
return this._passThroughHandler(handler, false);
};
};
},{"./util.js":38}],17:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise,
apiRejection,
INTERNAL,
tryConvertToPromise) {
var errors = _dereq_("./errors.js");
var TypeError = errors.TypeError;
var util = _dereq_("./util.js");
var errorObj = util.errorObj;
var tryCatch = util.tryCatch;
var yieldHandlers = [];
function promiseFromYieldHandler(value, yieldHandlers, traceParent) {
for (var i = 0; i < yieldHandlers.length; ++i) {
traceParent._pushContext();
var result = tryCatch(yieldHandlers[i])(value);
traceParent._popContext();
if (result === errorObj) {
traceParent._pushContext();
var ret = Promise.reject(errorObj.e);
traceParent._popContext();
return ret;
}
var maybePromise = tryConvertToPromise(result, traceParent);
if (maybePromise instanceof Promise) return maybePromise;
}
return null;
}
function PromiseSpawn(generatorFunction, receiver, yieldHandler, stack) {
var promise = this._promise = new Promise(INTERNAL);
promise._captureStackTrace();
this._stack = stack;
this._generatorFunction = generatorFunction;
this._receiver = receiver;
this._generator = undefined;
this._yieldHandlers = typeof yieldHandler === "function"
? [yieldHandler].concat(yieldHandlers)
: yieldHandlers;
}
PromiseSpawn.prototype.promise = function () {
return this._promise;
};
PromiseSpawn.prototype._run = function () {
this._generator = this._generatorFunction.call(this._receiver);
this._receiver =
this._generatorFunction = undefined;
this._next(undefined);
};
PromiseSpawn.prototype._continue = function (result) {
if (result === errorObj) {
return this._promise._rejectCallback(result.e, false, true);
}
var value = result.value;
if (result.done === true) {
this._promise._resolveCallback(value);
} else {
var maybePromise = tryConvertToPromise(value, this._promise);
if (!(maybePromise instanceof Promise)) {
maybePromise =
promiseFromYieldHandler(maybePromise,
this._yieldHandlers,
this._promise);
if (maybePromise === null) {
this._throw(
new TypeError(
"A value %s was yielded that could not be treated as a promise\u000a\u000a See http://goo.gl/4Y4pDk\u000a\u000a".replace("%s", value) +
"From coroutine:\u000a" +
this._stack.split("\n").slice(1, -7).join("\n")
)
);
return;
}
}
maybePromise._then(
this._next,
this._throw,
undefined,
this,
null
);
}
};
PromiseSpawn.prototype._throw = function (reason) {
this._promise._attachExtraTrace(reason);
this._promise._pushContext();
var result = tryCatch(this._generator["throw"])
.call(this._generator, reason);
this._promise._popContext();
this._continue(result);
};
PromiseSpawn.prototype._next = function (value) {
this._promise._pushContext();
var result = tryCatch(this._generator.next).call(this._generator, value);
this._promise._popContext();
this._continue(result);
};
Promise.coroutine = function (generatorFunction, options) {
if (typeof generatorFunction !== "function") {
throw new TypeError("generatorFunction must be a function\u000a\u000a See http://goo.gl/6Vqhm0\u000a");
}
var yieldHandler = Object(options).yieldHandler;
var PromiseSpawn$ = PromiseSpawn;
var stack = new Error().stack;
return function () {
var generator = generatorFunction.apply(this, arguments);
var spawn = new PromiseSpawn$(undefined, undefined, yieldHandler,
stack);
spawn._generator = generator;
spawn._next(undefined);
return spawn.promise();
};
};
Promise.coroutine.addYieldHandler = function(fn) {
if (typeof fn !== "function") throw new TypeError("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a");
yieldHandlers.push(fn);
};
Promise.spawn = function (generatorFunction) {
if (typeof generatorFunction !== "function") {
return apiRejection("generatorFunction must be a function\u000a\u000a See http://goo.gl/6Vqhm0\u000a");
}
var spawn = new PromiseSpawn(generatorFunction, this);
var ret = spawn.promise();
spawn._run(Promise.spawn);
return ret;
};
};
},{"./errors.js":13,"./util.js":38}],18:[function(_dereq_,module,exports){
"use strict";
module.exports =
function(Promise, PromiseArray, tryConvertToPromise, INTERNAL) {
var util = _dereq_("./util.js");
var canEvaluate = util.canEvaluate;
var tryCatch = util.tryCatch;
var errorObj = util.errorObj;
var reject;
if (!true) {
if (canEvaluate) {
var thenCallback = function(i) {
return new Function("value", "holder", " \n\
'use strict'; \n\
holder.pIndex = value; \n\
holder.checkFulfillment(this); \n\
".replace(/Index/g, i));
};
var caller = function(count) {
var values = [];
for (var i = 1; i <= count; ++i) values.push("holder.p" + i);
return new Function("holder", " \n\
'use strict'; \n\
var callback = holder.fn; \n\
return callback(values); \n\
".replace(/values/g, values.join(", ")));
};
var thenCallbacks = [];
var callers = [undefined];
for (var i = 1; i <= 5; ++i) {
thenCallbacks.push(thenCallback(i));
callers.push(caller(i));
}
var Holder = function(total, fn) {
this.p1 = this.p2 = this.p3 = this.p4 = this.p5 = null;
this.fn = fn;
this.total = total;
this.now = 0;
};
Holder.prototype.callers = callers;
Holder.prototype.checkFulfillment = function(promise) {
var now = this.now;
now++;
var total = this.total;
if (now >= total) {
var handler = this.callers[total];
promise._pushContext();
var ret = tryCatch(handler)(this);
promise._popContext();
if (ret === errorObj) {
promise._rejectCallback(ret.e, false, true);
} else {
promise._resolveCallback(ret);
}
} else {
this.now = now;
}
};
var reject = function (reason) {
this._reject(reason);
};
}
}
Promise.join = function () {
var last = arguments.length - 1;
var fn;
if (last > 0 && typeof arguments[last] === "function") {
fn = arguments[last];
if (!true) {
if (last < 6 && canEvaluate) {
var ret = new Promise(INTERNAL);
ret._captureStackTrace();
var holder = new Holder(last, fn);
var callbacks = thenCallbacks;
for (var i = 0; i < last; ++i) {
var maybePromise = tryConvertToPromise(arguments[i], ret);
if (maybePromise instanceof Promise) {
maybePromise = maybePromise._target();
if (maybePromise._isPending()) {
maybePromise._then(callbacks[i], reject,
undefined, ret, holder);
} else if (maybePromise._isFulfilled()) {
callbacks[i].call(ret,
maybePromise._value(), holder);
} else {
ret._reject(maybePromise._reason());
}
} else {
callbacks[i].call(ret, maybePromise, holder);
}
}
return ret;
}
}
}
var $_len = arguments.length;var args = new Array($_len); for(var $_i = 0; $_i < $_len; ++$_i) {args[$_i] = arguments[$_i];}
if (fn) args.pop();
var ret = new PromiseArray(args).promise();
return fn !== undefined ? ret.spread(fn) : ret;
};
};
},{"./util.js":38}],19:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise,
PromiseArray,
apiRejection,
tryConvertToPromise,
INTERNAL) {
var getDomain = Promise._getDomain;
var async = _dereq_("./async.js");
var util = _dereq_("./util.js");
var tryCatch = util.tryCatch;
var errorObj = util.errorObj;
var PENDING = {};
var EMPTY_ARRAY = [];
function MappingPromiseArray(promises, fn, limit, _filter) {
this.constructor$(promises);
this._promise._captureStackTrace();
var domain = getDomain();
this._callback = domain === null ? fn : domain.bind(fn);
this._preservedValues = _filter === INTERNAL
? new Array(this.length())
: null;
this._limit = limit;
this._inFlight = 0;
this._queue = limit >= 1 ? [] : EMPTY_ARRAY;
async.invoke(init, this, undefined);
}
util.inherits(MappingPromiseArray, PromiseArray);
function init() {this._init$(undefined, -2);}
MappingPromiseArray.prototype._init = function () {};
MappingPromiseArray.prototype._promiseFulfilled = function (value, index) {
var values = this._values;
var length = this.length();
var preservedValues = this._preservedValues;
var limit = this._limit;
if (values[index] === PENDING) {
values[index] = value;
if (limit >= 1) {
this._inFlight--;
this._drainQueue();
if (this._isResolved()) return;
}
} else {
if (limit >= 1 && this._inFlight >= limit) {
values[index] = value;
this._queue.push(index);
return;
}
if (preservedValues !== null) preservedValues[index] = value;
var callback = this._callback;
var receiver = this._promise._boundValue();
this._promise._pushContext();
var ret = tryCatch(callback).call(receiver, value, index, length);
this._promise._popContext();
if (ret === errorObj) return this._reject(ret.e);
var maybePromise = tryConvertToPromise(ret, this._promise);
if (maybePromise instanceof Promise) {
maybePromise = maybePromise._target();
if (maybePromise._isPending()) {
if (limit >= 1) this._inFlight++;
values[index] = PENDING;
return maybePromise._proxyPromiseArray(this, index);
} else if (maybePromise._isFulfilled()) {
ret = maybePromise._value();
} else {
return this._reject(maybePromise._reason());
}
}
values[index] = ret;
}
var totalResolved = ++this._totalResolved;
if (totalResolved >= length) {
if (preservedValues !== null) {
this._filter(values, preservedValues);
} else {
this._resolve(values);
}
}
};
MappingPromiseArray.prototype._drainQueue = function () {
var queue = this._queue;
var limit = this._limit;
var values = this._values;
while (queue.length > 0 && this._inFlight < limit) {
if (this._isResolved()) return;
var index = queue.pop();
this._promiseFulfilled(values[index], index);
}
};
MappingPromiseArray.prototype._filter = function (booleans, values) {
var len = values.length;
var ret = new Array(len);
var j = 0;
for (var i = 0; i < len; ++i) {
if (booleans[i]) ret[j++] = values[i];
}
ret.length = j;
this._resolve(ret);
};
MappingPromiseArray.prototype.preservedValues = function () {
return this._preservedValues;
};
function map(promises, fn, options, _filter) {
var limit = typeof options === "object" && options !== null
? options.concurrency
: 0;
limit = typeof limit === "number" &&
isFinite(limit) && limit >= 1 ? limit : 0;
return new MappingPromiseArray(promises, fn, limit, _filter);
}
Promise.prototype.map = function (fn, options) {
if (typeof fn !== "function") return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a");
return map(this, fn, options, null).promise();
};
Promise.map = function (promises, fn, options, _filter) {
if (typeof fn !== "function") return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a");
return map(promises, fn, options, _filter).promise();
};
};
},{"./async.js":2,"./util.js":38}],20:[function(_dereq_,module,exports){
"use strict";
module.exports =
function(Promise, INTERNAL, tryConvertToPromise, apiRejection) {
var util = _dereq_("./util.js");
var tryCatch = util.tryCatch;
Promise.method = function (fn) {
if (typeof fn !== "function") {
throw new Promise.TypeError("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a");
}
return function () {
var ret = new Promise(INTERNAL);
ret._captureStackTrace();
ret._pushContext();
var value = tryCatch(fn).apply(this, arguments);
ret._popContext();
ret._resolveFromSyncValue(value);
return ret;
};
};
Promise.attempt = Promise["try"] = function (fn, args, ctx) {
if (typeof fn !== "function") {
return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a");
}
var ret = new Promise(INTERNAL);
ret._captureStackTrace();
ret._pushContext();
var value = util.isArray(args)
? tryCatch(fn).apply(ctx, args)
: tryCatch(fn).call(ctx, args);
ret._popContext();
ret._resolveFromSyncValue(value);
return ret;
};
Promise.prototype._resolveFromSyncValue = function (value) {
if (value === util.errorObj) {
this._rejectCallback(value.e, false, true);
} else {
this._resolveCallback(value, true);
}
};
};
},{"./util.js":38}],21:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise) {
var util = _dereq_("./util.js");
var async = _dereq_("./async.js");
var tryCatch = util.tryCatch;
var errorObj = util.errorObj;
function spreadAdapter(val, nodeback) {
var promise = this;
if (!util.isArray(val)) return successAdapter.call(promise, val, nodeback);
var ret =
tryCatch(nodeback).apply(promise._boundValue(), [null].concat(val));
if (ret === errorObj) {
async.throwLater(ret.e);
}
}
function successAdapter(val, nodeback) {
var promise = this;
var receiver = promise._boundValue();
var ret = val === undefined
? tryCatch(nodeback).call(receiver, null)
: tryCatch(nodeback).call(receiver, null, val);
if (ret === errorObj) {
async.throwLater(ret.e);
}
}
function errorAdapter(reason, nodeback) {
var promise = this;
if (!reason) {
var target = promise._target();
var newReason = target._getCarriedStackTrace();
newReason.cause = reason;
reason = newReason;
}
var ret = tryCatch(nodeback).call(promise._boundValue(), reason);
if (ret === errorObj) {
async.throwLater(ret.e);
}
}
Promise.prototype.asCallback =
Promise.prototype.nodeify = function (nodeback, options) {
if (typeof nodeback == "function") {
var adapter = successAdapter;
if (options !== undefined && Object(options).spread) {
adapter = spreadAdapter;
}
this._then(
adapter,
errorAdapter,
undefined,
this,
nodeback
);
}
return this;
};
};
},{"./async.js":2,"./util.js":38}],22:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise, PromiseArray) {
var util = _dereq_("./util.js");
var async = _dereq_("./async.js");
var tryCatch = util.tryCatch;
var errorObj = util.errorObj;
Promise.prototype.progressed = function (handler) {
return this._then(undefined, undefined, handler, undefined, undefined);
};
Promise.prototype._progress = function (progressValue) {
if (this._isFollowingOrFulfilledOrRejected()) return;
this._target()._progressUnchecked(progressValue);
};
Promise.prototype._progressHandlerAt = function (index) {
return index === 0
? this._progressHandler0
: this[(index << 2) + index - 5 + 2];
};
Promise.prototype._doProgressWith = function (progression) {
var progressValue = progression.value;
var handler = progression.handler;
var promise = progression.promise;
var receiver = progression.receiver;
var ret = tryCatch(handler).call(receiver, progressValue);
if (ret === errorObj) {
if (ret.e != null &&
ret.e.name !== "StopProgressPropagation") {
var trace = util.canAttachTrace(ret.e)
? ret.e : new Error(util.toString(ret.e));
promise._attachExtraTrace(trace);
promise._progress(ret.e);
}
} else if (ret instanceof Promise) {
ret._then(promise._progress, null, null, promise, undefined);
} else {
promise._progress(ret);
}
};
Promise.prototype._progressUnchecked = function (progressValue) {
var len = this._length();
var progress = this._progress;
for (var i = 0; i < len; i++) {
var handler = this._progressHandlerAt(i);
var promise = this._promiseAt(i);
if (!(promise instanceof Promise)) {
var receiver = this._receiverAt(i);
if (typeof handler === "function") {
handler.call(receiver, progressValue, promise);
} else if (receiver instanceof PromiseArray &&
!receiver._isResolved()) {
receiver._promiseProgressed(progressValue, promise);
}
continue;
}
if (typeof handler === "function") {
async.invoke(this._doProgressWith, this, {
handler: handler,
promise: promise,
receiver: this._receiverAt(i),
value: progressValue
});
} else {
async.invoke(progress, promise, progressValue);
}
}
};
};
},{"./async.js":2,"./util.js":38}],23:[function(_dereq_,module,exports){
"use strict";
module.exports = function() {
var makeSelfResolutionError = function () {
return new TypeError("circular promise resolution chain\u000a\u000a See http://goo.gl/LhFpo0\u000a");
};
var reflect = function() {
return new Promise.PromiseInspection(this._target());
};
var apiRejection = function(msg) {
return Promise.reject(new TypeError(msg));
};
var util = _dereq_("./util.js");
var getDomain;
if (util.isNode) {
getDomain = function() {
var ret = process.domain;
if (ret === undefined) ret = null;
return ret;
};
} else {
getDomain = function() {
return null;
};
}
util.notEnumerableProp(Promise, "_getDomain", getDomain);
var async = _dereq_("./async.js");
var errors = _dereq_("./errors.js");
var TypeError = Promise.TypeError = errors.TypeError;
Promise.RangeError = errors.RangeError;
Promise.CancellationError = errors.CancellationError;
Promise.TimeoutError = errors.TimeoutError;
Promise.OperationalError = errors.OperationalError;
Promise.RejectionError = errors.OperationalError;
Promise.AggregateError = errors.AggregateError;
var INTERNAL = function(){};
var APPLY = {};
var NEXT_FILTER = {e: null};
var tryConvertToPromise = _dereq_("./thenables.js")(Promise, INTERNAL);
var PromiseArray =
_dereq_("./promise_array.js")(Promise, INTERNAL,
tryConvertToPromise, apiRejection);
var CapturedTrace = _dereq_("./captured_trace.js")();
var isDebugging = _dereq_("./debuggability.js")(Promise, CapturedTrace);
/*jshint unused:false*/
var createContext =
_dereq_("./context.js")(Promise, CapturedTrace, isDebugging);
var CatchFilter = _dereq_("./catch_filter.js")(NEXT_FILTER);
var PromiseResolver = _dereq_("./promise_resolver.js");
var nodebackForPromise = PromiseResolver._nodebackForPromise;
var errorObj = util.errorObj;
var tryCatch = util.tryCatch;
function Promise(resolver) {
if (typeof resolver !== "function") {
throw new TypeError("the promise constructor requires a resolver function\u000a\u000a See http://goo.gl/EC22Yn\u000a");
}
if (this.constructor !== Promise) {
throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/KsIlge\u000a");
}
this._bitField = 0;
this._fulfillmentHandler0 = undefined;
this._rejectionHandler0 = undefined;
this._progressHandler0 = undefined;
this._promise0 = undefined;
this._receiver0 = undefined;
this._settledValue = undefined;
if (resolver !== INTERNAL) this._resolveFromResolver(resolver);
}
Promise.prototype.toString = function () {
return "[object Promise]";
};
Promise.prototype.caught = Promise.prototype["catch"] = function (fn) {
var len = arguments.length;
if (len > 1) {
var catchInstances = new Array(len - 1),
j = 0, i;
for (i = 0; i < len - 1; ++i) {
var item = arguments[i];
if (typeof item === "function") {
catchInstances[j++] = item;
} else {
return Promise.reject(
new TypeError("Catch filter must inherit from Error or be a simple predicate function\u000a\u000a See http://goo.gl/o84o68\u000a"));
}
}
catchInstances.length = j;
fn = arguments[i];
var catchFilter = new CatchFilter(catchInstances, fn, this);
return this._then(undefined, catchFilter.doFilter, undefined,
catchFilter, undefined);
}
return this._then(undefined, fn, undefined, undefined, undefined);
};
Promise.prototype.reflect = function () {
return this._then(reflect, reflect, undefined, this, undefined);
};
Promise.prototype.then = function (didFulfill, didReject, didProgress) {
if (isDebugging() && arguments.length > 0 &&
typeof didFulfill !== "function" &&
typeof didReject !== "function") {
var msg = ".then() only accepts functions but was passed: " +
util.classString(didFulfill);
if (arguments.length > 1) {
msg += ", " + util.classString(didReject);
}
this._warn(msg);
}
return this._then(didFulfill, didReject, didProgress,
undefined, undefined);
};
Promise.prototype.done = function (didFulfill, didReject, didProgress) {
var promise = this._then(didFulfill, didReject, didProgress,
undefined, undefined);
promise._setIsFinal();
};
Promise.prototype.spread = function (didFulfill, didReject) {
return this.all()._then(didFulfill, didReject, undefined, APPLY, undefined);
};
Promise.prototype.isCancellable = function () {
return !this.isResolved() &&
this._cancellable();
};
Promise.prototype.toJSON = function () {
var ret = {
isFulfilled: false,
isRejected: false,
fulfillmentValue: undefined,
rejectionReason: undefined
};
if (this.isFulfilled()) {
ret.fulfillmentValue = this.value();
ret.isFulfilled = true;
} else if (this.isRejected()) {
ret.rejectionReason = this.reason();
ret.isRejected = true;
}
return ret;
};
Promise.prototype.all = function () {
return new PromiseArray(this).promise();
};
Promise.prototype.error = function (fn) {
return this.caught(util.originatesFromRejection, fn);
};
Promise.is = function (val) {
return val instanceof Promise;
};
Promise.fromNode = function(fn) {
var ret = new Promise(INTERNAL);
var result = tryCatch(fn)(nodebackForPromise(ret));
if (result === errorObj) {
ret._rejectCallback(result.e, true, true);
}
return ret;
};
Promise.all = function (promises) {
return new PromiseArray(promises).promise();
};
Promise.defer = Promise.pending = function () {
var promise = new Promise(INTERNAL);
return new PromiseResolver(promise);
};
Promise.cast = function (obj) {
var ret = tryConvertToPromise(obj);
if (!(ret instanceof Promise)) {
var val = ret;
ret = new Promise(INTERNAL);
ret._fulfillUnchecked(val);
}
return ret;
};
Promise.resolve = Promise.fulfilled = Promise.cast;
Promise.reject = Promise.rejected = function (reason) {
var ret = new Promise(INTERNAL);
ret._captureStackTrace();
ret._rejectCallback(reason, true);
return ret;
};
Promise.setScheduler = function(fn) {
if (typeof fn !== "function") throw new TypeError("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a");
var prev = async._schedule;
async._schedule = fn;
return prev;
};
Promise.prototype._then = function (
didFulfill,
didReject,
didProgress,
receiver,
internalData
) {
var haveInternalData = internalData !== undefined;
var ret = haveInternalData ? internalData : new Promise(INTERNAL);
if (!haveInternalData) {
ret._propagateFrom(this, 4 | 1);
ret._captureStackTrace();
}
var target = this._target();
if (target !== this) {
if (receiver === undefined) receiver = this._boundTo;
if (!haveInternalData) ret._setIsMigrated();
}
var callbackIndex = target._addCallbacks(didFulfill,
didReject,
didProgress,
ret,
receiver,
getDomain());
if (target._isResolved() && !target._isSettlePromisesQueued()) {
async.invoke(
target._settlePromiseAtPostResolution, target, callbackIndex);
}
return ret;
};
Promise.prototype._settlePromiseAtPostResolution = function (index) {
if (this._isRejectionUnhandled()) this._unsetRejectionIsUnhandled();
this._settlePromiseAt(index);
};
Promise.prototype._length = function () {
return this._bitField & 131071;
};
Promise.prototype._isFollowingOrFulfilledOrRejected = function () {
return (this._bitField & 939524096) > 0;
};
Promise.prototype._isFollowing = function () {
return (this._bitField & 536870912) === 536870912;
};
Promise.prototype._setLength = function (len) {
this._bitField = (this._bitField & -131072) |
(len & 131071);
};
Promise.prototype._setFulfilled = function () {
this._bitField = this._bitField | 268435456;
};
Promise.prototype._setRejected = function () {
this._bitField = this._bitField | 134217728;
};
Promise.prototype._setFollowing = function () {
this._bitField = this._bitField | 536870912;
};
Promise.prototype._setIsFinal = function () {
this._bitField = this._bitField | 33554432;
};
Promise.prototype._isFinal = function () {
return (this._bitField & 33554432) > 0;
};
Promise.prototype._cancellable = function () {
return (this._bitField & 67108864) > 0;
};
Promise.prototype._setCancellable = function () {
this._bitField = this._bitField | 67108864;
};
Promise.prototype._unsetCancellable = function () {
this._bitField = this._bitField & (~67108864);
};
Promise.prototype._setIsMigrated = function () {
this._bitField = this._bitField | 4194304;
};
Promise.prototype._unsetIsMigrated = function () {
this._bitField = this._bitField & (~4194304);
};
Promise.prototype._isMigrated = function () {
return (this._bitField & 4194304) > 0;
};
Promise.prototype._receiverAt = function (index) {
var ret = index === 0
? this._receiver0
: this[
index * 5 - 5 + 4];
if (ret === undefined && this._isBound()) {
return this._boundValue();
}
return ret;
};
Promise.prototype._promiseAt = function (index) {
return index === 0
? this._promise0
: this[index * 5 - 5 + 3];
};
Promise.prototype._fulfillmentHandlerAt = function (index) {
return index === 0
? this._fulfillmentHandler0
: this[index * 5 - 5 + 0];
};
Promise.prototype._rejectionHandlerAt = function (index) {
return index === 0
? this._rejectionHandler0
: this[index * 5 - 5 + 1];
};
Promise.prototype._boundValue = function() {
var ret = this._boundTo;
if (ret !== undefined) {
if (ret instanceof Promise) {
if (ret.isFulfilled()) {
return ret.value();
} else {
return undefined;
}
}
}
return ret;
};
Promise.prototype._migrateCallbacks = function (follower, index) {
var fulfill = follower._fulfillmentHandlerAt(index);
var reject = follower._rejectionHandlerAt(index);
var progress = follower._progressHandlerAt(index);
var promise = follower._promiseAt(index);
var receiver = follower._receiverAt(index);
if (promise instanceof Promise) promise._setIsMigrated();
this._addCallbacks(fulfill, reject, progress, promise, receiver, null);
};
Promise.prototype._addCallbacks = function (
fulfill,
reject,
progress,
promise,
receiver,
domain
) {
var index = this._length();
if (index >= 131071 - 5) {
index = 0;
this._setLength(0);
}
if (index === 0) {
this._promise0 = promise;
if (receiver !== undefined) this._receiver0 = receiver;
if (typeof fulfill === "function" && !this._isCarryingStackTrace()) {
this._fulfillmentHandler0 =
domain === null ? fulfill : domain.bind(fulfill);
}
if (typeof reject === "function") {
this._rejectionHandler0 =
domain === null ? reject : domain.bind(reject);
}
if (typeof progress === "function") {
this._progressHandler0 =
domain === null ? progress : domain.bind(progress);
}
} else {
var base = index * 5 - 5;
this[base + 3] = promise;
this[base + 4] = receiver;
if (typeof fulfill === "function") {
this[base + 0] =
domain === null ? fulfill : domain.bind(fulfill);
}
if (typeof reject === "function") {
this[base + 1] =
domain === null ? reject : domain.bind(reject);
}
if (typeof progress === "function") {
this[base + 2] =
domain === null ? progress : domain.bind(progress);
}
}
this._setLength(index + 1);
return index;
};
Promise.prototype._setProxyHandlers = function (receiver, promiseSlotValue) {
var index = this._length();
if (index >= 131071 - 5) {
index = 0;
this._setLength(0);
}
if (index === 0) {
this._promise0 = promiseSlotValue;
this._receiver0 = receiver;
} else {
var base = index * 5 - 5;
this[base + 3] = promiseSlotValue;
this[base + 4] = receiver;
}
this._setLength(index + 1);
};
Promise.prototype._proxyPromiseArray = function (promiseArray, index) {
this._setProxyHandlers(promiseArray, index);
};
Promise.prototype._resolveCallback = function(value, shouldBind) {
if (this._isFollowingOrFulfilledOrRejected()) return;
if (value === this)
return this._rejectCallback(makeSelfResolutionError(), false, true);
var maybePromise = tryConvertToPromise(value, this);
if (!(maybePromise instanceof Promise)) return this._fulfill(value);
var propagationFlags = 1 | (shouldBind ? 4 : 0);
this._propagateFrom(maybePromise, propagationFlags);
var promise = maybePromise._target();
if (promise._isPending()) {
var len = this._length();
for (var i = 0; i < len; ++i) {
promise._migrateCallbacks(this, i);
}
this._setFollowing();
this._setLength(0);
this._setFollowee(promise);
} else if (promise._isFulfilled()) {
this._fulfillUnchecked(promise._value());
} else {
this._rejectUnchecked(promise._reason(),
promise._getCarriedStackTrace());
}
};
Promise.prototype._rejectCallback =
function(reason, synchronous, shouldNotMarkOriginatingFromRejection) {
if (!shouldNotMarkOriginatingFromRejection) {
util.markAsOriginatingFromRejection(reason);
}
var trace = util.ensureErrorObject(reason);
var hasStack = trace === reason;
this._attachExtraTrace(trace, synchronous ? hasStack : false);
this._reject(reason, hasStack ? undefined : trace);
};
Promise.prototype._resolveFromResolver = function (resolver) {
var promise = this;
this._captureStackTrace();
this._pushContext();
var synchronous = true;
var r = tryCatch(resolver)(function(value) {
if (promise === null) return;
promise._resolveCallback(value);
promise = null;
}, function (reason) {
if (promise === null) return;
promise._rejectCallback(reason, synchronous);
promise = null;
});
synchronous = false;
this._popContext();
if (r !== undefined && r === errorObj && promise !== null) {
promise._rejectCallback(r.e, true, true);
promise = null;
}
};
Promise.prototype._settlePromiseFromHandler = function (
handler, receiver, value, promise
) {
if (promise._isRejected()) return;
promise._pushContext();
var x;
if (receiver === APPLY && !this._isRejected()) {
x = tryCatch(handler).apply(this._boundValue(), value);
} else {
x = tryCatch(handler).call(receiver, value);
}
promise._popContext();
if (x === errorObj || x === promise || x === NEXT_FILTER) {
var err = x === promise ? makeSelfResolutionError() : x.e;
promise._rejectCallback(err, false, true);
} else {
promise._resolveCallback(x);
}
};
Promise.prototype._target = function() {
var ret = this;
while (ret._isFollowing()) ret = ret._followee();
return ret;
};
Promise.prototype._followee = function() {
return this._rejectionHandler0;
};
Promise.prototype._setFollowee = function(promise) {
this._rejectionHandler0 = promise;
};
Promise.prototype._cleanValues = function () {
if (this._cancellable()) {
this._cancellationParent = undefined;
}
};
Promise.prototype._propagateFrom = function (parent, flags) {
if ((flags & 1) > 0 && parent._cancellable()) {
this._setCancellable();
this._cancellationParent = parent;
}
if ((flags & 4) > 0 && parent._isBound()) {
this._setBoundTo(parent._boundTo);
}
};
Promise.prototype._fulfill = function (value) {
if (this._isFollowingOrFulfilledOrRejected()) return;
this._fulfillUnchecked(value);
};
Promise.prototype._reject = function (reason, carriedStackTrace) {
if (this._isFollowingOrFulfilledOrRejected()) return;
this._rejectUnchecked(reason, carriedStackTrace);
};
Promise.prototype._settlePromiseAt = function (index) {
var promise = this._promiseAt(index);
var isPromise = promise instanceof Promise;
if (isPromise && promise._isMigrated()) {
promise._unsetIsMigrated();
return async.invoke(this._settlePromiseAt, this, index);
}
var handler = this._isFulfilled()
? this._fulfillmentHandlerAt(index)
: this._rejectionHandlerAt(index);
var carriedStackTrace =
this._isCarryingStackTrace() ? this._getCarriedStackTrace() : undefined;
var value = this._settledValue;
var receiver = this._receiverAt(index);
this._clearCallbackDataAtIndex(index);
if (typeof handler === "function") {
if (!isPromise) {
handler.call(receiver, value, promise);
} else {
this._settlePromiseFromHandler(handler, receiver, value, promise);
}
} else if (receiver instanceof PromiseArray) {
if (!receiver._isResolved()) {
if (this._isFulfilled()) {
receiver._promiseFulfilled(value, promise);
}
else {
receiver._promiseRejected(value, promise);
}
}
} else if (isPromise) {
if (this._isFulfilled()) {
promise._fulfill(value);
} else {
promise._reject(value, carriedStackTrace);
}
}
if (index >= 4 && (index & 31) === 4)
async.invokeLater(this._setLength, this, 0);
};
Promise.prototype._clearCallbackDataAtIndex = function(index) {
if (index === 0) {
if (!this._isCarryingStackTrace()) {
this._fulfillmentHandler0 = undefined;
}
this._rejectionHandler0 =
this._progressHandler0 =
this._receiver0 =
this._promise0 = undefined;
} else {
var base = index * 5 - 5;
this[base + 3] =
this[base + 4] =
this[base + 0] =
this[base + 1] =
this[base + 2] = undefined;
}
};
Promise.prototype._isSettlePromisesQueued = function () {
return (this._bitField &
-1073741824) === -1073741824;
};
Promise.prototype._setSettlePromisesQueued = function () {
this._bitField = this._bitField | -1073741824;
};
Promise.prototype._unsetSettlePromisesQueued = function () {
this._bitField = this._bitField & (~-1073741824);
};
Promise.prototype._queueSettlePromises = function() {
async.settlePromises(this);
this._setSettlePromisesQueued();
};
Promise.prototype._fulfillUnchecked = function (value) {
if (value === this) {
var err = makeSelfResolutionError();
this._attachExtraTrace(err);
return this._rejectUnchecked(err, undefined);
}
this._setFulfilled();
this._settledValue = value;
this._cleanValues();
if (this._length() > 0) {
this._queueSettlePromises();
}
};
Promise.prototype._rejectUncheckedCheckError = function (reason) {
var trace = util.ensureErrorObject(reason);
this._rejectUnchecked(reason, trace === reason ? undefined : trace);
};
Promise.prototype._rejectUnchecked = function (reason, trace) {
if (reason === this) {
var err = makeSelfResolutionError();
this._attachExtraTrace(err);
return this._rejectUnchecked(err);
}
this._setRejected();
this._settledValue = reason;
this._cleanValues();
if (this._isFinal()) {
async.throwLater(function(e) {
if ("stack" in e) {
async.invokeFirst(
CapturedTrace.unhandledRejection, undefined, e);
}
throw e;
}, trace === undefined ? reason : trace);
return;
}
if (trace !== undefined && trace !== reason) {
this._setCarriedStackTrace(trace);
}
if (this._length() > 0) {
this._queueSettlePromises();
} else {
this._ensurePossibleRejectionHandled();
}
};
Promise.prototype._settlePromises = function () {
this._unsetSettlePromisesQueued();
var len = this._length();
for (var i = 0; i < len; i++) {
this._settlePromiseAt(i);
}
};
util.notEnumerableProp(Promise,
"_makeSelfResolutionError",
makeSelfResolutionError);
_dereq_("./progress.js")(Promise, PromiseArray);
_dereq_("./method.js")(Promise, INTERNAL, tryConvertToPromise, apiRejection);
_dereq_("./bind.js")(Promise, INTERNAL, tryConvertToPromise);
_dereq_("./finally.js")(Promise, NEXT_FILTER, tryConvertToPromise);
_dereq_("./direct_resolve.js")(Promise);
_dereq_("./synchronous_inspection.js")(Promise);
_dereq_("./join.js")(Promise, PromiseArray, tryConvertToPromise, INTERNAL);
Promise.Promise = Promise;
_dereq_('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL);
_dereq_('./cancel.js')(Promise);
_dereq_('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext);
_dereq_('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise);
_dereq_('./nodeify.js')(Promise);
_dereq_('./call_get.js')(Promise);
_dereq_('./props.js')(Promise, PromiseArray, tryConvertToPromise, apiRejection);
_dereq_('./race.js')(Promise, INTERNAL, tryConvertToPromise, apiRejection);
_dereq_('./reduce.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL);
_dereq_('./settle.js')(Promise, PromiseArray);
_dereq_('./some.js')(Promise, PromiseArray, apiRejection);
_dereq_('./promisify.js')(Promise, INTERNAL);
_dereq_('./any.js')(Promise);
_dereq_('./each.js')(Promise, INTERNAL);
_dereq_('./timers.js')(Promise, INTERNAL);
_dereq_('./filter.js')(Promise, INTERNAL);
util.toFastProperties(Promise);
util.toFastProperties(Promise.prototype);
function fillTypes(value) {
var p = new Promise(INTERNAL);
p._fulfillmentHandler0 = value;
p._rejectionHandler0 = value;
p._progressHandler0 = value;
p._promise0 = value;
p._receiver0 = value;
p._settledValue = value;
}
// Complete slack tracking, opt out of field-type tracking and
// stabilize map
fillTypes({a: 1});
fillTypes({b: 2});
fillTypes({c: 3});
fillTypes(1);
fillTypes(function(){});
fillTypes(undefined);
fillTypes(false);
fillTypes(new Promise(INTERNAL));
CapturedTrace.setBounds(async.firstLineError, util.lastLineError);
return Promise;
};
},{"./any.js":1,"./async.js":2,"./bind.js":3,"./call_get.js":5,"./cancel.js":6,"./captured_trace.js":7,"./catch_filter.js":8,"./context.js":9,"./debuggability.js":10,"./direct_resolve.js":11,"./each.js":12,"./errors.js":13,"./filter.js":15,"./finally.js":16,"./generators.js":17,"./join.js":18,"./map.js":19,"./method.js":20,"./nodeify.js":21,"./progress.js":22,"./promise_array.js":24,"./promise_resolver.js":25,"./promisify.js":26,"./props.js":27,"./race.js":29,"./reduce.js":30,"./settle.js":32,"./some.js":33,"./synchronous_inspection.js":34,"./thenables.js":35,"./timers.js":36,"./using.js":37,"./util.js":38}],24:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise, INTERNAL, tryConvertToPromise,
apiRejection) {
var util = _dereq_("./util.js");
var isArray = util.isArray;
function toResolutionValue(val) {
switch(val) {
case -2: return [];
case -3: return {};
}
}
function PromiseArray(values) {
var promise = this._promise = new Promise(INTERNAL);
var parent;
if (values instanceof Promise) {
parent = values;
promise._propagateFrom(parent, 1 | 4);
}
this._values = values;
this._length = 0;
this._totalResolved = 0;
this._init(undefined, -2);
}
PromiseArray.prototype.length = function () {
return this._length;
};
PromiseArray.prototype.promise = function () {
return this._promise;
};
PromiseArray.prototype._init = function init(_, resolveValueIfEmpty) {
var values = tryConvertToPromise(this._values, this._promise);
if (values instanceof Promise) {
values = values._target();
this._values = values;
if (values._isFulfilled()) {
values = values._value();
if (!isArray(values)) {
var err = new Promise.TypeError("expecting an array, a promise or a thenable\u000a\u000a See http://goo.gl/s8MMhc\u000a");
this.__hardReject__(err);
return;
}
} else if (values._isPending()) {
values._then(
init,
this._reject,
undefined,
this,
resolveValueIfEmpty
);
return;
} else {
this._reject(values._reason());
return;
}
} else if (!isArray(values)) {
this._promise._reject(apiRejection("expecting an array, a promise or a thenable\u000a\u000a See http://goo.gl/s8MMhc\u000a")._reason());
return;
}
if (values.length === 0) {
if (resolveValueIfEmpty === -5) {
this._resolveEmptyArray();
}
else {
this._resolve(toResolutionValue(resolveValueIfEmpty));
}
return;
}
var len = this.getActualLength(values.length);
this._length = len;
this._values = this.shouldCopyValues() ? new Array(len) : this._values;
var promise = this._promise;
for (var i = 0; i < len; ++i) {
var isResolved = this._isResolved();
var maybePromise = tryConvertToPromise(values[i], promise);
if (maybePromise instanceof Promise) {
maybePromise = maybePromise._target();
if (isResolved) {
maybePromise._ignoreRejections();
} else if (maybePromise._isPending()) {
maybePromise._proxyPromiseArray(this, i);
} else if (maybePromise._isFulfilled()) {
this._promiseFulfilled(maybePromise._value(), i);
} else {
this._promiseRejected(maybePromise._reason(), i);
}
} else if (!isResolved) {
this._promiseFulfilled(maybePromise, i);
}
}
};
PromiseArray.prototype._isResolved = function () {
return this._values === null;
};
PromiseArray.prototype._resolve = function (value) {
this._values = null;
this._promise._fulfill(value);
};
PromiseArray.prototype.__hardReject__ =
PromiseArray.prototype._reject = function (reason) {
this._values = null;
this._promise._rejectCallback(reason, false, true);
};
PromiseArray.prototype._promiseProgressed = function (progressValue, index) {
this._promise._progress({
index: index,
value: progressValue
});
};
PromiseArray.prototype._promiseFulfilled = function (value, index) {
this._values[index] = value;
var totalResolved = ++this._totalResolved;
if (totalResolved >= this._length) {
this._resolve(this._values);
}
};
PromiseArray.prototype._promiseRejected = function (reason, index) {
this._totalResolved++;
this._reject(reason);
};
PromiseArray.prototype.shouldCopyValues = function () {
return true;
};
PromiseArray.prototype.getActualLength = function (len) {
return len;
};
return PromiseArray;
};
},{"./util.js":38}],25:[function(_dereq_,module,exports){
"use strict";
var util = _dereq_("./util.js");
var maybeWrapAsError = util.maybeWrapAsError;
var errors = _dereq_("./errors.js");
var TimeoutError = errors.TimeoutError;
var OperationalError = errors.OperationalError;
var haveGetters = util.haveGetters;
var es5 = _dereq_("./es5.js");
function isUntypedError(obj) {
return obj instanceof Error &&
es5.getPrototypeOf(obj) === Error.prototype;
}
var rErrorKey = /^(?:name|message|stack|cause)$/;
function wrapAsOperationalError(obj) {
var ret;
if (isUntypedError(obj)) {
ret = new OperationalError(obj);
ret.name = obj.name;
ret.message = obj.message;
ret.stack = obj.stack;
var keys = es5.keys(obj);
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
if (!rErrorKey.test(key)) {
ret[key] = obj[key];
}
}
return ret;
}
util.markAsOriginatingFromRejection(obj);
return obj;
}
function nodebackForPromise(promise) {
return function(err, value) {
if (promise === null) return;
if (err) {
var wrapped = wrapAsOperationalError(maybeWrapAsError(err));
promise._attachExtraTrace(wrapped);
promise._reject(wrapped);
} else if (arguments.length > 2) {
var $_len = arguments.length;var args = new Array($_len - 1); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];}
promise._fulfill(args);
} else {
promise._fulfill(value);
}
promise = null;
};
}
var PromiseResolver;
if (!haveGetters) {
PromiseResolver = function (promise) {
this.promise = promise;
this.asCallback = nodebackForPromise(promise);
this.callback = this.asCallback;
};
}
else {
PromiseResolver = function (promise) {
this.promise = promise;
};
}
if (haveGetters) {
var prop = {
get: function() {
return nodebackForPromise(this.promise);
}
};
es5.defineProperty(PromiseResolver.prototype, "asCallback", prop);
es5.defineProperty(PromiseResolver.prototype, "callback", prop);
}
PromiseResolver._nodebackForPromise = nodebackForPromise;
PromiseResolver.prototype.toString = function () {
return "[object PromiseResolver]";
};
PromiseResolver.prototype.resolve =
PromiseResolver.prototype.fulfill = function (value) {
if (!(this instanceof PromiseResolver)) {
throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\u000a\u000a See http://goo.gl/sdkXL9\u000a");
}
this.promise._resolveCallback(value);
};
PromiseResolver.prototype.reject = function (reason) {
if (!(this instanceof PromiseResolver)) {
throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\u000a\u000a See http://goo.gl/sdkXL9\u000a");
}
this.promise._rejectCallback(reason);
};
PromiseResolver.prototype.progress = function (value) {
if (!(this instanceof PromiseResolver)) {
throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\u000a\u000a See http://goo.gl/sdkXL9\u000a");
}
this.promise._progress(value);
};
PromiseResolver.prototype.cancel = function (err) {
this.promise.cancel(err);
};
PromiseResolver.prototype.timeout = function () {
this.reject(new TimeoutError("timeout"));
};
PromiseResolver.prototype.isResolved = function () {
return this.promise.isResolved();
};
PromiseResolver.prototype.toJSON = function () {
return this.promise.toJSON();
};
module.exports = PromiseResolver;
},{"./errors.js":13,"./es5.js":14,"./util.js":38}],26:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise, INTERNAL) {
var THIS = {};
var util = _dereq_("./util.js");
var nodebackForPromise = _dereq_("./promise_resolver.js")
._nodebackForPromise;
var withAppended = util.withAppended;
var maybeWrapAsError = util.maybeWrapAsError;
var canEvaluate = util.canEvaluate;
var TypeError = _dereq_("./errors").TypeError;
var defaultSuffix = "Async";
var defaultPromisified = {__isPromisified__: true};
var noCopyProps = [
"arity", "length",
"name",
"arguments",
"caller",
"callee",
"prototype",
"__isPromisified__"
];
var noCopyPropsPattern = new RegExp("^(?:" + noCopyProps.join("|") + ")$");
var defaultFilter = function(name) {
return util.isIdentifier(name) &&
name.charAt(0) !== "_" &&
name !== "constructor";
};
function propsFilter(key) {
return !noCopyPropsPattern.test(key);
}
function isPromisified(fn) {
try {
return fn.__isPromisified__ === true;
}
catch (e) {
return false;
}
}
function hasPromisified(obj, key, suffix) {
var val = util.getDataPropertyOrDefault(obj, key + suffix,
defaultPromisified);
return val ? isPromisified(val) : false;
}
function checkValid(ret, suffix, suffixRegexp) {
for (var i = 0; i < ret.length; i += 2) {
var key = ret[i];
if (suffixRegexp.test(key)) {
var keyWithoutAsyncSuffix = key.replace(suffixRegexp, "");
for (var j = 0; j < ret.length; j += 2) {
if (ret[j] === keyWithoutAsyncSuffix) {
throw new TypeError("Cannot promisify an API that has normal methods with '%s'-suffix\u000a\u000a See http://goo.gl/iWrZbw\u000a"
.replace("%s", suffix));
}
}
}
}
}
function promisifiableMethods(obj, suffix, suffixRegexp, filter) {
var keys = util.inheritedDataKeys(obj);
var ret = [];
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
var value = obj[key];
var passesDefaultFilter = filter === defaultFilter
? true : defaultFilter(key, value, obj);
if (typeof value === "function" &&
!isPromisified(value) &&
!hasPromisified(obj, key, suffix) &&
filter(key, value, obj, passesDefaultFilter)) {
ret.push(key, value);
}
}
checkValid(ret, suffix, suffixRegexp);
return ret;
}
var escapeIdentRegex = function(str) {
return str.replace(/([$])/, "\\$");
};
var makeNodePromisifiedEval;
if (!true) {
var switchCaseArgumentOrder = function(likelyArgumentCount) {
var ret = [likelyArgumentCount];
var min = Math.max(0, likelyArgumentCount - 1 - 3);
for(var i = likelyArgumentCount - 1; i >= min; --i) {
ret.push(i);
}
for(var i = likelyArgumentCount + 1; i <= 3; ++i) {
ret.push(i);
}
return ret;
};
var argumentSequence = function(argumentCount) {
return util.filledRange(argumentCount, "_arg", "");
};
var parameterDeclaration = function(parameterCount) {
return util.filledRange(
Math.max(parameterCount, 3), "_arg", "");
};
var parameterCount = function(fn) {
if (typeof fn.length === "number") {
return Math.max(Math.min(fn.length, 1023 + 1), 0);
}
return 0;
};
makeNodePromisifiedEval =
function(callback, receiver, originalName, fn) {
var newParameterCount = Math.max(0, parameterCount(fn) - 1);
var argumentOrder = switchCaseArgumentOrder(newParameterCount);
var shouldProxyThis = typeof callback === "string" || receiver === THIS;
function generateCallForArgumentCount(count) {
var args = argumentSequence(count).join(", ");
var comma = count > 0 ? ", " : "";
var ret;
if (shouldProxyThis) {
ret = "ret = callback.call(this, {{args}}, nodeback); break;\n";
} else {
ret = receiver === undefined
? "ret = callback({{args}}, nodeback); break;\n"
: "ret = callback.call(receiver, {{args}}, nodeback); break;\n";
}
return ret.replace("{{args}}", args).replace(", ", comma);
}
function generateArgumentSwitchCase() {
var ret = "";
for (var i = 0; i < argumentOrder.length; ++i) {
ret += "case " + argumentOrder[i] +":" +
generateCallForArgumentCount(argumentOrder[i]);
}
ret += " \n\
default: \n\
var args = new Array(len + 1); \n\
var i = 0; \n\
for (var i = 0; i < len; ++i) { \n\
args[i] = arguments[i]; \n\
} \n\
args[i] = nodeback; \n\
[CodeForCall] \n\
break; \n\
".replace("[CodeForCall]", (shouldProxyThis
? "ret = callback.apply(this, args);\n"
: "ret = callback.apply(receiver, args);\n"));
return ret;
}
var getFunctionCode = typeof callback === "string"
? ("this != null ? this['"+callback+"'] : fn")
: "fn";
return new Function("Promise",
"fn",
"receiver",
"withAppended",
"maybeWrapAsError",
"nodebackForPromise",
"tryCatch",
"errorObj",
"notEnumerableProp",
"INTERNAL","'use strict'; \n\
var ret = function (Parameters) { \n\
'use strict'; \n\
var len = arguments.length; \n\
var promise = new Promise(INTERNAL); \n\
promise._captureStackTrace(); \n\
var nodeback = nodebackForPromise(promise); \n\
var ret; \n\
var callback = tryCatch([GetFunctionCode]); \n\
switch(len) { \n\
[CodeForSwitchCase] \n\
} \n\
if (ret === errorObj) { \n\
promise._rejectCallback(maybeWrapAsError(ret.e), true, true);\n\
} \n\
return promise; \n\
}; \n\
notEnumerableProp(ret, '__isPromisified__', true); \n\
return ret; \n\
"
.replace("Parameters", parameterDeclaration(newParameterCount))
.replace("[CodeForSwitchCase]", generateArgumentSwitchCase())
.replace("[GetFunctionCode]", getFunctionCode))(
Promise,
fn,
receiver,
withAppended,
maybeWrapAsError,
nodebackForPromise,
util.tryCatch,
util.errorObj,
util.notEnumerableProp,
INTERNAL
);
};
}
function makeNodePromisifiedClosure(callback, receiver, _, fn) {
var defaultThis = (function() {return this;})();
var method = callback;
if (typeof method === "string") {
callback = fn;
}
function promisified() {
var _receiver = receiver;
if (receiver === THIS) _receiver = this;
var promise = new Promise(INTERNAL);
promise._captureStackTrace();
var cb = typeof method === "string" && this !== defaultThis
? this[method] : callback;
var fn = nodebackForPromise(promise);
try {
cb.apply(_receiver, withAppended(arguments, fn));
} catch(e) {
promise._rejectCallback(maybeWrapAsError(e), true, true);
}
return promise;
}
util.notEnumerableProp(promisified, "__isPromisified__", true);
return promisified;
}
var makeNodePromisified = canEvaluate
? makeNodePromisifiedEval
: makeNodePromisifiedClosure;
function promisifyAll(obj, suffix, filter, promisifier) {
var suffixRegexp = new RegExp(escapeIdentRegex(suffix) + "$");
var methods =
promisifiableMethods(obj, suffix, suffixRegexp, filter);
for (var i = 0, len = methods.length; i < len; i+= 2) {
var key = methods[i];
var fn = methods[i+1];
var promisifiedKey = key + suffix;
obj[promisifiedKey] = promisifier === makeNodePromisified
? makeNodePromisified(key, THIS, key, fn, suffix)
: promisifier(fn, function() {
return makeNodePromisified(key, THIS, key, fn, suffix);
});
}
util.toFastProperties(obj);
return obj;
}
function promisify(callback, receiver) {
return makeNodePromisified(callback, receiver, undefined, callback);
}
Promise.promisify = function (fn, receiver) {
if (typeof fn !== "function") {
throw new TypeError("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a");
}
if (isPromisified(fn)) {
return fn;
}
var ret = promisify(fn, arguments.length < 2 ? THIS : receiver);
util.copyDescriptors(fn, ret, propsFilter);
return ret;
};
Promise.promisifyAll = function (target, options) {
if (typeof target !== "function" && typeof target !== "object") {
throw new TypeError("the target of promisifyAll must be an object or a function\u000a\u000a See http://goo.gl/9ITlV0\u000a");
}
options = Object(options);
var suffix = options.suffix;
if (typeof suffix !== "string") suffix = defaultSuffix;
var filter = options.filter;
if (typeof filter !== "function") filter = defaultFilter;
var promisifier = options.promisifier;
if (typeof promisifier !== "function") promisifier = makeNodePromisified;
if (!util.isIdentifier(suffix)) {
throw new RangeError("suffix must be a valid identifier\u000a\u000a See http://goo.gl/8FZo5V\u000a");
}
var keys = util.inheritedDataKeys(target);
for (var i = 0; i < keys.length; ++i) {
var value = target[keys[i]];
if (keys[i] !== "constructor" &&
util.isClass(value)) {
promisifyAll(value.prototype, suffix, filter, promisifier);
promisifyAll(value, suffix, filter, promisifier);
}
}
return promisifyAll(target, suffix, filter, promisifier);
};
};
},{"./errors":13,"./promise_resolver.js":25,"./util.js":38}],27:[function(_dereq_,module,exports){
"use strict";
module.exports = function(
Promise, PromiseArray, tryConvertToPromise, apiRejection) {
var util = _dereq_("./util.js");
var isObject = util.isObject;
var es5 = _dereq_("./es5.js");
function PropertiesPromiseArray(obj) {
var keys = es5.keys(obj);
var len = keys.length;
var values = new Array(len * 2);
for (var i = 0; i < len; ++i) {
var key = keys[i];
values[i] = obj[key];
values[i + len] = key;
}
this.constructor$(values);
}
util.inherits(PropertiesPromiseArray, PromiseArray);
PropertiesPromiseArray.prototype._init = function () {
this._init$(undefined, -3) ;
};
PropertiesPromiseArray.prototype._promiseFulfilled = function (value, index) {
this._values[index] = value;
var totalResolved = ++this._totalResolved;
if (totalResolved >= this._length) {
var val = {};
var keyOffset = this.length();
for (var i = 0, len = this.length(); i < len; ++i) {
val[this._values[i + keyOffset]] = this._values[i];
}
this._resolve(val);
}
};
PropertiesPromiseArray.prototype._promiseProgressed = function (value, index) {
this._promise._progress({
key: this._values[index + this.length()],
value: value
});
};
PropertiesPromiseArray.prototype.shouldCopyValues = function () {
return false;
};
PropertiesPromiseArray.prototype.getActualLength = function (len) {
return len >> 1;
};
function props(promises) {
var ret;
var castValue = tryConvertToPromise(promises);
if (!isObject(castValue)) {
return apiRejection("cannot await properties of a non-object\u000a\u000a See http://goo.gl/OsFKC8\u000a");
} else if (castValue instanceof Promise) {
ret = castValue._then(
Promise.props, undefined, undefined, undefined, undefined);
} else {
ret = new PropertiesPromiseArray(castValue).promise();
}
if (castValue instanceof Promise) {
ret._propagateFrom(castValue, 4);
}
return ret;
}
Promise.prototype.props = function () {
return props(this);
};
Promise.props = function (promises) {
return props(promises);
};
};
},{"./es5.js":14,"./util.js":38}],28:[function(_dereq_,module,exports){
"use strict";
function arrayMove(src, srcIndex, dst, dstIndex, len) {
for (var j = 0; j < len; ++j) {
dst[j + dstIndex] = src[j + srcIndex];
src[j + srcIndex] = void 0;
}
}
function Queue(capacity) {
this._capacity = capacity;
this._length = 0;
this._front = 0;
}
Queue.prototype._willBeOverCapacity = function (size) {
return this._capacity < size;
};
Queue.prototype._pushOne = function (arg) {
var length = this.length();
this._checkCapacity(length + 1);
var i = (this._front + length) & (this._capacity - 1);
this[i] = arg;
this._length = length + 1;
};
Queue.prototype._unshiftOne = function(value) {
var capacity = this._capacity;
this._checkCapacity(this.length() + 1);
var front = this._front;
var i = (((( front - 1 ) &
( capacity - 1) ) ^ capacity ) - capacity );
this[i] = value;
this._front = i;
this._length = this.length() + 1;
};
Queue.prototype.unshift = function(fn, receiver, arg) {
this._unshiftOne(arg);
this._unshiftOne(receiver);
this._unshiftOne(fn);
};
Queue.prototype.push = function (fn, receiver, arg) {
var length = this.length() + 3;
if (this._willBeOverCapacity(length)) {
this._pushOne(fn);
this._pushOne(receiver);
this._pushOne(arg);
return;
}
var j = this._front + length - 3;
this._checkCapacity(length);
var wrapMask = this._capacity - 1;
this[(j + 0) & wrapMask] = fn;
this[(j + 1) & wrapMask] = receiver;
this[(j + 2) & wrapMask] = arg;
this._length = length;
};
Queue.prototype.shift = function () {
var front = this._front,
ret = this[front];
this[front] = undefined;
this._front = (front + 1) & (this._capacity - 1);
this._length--;
return ret;
};
Queue.prototype.length = function () {
return this._length;
};
Queue.prototype._checkCapacity = function (size) {
if (this._capacity < size) {
this._resizeTo(this._capacity << 1);
}
};
Queue.prototype._resizeTo = function (capacity) {
var oldCapacity = this._capacity;
this._capacity = capacity;
var front = this._front;
var length = this._length;
var moveItemsCount = (front + length) & (oldCapacity - 1);
arrayMove(this, 0, this, oldCapacity, moveItemsCount);
};
module.exports = Queue;
},{}],29:[function(_dereq_,module,exports){
"use strict";
module.exports = function(
Promise, INTERNAL, tryConvertToPromise, apiRejection) {
var isArray = _dereq_("./util.js").isArray;
var raceLater = function (promise) {
return promise.then(function(array) {
return race(array, promise);
});
};
function race(promises, parent) {
var maybePromise = tryConvertToPromise(promises);
if (maybePromise instanceof Promise) {
return raceLater(maybePromise);
} else if (!isArray(promises)) {
return apiRejection("expecting an array, a promise or a thenable\u000a\u000a See http://goo.gl/s8MMhc\u000a");
}
var ret = new Promise(INTERNAL);
if (parent !== undefined) {
ret._propagateFrom(parent, 4 | 1);
}
var fulfill = ret._fulfill;
var reject = ret._reject;
for (var i = 0, len = promises.length; i < len; ++i) {
var val = promises[i];
if (val === undefined && !(i in promises)) {
continue;
}
Promise.cast(val)._then(fulfill, reject, undefined, ret, null);
}
return ret;
}
Promise.race = function (promises) {
return race(promises, undefined);
};
Promise.prototype.race = function () {
return race(this, undefined);
};
};
},{"./util.js":38}],30:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise,
PromiseArray,
apiRejection,
tryConvertToPromise,
INTERNAL) {
var getDomain = Promise._getDomain;
var async = _dereq_("./async.js");
var util = _dereq_("./util.js");
var tryCatch = util.tryCatch;
var errorObj = util.errorObj;
function ReductionPromiseArray(promises, fn, accum, _each) {
this.constructor$(promises);
this._promise._captureStackTrace();
this._preservedValues = _each === INTERNAL ? [] : null;
this._zerothIsAccum = (accum === undefined);
this._gotAccum = false;
this._reducingIndex = (this._zerothIsAccum ? 1 : 0);
this._valuesPhase = undefined;
var maybePromise = tryConvertToPromise(accum, this._promise);
var rejected = false;
var isPromise = maybePromise instanceof Promise;
if (isPromise) {
maybePromise = maybePromise._target();
if (maybePromise._isPending()) {
maybePromise._proxyPromiseArray(this, -1);
} else if (maybePromise._isFulfilled()) {
accum = maybePromise._value();
this._gotAccum = true;
} else {
this._reject(maybePromise._reason());
rejected = true;
}
}
if (!(isPromise || this._zerothIsAccum)) this._gotAccum = true;
var domain = getDomain();
this._callback = domain === null ? fn : domain.bind(fn);
this._accum = accum;
if (!rejected) async.invoke(init, this, undefined);
}
function init() {
this._init$(undefined, -5);
}
util.inherits(ReductionPromiseArray, PromiseArray);
ReductionPromiseArray.prototype._init = function () {};
ReductionPromiseArray.prototype._resolveEmptyArray = function () {
if (this._gotAccum || this._zerothIsAccum) {
this._resolve(this._preservedValues !== null
? [] : this._accum);
}
};
ReductionPromiseArray.prototype._promiseFulfilled = function (value, index) {
var values = this._values;
values[index] = value;
var length = this.length();
var preservedValues = this._preservedValues;
var isEach = preservedValues !== null;
var gotAccum = this._gotAccum;
var valuesPhase = this._valuesPhase;
var valuesPhaseIndex;
if (!valuesPhase) {
valuesPhase = this._valuesPhase = new Array(length);
for (valuesPhaseIndex=0; valuesPhaseIndex<length; ++valuesPhaseIndex) {
valuesPhase[valuesPhaseIndex] = 0;
}
}
valuesPhaseIndex = valuesPhase[index];
if (index === 0 && this._zerothIsAccum) {
this._accum = value;
this._gotAccum = gotAccum = true;
valuesPhase[index] = ((valuesPhaseIndex === 0)
? 1 : 2);
} else if (index === -1) {
this._accum = value;
this._gotAccum = gotAccum = true;
} else {
if (valuesPhaseIndex === 0) {
valuesPhase[index] = 1;
} else {
valuesPhase[index] = 2;
this._accum = value;
}
}
if (!gotAccum) return;
var callback = this._callback;
var receiver = this._promise._boundValue();
var ret;
for (var i = this._reducingIndex; i < length; ++i) {
valuesPhaseIndex = valuesPhase[i];
if (valuesPhaseIndex === 2) {
this._reducingIndex = i + 1;
continue;
}
if (valuesPhaseIndex !== 1) return;
value = values[i];
this._promise._pushContext();
if (isEach) {
preservedValues.push(value);
ret = tryCatch(callback).call(receiver, value, i, length);
}
else {
ret = tryCatch(callback)
.call(receiver, this._accum, value, i, length);
}
this._promise._popContext();
if (ret === errorObj) return this._reject(ret.e);
var maybePromise = tryConvertToPromise(ret, this._promise);
if (maybePromise instanceof Promise) {
maybePromise = maybePromise._target();
if (maybePromise._isPending()) {
valuesPhase[i] = 4;
return maybePromise._proxyPromiseArray(this, i);
} else if (maybePromise._isFulfilled()) {
ret = maybePromise._value();
} else {
return this._reject(maybePromise._reason());
}
}
this._reducingIndex = i + 1;
this._accum = ret;
}
this._resolve(isEach ? preservedValues : this._accum);
};
function reduce(promises, fn, initialValue, _each) {
if (typeof fn !== "function") return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a");
var array = new ReductionPromiseArray(promises, fn, initialValue, _each);
return array.promise();
}
Promise.prototype.reduce = function (fn, initialValue) {
return reduce(this, fn, initialValue, null);
};
Promise.reduce = function (promises, fn, initialValue, _each) {
return reduce(promises, fn, initialValue, _each);
};
};
},{"./async.js":2,"./util.js":38}],31:[function(_dereq_,module,exports){
"use strict";
var schedule;
var util = _dereq_("./util");
var noAsyncScheduler = function() {
throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/m3OTXk\u000a");
};
if (util.isNode && typeof MutationObserver === "undefined") {
var GlobalSetImmediate = global.setImmediate;
var ProcessNextTick = process.nextTick;
schedule = util.isRecentNode
? function(fn) { GlobalSetImmediate.call(global, fn); }
: function(fn) { ProcessNextTick.call(process, fn); };
} else if ((typeof MutationObserver !== "undefined") &&
!(typeof window !== "undefined" &&
window.navigator &&
window.navigator.standalone)) {
schedule = function(fn) {
var div = document.createElement("div");
var observer = new MutationObserver(fn);
observer.observe(div, {attributes: true});
return function() { div.classList.toggle("foo"); };
};
schedule.isStatic = true;
} else if (typeof setImmediate !== "undefined") {
schedule = function (fn) {
setImmediate(fn);
};
} else if (typeof setTimeout !== "undefined") {
schedule = function (fn) {
setTimeout(fn, 0);
};
} else {
schedule = noAsyncScheduler;
}
module.exports = schedule;
},{"./util":38}],32:[function(_dereq_,module,exports){
"use strict";
module.exports =
function(Promise, PromiseArray) {
var PromiseInspection = Promise.PromiseInspection;
var util = _dereq_("./util.js");
function SettledPromiseArray(values) {
this.constructor$(values);
}
util.inherits(SettledPromiseArray, PromiseArray);
SettledPromiseArray.prototype._promiseResolved = function (index, inspection) {
this._values[index] = inspection;
var totalResolved = ++this._totalResolved;
if (totalResolved >= this._length) {
this._resolve(this._values);
}
};
SettledPromiseArray.prototype._promiseFulfilled = function (value, index) {
var ret = new PromiseInspection();
ret._bitField = 268435456;
ret._settledValue = value;
this._promiseResolved(index, ret);
};
SettledPromiseArray.prototype._promiseRejected = function (reason, index) {
var ret = new PromiseInspection();
ret._bitField = 134217728;
ret._settledValue = reason;
this._promiseResolved(index, ret);
};
Promise.settle = function (promises) {
return new SettledPromiseArray(promises).promise();
};
Promise.prototype.settle = function () {
return new SettledPromiseArray(this).promise();
};
};
},{"./util.js":38}],33:[function(_dereq_,module,exports){
"use strict";
module.exports =
function(Promise, PromiseArray, apiRejection) {
var util = _dereq_("./util.js");
var RangeError = _dereq_("./errors.js").RangeError;
var AggregateError = _dereq_("./errors.js").AggregateError;
var isArray = util.isArray;
function SomePromiseArray(values) {
this.constructor$(values);
this._howMany = 0;
this._unwrap = false;
this._initialized = false;
}
util.inherits(SomePromiseArray, PromiseArray);
SomePromiseArray.prototype._init = function () {
if (!this._initialized) {
return;
}
if (this._howMany === 0) {
this._resolve([]);
return;
}
this._init$(undefined, -5);
var isArrayResolved = isArray(this._values);
if (!this._isResolved() &&
isArrayResolved &&
this._howMany > this._canPossiblyFulfill()) {
this._reject(this._getRangeError(this.length()));
}
};
SomePromiseArray.prototype.init = function () {
this._initialized = true;
this._init();
};
SomePromiseArray.prototype.setUnwrap = function () {
this._unwrap = true;
};
SomePromiseArray.prototype.howMany = function () {
return this._howMany;
};
SomePromiseArray.prototype.setHowMany = function (count) {
this._howMany = count;
};
SomePromiseArray.prototype._promiseFulfilled = function (value) {
this._addFulfilled(value);
if (this._fulfilled() === this.howMany()) {
this._values.length = this.howMany();
if (this.howMany() === 1 && this._unwrap) {
this._resolve(this._values[0]);
} else {
this._resolve(this._values);
}
}
};
SomePromiseArray.prototype._promiseRejected = function (reason) {
this._addRejected(reason);
if (this.howMany() > this._canPossiblyFulfill()) {
var e = new AggregateError();
for (var i = this.length(); i < this._values.length; ++i) {
e.push(this._values[i]);
}
this._reject(e);
}
};
SomePromiseArray.prototype._fulfilled = function () {
return this._totalResolved;
};
SomePromiseArray.prototype._rejected = function () {
return this._values.length - this.length();
};
SomePromiseArray.prototype._addRejected = function (reason) {
this._values.push(reason);
};
SomePromiseArray.prototype._addFulfilled = function (value) {
this._values[this._totalResolved++] = value;
};
SomePromiseArray.prototype._canPossiblyFulfill = function () {
return this.length() - this._rejected();
};
SomePromiseArray.prototype._getRangeError = function (count) {
var message = "Input array must contain at least " +
this._howMany + " items but contains only " + count + " items";
return new RangeError(message);
};
SomePromiseArray.prototype._resolveEmptyArray = function () {
this._reject(this._getRangeError(0));
};
function some(promises, howMany) {
if ((howMany | 0) !== howMany || howMany < 0) {
return apiRejection("expecting a positive integer\u000a\u000a See http://goo.gl/1wAmHx\u000a");
}
var ret = new SomePromiseArray(promises);
var promise = ret.promise();
ret.setHowMany(howMany);
ret.init();
return promise;
}
Promise.some = function (promises, howMany) {
return some(promises, howMany);
};
Promise.prototype.some = function (howMany) {
return some(this, howMany);
};
Promise._SomePromiseArray = SomePromiseArray;
};
},{"./errors.js":13,"./util.js":38}],34:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise) {
function PromiseInspection(promise) {
if (promise !== undefined) {
promise = promise._target();
this._bitField = promise._bitField;
this._settledValue = promise._settledValue;
}
else {
this._bitField = 0;
this._settledValue = undefined;
}
}
PromiseInspection.prototype.value = function () {
if (!this.isFulfilled()) {
throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/hc1DLj\u000a");
}
return this._settledValue;
};
PromiseInspection.prototype.error =
PromiseInspection.prototype.reason = function () {
if (!this.isRejected()) {
throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/hPuiwB\u000a");
}
return this._settledValue;
};
PromiseInspection.prototype.isFulfilled =
Promise.prototype._isFulfilled = function () {
return (this._bitField & 268435456) > 0;
};
PromiseInspection.prototype.isRejected =
Promise.prototype._isRejected = function () {
return (this._bitField & 134217728) > 0;
};
PromiseInspection.prototype.isPending =
Promise.prototype._isPending = function () {
return (this._bitField & 402653184) === 0;
};
PromiseInspection.prototype.isResolved =
Promise.prototype._isResolved = function () {
return (this._bitField & 402653184) > 0;
};
Promise.prototype.isPending = function() {
return this._target()._isPending();
};
Promise.prototype.isRejected = function() {
return this._target()._isRejected();
};
Promise.prototype.isFulfilled = function() {
return this._target()._isFulfilled();
};
Promise.prototype.isResolved = function() {
return this._target()._isResolved();
};
Promise.prototype._value = function() {
return this._settledValue;
};
Promise.prototype._reason = function() {
this._unsetRejectionIsUnhandled();
return this._settledValue;
};
Promise.prototype.value = function() {
var target = this._target();
if (!target.isFulfilled()) {
throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/hc1DLj\u000a");
}
return target._settledValue;
};
Promise.prototype.reason = function() {
var target = this._target();
if (!target.isRejected()) {
throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/hPuiwB\u000a");
}
target._unsetRejectionIsUnhandled();
return target._settledValue;
};
Promise.PromiseInspection = PromiseInspection;
};
},{}],35:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise, INTERNAL) {
var util = _dereq_("./util.js");
var errorObj = util.errorObj;
var isObject = util.isObject;
function tryConvertToPromise(obj, context) {
if (isObject(obj)) {
if (obj instanceof Promise) {
return obj;
}
else if (isAnyBluebirdPromise(obj)) {
var ret = new Promise(INTERNAL);
obj._then(
ret._fulfillUnchecked,
ret._rejectUncheckedCheckError,
ret._progressUnchecked,
ret,
null
);
return ret;
}
var then = util.tryCatch(getThen)(obj);
if (then === errorObj) {
if (context) context._pushContext();
var ret = Promise.reject(then.e);
if (context) context._popContext();
return ret;
} else if (typeof then === "function") {
return doThenable(obj, then, context);
}
}
return obj;
}
function getThen(obj) {
return obj.then;
}
var hasProp = {}.hasOwnProperty;
function isAnyBluebirdPromise(obj) {
return hasProp.call(obj, "_promise0");
}
function doThenable(x, then, context) {
var promise = new Promise(INTERNAL);
var ret = promise;
if (context) context._pushContext();
promise._captureStackTrace();
if (context) context._popContext();
var synchronous = true;
var result = util.tryCatch(then).call(x,
resolveFromThenable,
rejectFromThenable,
progressFromThenable);
synchronous = false;
if (promise && result === errorObj) {
promise._rejectCallback(result.e, true, true);
promise = null;
}
function resolveFromThenable(value) {
if (!promise) return;
promise._resolveCallback(value);
promise = null;
}
function rejectFromThenable(reason) {
if (!promise) return;
promise._rejectCallback(reason, synchronous, true);
promise = null;
}
function progressFromThenable(value) {
if (!promise) return;
if (typeof promise._progress === "function") {
promise._progress(value);
}
}
return ret;
}
return tryConvertToPromise;
};
},{"./util.js":38}],36:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise, INTERNAL) {
var util = _dereq_("./util.js");
var TimeoutError = Promise.TimeoutError;
var afterTimeout = function (promise, message) {
if (!promise.isPending()) return;
if (typeof message !== "string") {
message = "operation timed out";
}
var err = new TimeoutError(message);
util.markAsOriginatingFromRejection(err);
promise._attachExtraTrace(err);
promise._cancel(err);
};
var afterValue = function(value) { return delay(+this).thenReturn(value); };
var delay = Promise.delay = function (value, ms) {
if (ms === undefined) {
ms = value;
value = undefined;
var ret = new Promise(INTERNAL);
setTimeout(function() { ret._fulfill(); }, ms);
return ret;
}
ms = +ms;
return Promise.resolve(value)._then(afterValue, null, null, ms, undefined);
};
Promise.prototype.delay = function (ms) {
return delay(this, ms);
};
function successClear(value) {
var handle = this;
if (handle instanceof Number) handle = +handle;
clearTimeout(handle);
return value;
}
function failureClear(reason) {
var handle = this;
if (handle instanceof Number) handle = +handle;
clearTimeout(handle);
throw reason;
}
Promise.prototype.timeout = function (ms, message) {
ms = +ms;
var ret = this.then().cancellable();
ret._cancellationParent = this;
var handle = setTimeout(function timeoutTimeout() {
afterTimeout(ret, message);
}, ms);
return ret._then(successClear, failureClear, undefined, handle, undefined);
};
};
},{"./util.js":38}],37:[function(_dereq_,module,exports){
"use strict";
module.exports = function (Promise, apiRejection, tryConvertToPromise,
createContext) {
var TypeError = _dereq_("./errors.js").TypeError;
var inherits = _dereq_("./util.js").inherits;
var PromiseInspection = Promise.PromiseInspection;
function inspectionMapper(inspections) {
var len = inspections.length;
for (var i = 0; i < len; ++i) {
var inspection = inspections[i];
if (inspection.isRejected()) {
return Promise.reject(inspection.error());
}
inspections[i] = inspection._settledValue;
}
return inspections;
}
function thrower(e) {
setTimeout(function(){throw e;}, 0);
}
function castPreservingDisposable(thenable) {
var maybePromise = tryConvertToPromise(thenable);
if (maybePromise !== thenable &&
typeof thenable._isDisposable === "function" &&
typeof thenable._getDisposer === "function" &&
thenable._isDisposable()) {
maybePromise._setDisposable(thenable._getDisposer());
}
return maybePromise;
}
function dispose(resources, inspection) {
var i = 0;
var len = resources.length;
var ret = Promise.defer();
function iterator() {
if (i >= len) return ret.resolve();
var maybePromise = castPreservingDisposable(resources[i++]);
if (maybePromise instanceof Promise &&
maybePromise._isDisposable()) {
try {
maybePromise = tryConvertToPromise(
maybePromise._getDisposer().tryDispose(inspection),
resources.promise);
} catch (e) {
return thrower(e);
}
if (maybePromise instanceof Promise) {
return maybePromise._then(iterator, thrower,
null, null, null);
}
}
iterator();
}
iterator();
return ret.promise;
}
function disposerSuccess(value) {
var inspection = new PromiseInspection();
inspection._settledValue = value;
inspection._bitField = 268435456;
return dispose(this, inspection).thenReturn(value);
}
function disposerFail(reason) {
var inspection = new PromiseInspection();
inspection._settledValue = reason;
inspection._bitField = 134217728;
return dispose(this, inspection).thenThrow(reason);
}
function Disposer(data, promise, context) {
this._data = data;
this._promise = promise;
this._context = context;
}
Disposer.prototype.data = function () {
return this._data;
};
Disposer.prototype.promise = function () {
return this._promise;
};
Disposer.prototype.resource = function () {
if (this.promise().isFulfilled()) {
return this.promise().value();
}
return null;
};
Disposer.prototype.tryDispose = function(inspection) {
var resource = this.resource();
var context = this._context;
if (context !== undefined) context._pushContext();
var ret = resource !== null
? this.doDispose(resource, inspection) : null;
if (context !== undefined) context._popContext();
this._promise._unsetDisposable();
this._data = null;
return ret;
};
Disposer.isDisposer = function (d) {
return (d != null &&
typeof d.resource === "function" &&
typeof d.tryDispose === "function");
};
function FunctionDisposer(fn, promise, context) {
this.constructor$(fn, promise, context);
}
inherits(FunctionDisposer, Disposer);
FunctionDisposer.prototype.doDispose = function (resource, inspection) {
var fn = this.data();
return fn.call(resource, resource, inspection);
};
function maybeUnwrapDisposer(value) {
if (Disposer.isDisposer(value)) {
this.resources[this.index]._setDisposable(value);
return value.promise();
}
return value;
}
Promise.using = function () {
var len = arguments.length;
if (len < 2) return apiRejection(
"you must pass at least 2 arguments to Promise.using");
var fn = arguments[len - 1];
if (typeof fn !== "function") return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a");
len--;
var resources = new Array(len);
for (var i = 0; i < len; ++i) {
var resource = arguments[i];
if (Disposer.isDisposer(resource)) {
var disposer = resource;
resource = resource.promise();
resource._setDisposable(disposer);
} else {
var maybePromise = tryConvertToPromise(resource);
if (maybePromise instanceof Promise) {
resource =
maybePromise._then(maybeUnwrapDisposer, null, null, {
resources: resources,
index: i
}, undefined);
}
}
resources[i] = resource;
}
var promise = Promise.settle(resources)
.then(inspectionMapper)
.then(function(vals) {
promise._pushContext();
var ret;
try {
ret = fn.apply(undefined, vals);
} finally {
promise._popContext();
}
return ret;
})
._then(
disposerSuccess, disposerFail, undefined, resources, undefined);
resources.promise = promise;
return promise;
};
Promise.prototype._setDisposable = function (disposer) {
this._bitField = this._bitField | 262144;
this._disposer = disposer;
};
Promise.prototype._isDisposable = function () {
return (this._bitField & 262144) > 0;
};
Promise.prototype._getDisposer = function () {
return this._disposer;
};
Promise.prototype._unsetDisposable = function () {
this._bitField = this._bitField & (~262144);
this._disposer = undefined;
};
Promise.prototype.disposer = function (fn) {
if (typeof fn === "function") {
return new FunctionDisposer(fn, this, createContext());
}
throw new TypeError();
};
};
},{"./errors.js":13,"./util.js":38}],38:[function(_dereq_,module,exports){
"use strict";
var es5 = _dereq_("./es5.js");
var canEvaluate = typeof navigator == "undefined";
var haveGetters = (function(){
try {
var o = {};
es5.defineProperty(o, "f", {
get: function () {
return 3;
}
});
return o.f === 3;
}
catch (e) {
return false;
}
})();
var errorObj = {e: {}};
var tryCatchTarget;
function tryCatcher() {
try {
var target = tryCatchTarget;
tryCatchTarget = null;
return target.apply(this, arguments);
} catch (e) {
errorObj.e = e;
return errorObj;
}
}
function tryCatch(fn) {
tryCatchTarget = fn;
return tryCatcher;
}
var inherits = function(Child, Parent) {
var hasProp = {}.hasOwnProperty;
function T() {
this.constructor = Child;
this.constructor$ = Parent;
for (var propertyName in Parent.prototype) {
if (hasProp.call(Parent.prototype, propertyName) &&
propertyName.charAt(propertyName.length-1) !== "$"
) {
this[propertyName + "$"] = Parent.prototype[propertyName];
}
}
}
T.prototype = Parent.prototype;
Child.prototype = new T();
return Child.prototype;
};
function isPrimitive(val) {
return val == null || val === true || val === false ||
typeof val === "string" || typeof val === "number";
}
function isObject(value) {
return !isPrimitive(value);
}
function maybeWrapAsError(maybeError) {
if (!isPrimitive(maybeError)) return maybeError;
return new Error(safeToString(maybeError));
}
function withAppended(target, appendee) {
var len = target.length;
var ret = new Array(len + 1);
var i;
for (i = 0; i < len; ++i) {
ret[i] = target[i];
}
ret[i] = appendee;
return ret;
}
function getDataPropertyOrDefault(obj, key, defaultValue) {
if (es5.isES5) {
var desc = Object.getOwnPropertyDescriptor(obj, key);
if (desc != null) {
return desc.get == null && desc.set == null
? desc.value
: defaultValue;
}
} else {
return {}.hasOwnProperty.call(obj, key) ? obj[key] : undefined;
}
}
function notEnumerableProp(obj, name, value) {
if (isPrimitive(obj)) return obj;
var descriptor = {
value: value,
configurable: true,
enumerable: false,
writable: true
};
es5.defineProperty(obj, name, descriptor);
return obj;
}
function thrower(r) {
throw r;
}
var inheritedDataKeys = (function() {
var excludedPrototypes = [
Array.prototype,
Object.prototype,
Function.prototype
];
var isExcludedProto = function(val) {
for (var i = 0; i < excludedPrototypes.length; ++i) {
if (excludedPrototypes[i] === val) {
return true;
}
}
return false;
};
if (es5.isES5) {
var getKeys = Object.getOwnPropertyNames;
return function(obj) {
var ret = [];
var visitedKeys = Object.create(null);
while (obj != null && !isExcludedProto(obj)) {
var keys;
try {
keys = getKeys(obj);
} catch (e) {
return ret;
}
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
if (visitedKeys[key]) continue;
visitedKeys[key] = true;
var desc = Object.getOwnPropertyDescriptor(obj, key);
if (desc != null && desc.get == null && desc.set == null) {
ret.push(key);
}
}
obj = es5.getPrototypeOf(obj);
}
return ret;
};
} else {
var hasProp = {}.hasOwnProperty;
return function(obj) {
if (isExcludedProto(obj)) return [];
var ret = [];
/*jshint forin:false */
enumeration: for (var key in obj) {
if (hasProp.call(obj, key)) {
ret.push(key);
} else {
for (var i = 0; i < excludedPrototypes.length; ++i) {
if (hasProp.call(excludedPrototypes[i], key)) {
continue enumeration;
}
}
ret.push(key);
}
}
return ret;
};
}
})();
var thisAssignmentPattern = /this\s*\.\s*\S+\s*=/;
function isClass(fn) {
try {
if (typeof fn === "function") {
var keys = es5.names(fn.prototype);
var hasMethods = es5.isES5 && keys.length > 1;
var hasMethodsOtherThanConstructor = keys.length > 0 &&
!(keys.length === 1 && keys[0] === "constructor");
var hasThisAssignmentAndStaticMethods =
thisAssignmentPattern.test(fn + "") && es5.names(fn).length > 0;
if (hasMethods || hasMethodsOtherThanConstructor ||
hasThisAssignmentAndStaticMethods) {
return true;
}
}
return false;
} catch (e) {
return false;
}
}
function toFastProperties(obj) {
/*jshint -W027,-W055,-W031*/
function f() {}
f.prototype = obj;
var l = 8;
while (l--) new f();
return obj;
eval(obj);
}
var rident = /^[a-z$_][a-z$_0-9]*$/i;
function isIdentifier(str) {
return rident.test(str);
}
function filledRange(count, prefix, suffix) {
var ret = new Array(count);
for(var i = 0; i < count; ++i) {
ret[i] = prefix + i + suffix;
}
return ret;
}
function safeToString(obj) {
try {
return obj + "";
} catch (e) {
return "[no string representation]";
}
}
function markAsOriginatingFromRejection(e) {
try {
notEnumerableProp(e, "isOperational", true);
}
catch(ignore) {}
}
function originatesFromRejection(e) {
if (e == null) return false;
return ((e instanceof Error["__BluebirdErrorTypes__"].OperationalError) ||
e["isOperational"] === true);
}
function canAttachTrace(obj) {
return obj instanceof Error && es5.propertyIsWritable(obj, "stack");
}
var ensureErrorObject = (function() {
if (!("stack" in new Error())) {
return function(value) {
if (canAttachTrace(value)) return value;
try {throw new Error(safeToString(value));}
catch(err) {return err;}
};
} else {
return function(value) {
if (canAttachTrace(value)) return value;
return new Error(safeToString(value));
};
}
})();
function classString(obj) {
return {}.toString.call(obj);
}
function copyDescriptors(from, to, filter) {
var keys = es5.names(from);
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
if (filter(key)) {
try {
es5.defineProperty(to, key, es5.getDescriptor(from, key));
} catch (ignore) {}
}
}
}
var ret = {
isClass: isClass,
isIdentifier: isIdentifier,
inheritedDataKeys: inheritedDataKeys,
getDataPropertyOrDefault: getDataPropertyOrDefault,
thrower: thrower,
isArray: es5.isArray,
haveGetters: haveGetters,
notEnumerableProp: notEnumerableProp,
isPrimitive: isPrimitive,
isObject: isObject,
canEvaluate: canEvaluate,
errorObj: errorObj,
tryCatch: tryCatch,
inherits: inherits,
withAppended: withAppended,
maybeWrapAsError: maybeWrapAsError,
toFastProperties: toFastProperties,
filledRange: filledRange,
toString: safeToString,
canAttachTrace: canAttachTrace,
ensureErrorObject: ensureErrorObject,
originatesFromRejection: originatesFromRejection,
markAsOriginatingFromRejection: markAsOriginatingFromRejection,
classString: classString,
copyDescriptors: copyDescriptors,
hasDevTools: typeof chrome !== "undefined" && chrome &&
typeof chrome.loadTimes === "function",
isNode: typeof process !== "undefined" &&
classString(process).toLowerCase() === "[object process]"
};
ret.isRecentNode = ret.isNode && (function() {
var version = process.versions.node.split(".").map(Number);
return (version[0] === 0 && version[1] > 10) || (version[0] > 0);
})();
if (ret.isNode) ret.toFastProperties(process);
try {throw new Error(); } catch (e) {ret.lastLineError = e;}
module.exports = ret;
},{"./es5.js":14}]},{},[4])(4)
}); ;if (typeof window !== 'undefined' && window !== null) { window.P = window.Promise; } else if (typeof self !== 'undefined' && self !== null) { self.P = self.Promise; }
}).call(this,require(53),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"53":53}]},{},[21])(21)
}); | unexpected.js | /*!
* Copyright (c) 2013 Sune Simonsen <[email protected]>
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the 'Software'), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}(g.weknowhow || (g.weknowhow = {})).expect = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
module.exports = function AssertionString(text) {
this.text = text;
};
},{}],2:[function(require,module,exports){
var createStandardErrorMessage = require(6);
var utils = require(19);
var magicpen = require(44);
var extend = utils.extend;
var leven = require(40);
var makePromise = require(11);
var addAdditionalPromiseMethods = require(4);
var isPendingPromise = require(9);
var oathbreaker = require(13);
var UnexpectedError = require(3);
var notifyPendingPromise = require(12);
var defaultDepth = require(8);
var createWrappedExpectProto = require(7);
var AssertionString = require(1);
var throwIfNonUnexpectedError = require(16);
var makeDiffResultBackwardsCompatible = require(10);
function isAssertionArg(arg) {
return arg.type.is('assertion');
}
function Context(unexpected) {
this.expect = unexpected;
this.level = 0;
}
Context.prototype.child = function () {
var child = Object.create(this);
child.level++;
return child;
};
var anyType = {
_unexpectedType: true,
name: 'any',
level: 0,
identify: function () {
return true;
},
equal: utils.objectIs,
inspect: function (value, depth, output) {
if (output && output.isMagicPen) {
return output.text(value);
} else {
// Guard against node.js' require('util').inspect eagerly calling .inspect() on objects
return 'type: ' + this.name;
}
},
diff: function (actual, expected, output, diff, inspect) {
return null;
},
typeEqualityCache: {},
is: function (typeOrTypeName) {
var typeName;
if (typeof typeOrTypeName === 'string') {
typeName = typeOrTypeName;
} else {
typeName = typeOrTypeName.name;
}
var cachedValue = this.typeEqualityCache[typeName];
if (typeof cachedValue !== 'undefined') {
return cachedValue;
}
var result = false;
if (this.name === typeName) {
result = true;
} else if (this.baseType) {
result = this.baseType.is(typeName);
}
this.typeEqualityCache[typeName] = result;
return result;
}
};
function Unexpected(options) {
options = options || {};
this.assertions = options.assertions || {};
this.typeByName = options.typeByName || {any: anyType};
this.types = options.types || [anyType];
if (options.output) {
this.output = options.output;
} else {
this.output = magicpen();
this.output.inline = false;
this.output.diff = false;
}
this._outputFormat = options.format || magicpen.defaultFormat;
this.installedPlugins = options.installedPlugins || [];
// Make bound versions of these two helpers up front to save a bit when creating wrapped expects:
var that = this;
this.getType = function (typeName) {
return that.typeByName[typeName] || (that.parent && that.parent.getType(typeName));
};
this.findTypeOf = function (obj) {
return utils.findFirst(that.types || [], function (type) {
return type.identify && type.identify(obj);
}) || (that.parent && that.parent.findTypeOf(obj));
};
this.findTypeOfWithParentType = function (obj, requiredParentType) {
return utils.findFirst(that.types || [], function (type) {
return type.identify && type.identify(obj) && (!requiredParentType || type.is(requiredParentType));
}) || (that.parent && that.parent.findTypeOfWithParentType(obj, requiredParentType));
};
this.findCommonType = function (a, b) {
var aAncestorIndex = {};
var current = this.findTypeOf(a);
while (current) {
aAncestorIndex[current.name] = current;
current = current.baseType;
}
current = this.findTypeOf(b);
while (current) {
if (aAncestorIndex[current.name]) {
return current;
}
current = current.baseType;
}
};
this._wrappedExpectProto = createWrappedExpectProto(this);
}
var OR = {};
function getOrGroups(expectations) {
var orGroups = [[]];
expectations.forEach(function (expectation) {
if (expectation === OR) {
orGroups.push([]);
} else {
orGroups[orGroups.length - 1].push(expectation);
}
});
return orGroups;
}
function evaluateGroup(unexpected, context, subject, orGroup) {
return orGroup.map(function (expectation) {
var args = Array.prototype.slice.call(expectation);
args.unshift(subject);
return {
expectation: args,
promise: makePromise(function () {
if (typeof args[1] === 'function') {
if (args.length > 2) {
throw new Error('expect.it(<function>) does not accept additional arguments');
} else {
// expect.it(function (value) { ... })
return args[1](args[0]);
}
} else {
return unexpected._expect(context.child(), args);
}
})
};
});
}
function writeGroupEvaluationsToOutput(output, groupEvaluations) {
var hasOrClauses = groupEvaluations.length > 1;
var hasAndClauses = groupEvaluations.some(function (groupEvaluation) {
return groupEvaluation.length > 1;
});
groupEvaluations.forEach(function (groupEvaluation, i) {
if (i > 0) {
if (hasAndClauses) {
output.nl();
} else {
output.sp();
}
output.jsComment('or').nl();
}
var groupFailed = false;
groupEvaluation.forEach(function (evaluation, j) {
if (j > 0) {
output.jsComment(' and').nl();
}
var isRejected = evaluation.promise.isRejected();
if (isRejected && !groupFailed) {
groupFailed = true;
var err = evaluation.promise.reason();
if (hasAndClauses || hasOrClauses) {
output.error('⨯ ');
}
output.block(function (output) {
output.append(err.getErrorMessage(output));
});
} else {
if (isRejected) {
output.error('⨯ ');
} else {
output.success('✓ ');
}
var expectation = evaluation.expectation;
output.block(function (output) {
var subject = expectation[0];
var subjectOutput = function (output) {
output.appendInspected(subject);
};
var args = expectation.slice(2);
var argsOutput = args.map(function (arg) {
return function (output) {
output.appendInspected(arg);
};
});
var testDescription = expectation[1];
createStandardErrorMessage(output, subjectOutput, testDescription, argsOutput, {
subject: subject
});
});
}
});
});
}
function createExpectIt(unexpected, expectations) {
var orGroups = getOrGroups(expectations);
function expectIt(subject, context) {
context = (
context &&
typeof context === 'object' &&
context instanceof Context
) ? context : new Context(unexpected);
var groupEvaluations = [];
var promises = [];
orGroups.forEach(function (orGroup) {
var evaluations = evaluateGroup(unexpected, context, subject, orGroup);
evaluations.forEach(function (evaluation) {
promises.push(evaluation.promise);
});
groupEvaluations.push(evaluations);
});
return oathbreaker(makePromise.settle(promises).then(function () {
groupEvaluations.forEach(function (groupEvaluation) {
groupEvaluation.forEach(function (evaluation) {
if (evaluation.promise.isRejected() && evaluation.promise.reason().errorMode === 'bubbleThrough') {
throw evaluation.promise.reason();
}
});
});
if (!groupEvaluations.some(function (groupEvaluation) {
return groupEvaluation.every(function (evaluation) {
return evaluation.promise.isFulfilled();
});
})) {
unexpected.fail(function (output) {
writeGroupEvaluationsToOutput(output, groupEvaluations);
});
}
}));
}
expectIt._expectIt = true;
expectIt._expectations = expectations;
expectIt._OR = OR;
expectIt.and = function () {
var copiedExpectations = expectations.slice();
copiedExpectations.push(arguments);
return createExpectIt(unexpected, copiedExpectations);
};
expectIt.or = function () {
var copiedExpectations = expectations.slice();
copiedExpectations.push(OR, arguments);
return createExpectIt(unexpected, copiedExpectations);
};
return expectIt;
}
Unexpected.prototype.it = function () { // ...
return createExpectIt(this, [arguments]);
};
Unexpected.prototype.equal = function (actual, expected, depth, seen) {
var that = this;
depth = typeof depth === 'number' ? depth : 100;
if (depth <= 0) {
// detect recursive loops in the structure
seen = seen || [];
if (seen.indexOf(actual) !== -1) {
throw new Error('Cannot compare circular structures');
}
seen.push(actual);
}
return this.findCommonType(actual, expected).equal(actual, expected, function (a, b) {
return that.equal(a, b, depth - 1, seen);
});
};
Unexpected.prototype.inspect = function (obj, depth, outputOrFormat) {
var seen = [];
var that = this;
var printOutput = function (obj, currentDepth, output) {
var objType = that.findTypeOf(obj);
if (currentDepth <= 0 && objType.is('object') && !objType.is('expect.it')) {
return output.text('...');
}
seen = seen || [];
if (seen.indexOf(obj) !== -1) {
return output.text('[Circular]');
}
return objType.inspect(obj, currentDepth, output, function (v, childDepth) {
output = output.clone();
seen.push(obj);
if (typeof childDepth === 'undefined') {
childDepth = currentDepth - 1;
}
output = printOutput(v, childDepth, output) || output;
seen.pop();
return output;
});
};
var output = typeof outputOrFormat === 'string' ? this.createOutput(outputOrFormat) : outputOrFormat;
output = output || this.createOutput();
return printOutput(obj, typeof depth === 'number' ? depth : defaultDepth, output) || output;
};
Unexpected.prototype.expandTypeAlternations = function (assertion) {
var that = this;
function createPermutations(args, i) {
if (i === args.length) {
return [];
}
var result = [];
args[i].forEach(function (arg) {
var tails = createPermutations(args, i + 1);
if (tails.length) {
tails.forEach(function (tail) {
result.push([arg].concat(tail));
});
} else if (arg.type.is('assertion')) {
result.push([
{ type: arg.type, minimum: 1, maximum: 1 },
{ type: that.getType('any'), minimum: 0, maximum: Infinity }
]);
result.push([
{ type: that.getType('expect.it'), minimum: 1, maximum: 1 }
]);
if (arg.minimum === 0) { // <assertion?>
result.push([]);
}
} else {
result.push([arg]);
}
});
return result;
}
var result = [];
assertion.subject.forEach(function (subjectRequirement) {
if (assertion.args.length) {
createPermutations(assertion.args, 0).forEach(function (args) {
result.push(extend({}, assertion, {
subject: subjectRequirement,
args: args
}));
});
} else {
result.push(extend({}, assertion, {
subject: subjectRequirement,
args: []
}));
}
});
return result;
};
Unexpected.prototype.parseAssertion = function (assertionString) {
var that = this;
var tokens = [];
var nextIndex = 0;
function parseTypeToken(typeToken) {
return typeToken.split('|').map(function (typeDeclaration) {
var matchNameAndOperator = typeDeclaration.match(/^([a-z_](?:|[a-z0-9_.-]*[_a-z0-9]))([+*?]|)$/i);
if (!matchNameAndOperator) {
throw new SyntaxError('Cannot parse type declaration:' + typeDeclaration);
}
var type = that.getType(matchNameAndOperator[1]);
if (!type) {
throw new Error('Unknown type: ' + matchNameAndOperator[1] + ' in ' + assertionString);
}
var operator = matchNameAndOperator[2];
return {
minimum: !operator || operator === '+' ? 1 : 0,
maximum: operator === '*' || operator === '+' ? Infinity : 1,
type: type
};
});
}
function hasVarargs(types) {
return types.some(function (type) {
return type.minimum !== 1 || type.maximum !== 1;
});
}
assertionString.replace(/\s*<((?:[a-z_](?:|[a-z0-9_.-]*[_a-z0-9])[?*+]?)(?:\|(?:[a-z_](?:|[a-z0-9_.-]*[_a-z0-9])[?*+]?))*)>|\s*([^<]+)/ig, function ($0, $1, $2, index) {
if (index !== nextIndex) {
throw new SyntaxError('Cannot parse token at index ' + nextIndex + ' in ' + assertionString);
}
if ($1) {
tokens.push(parseTypeToken($1));
} else {
tokens.push($2.trim());
}
nextIndex += $0.length;
});
var assertion;
if (tokens.length === 1 && typeof tokens[0] === 'string') {
assertion = {
subject: parseTypeToken('any'),
assertion: tokens[0],
args: [parseTypeToken('any*')]
};
} else {
assertion = {
subject: tokens[0],
assertion: tokens[1],
args: tokens.slice(2)
};
}
if (!Array.isArray(assertion.subject)) {
throw new SyntaxError('Missing subject type in ' + assertionString);
}
if (typeof assertion.assertion !== 'string') {
throw new SyntaxError('Missing assertion in ' + assertionString);
}
if (hasVarargs(assertion.subject)) {
throw new SyntaxError('The subject type cannot have varargs: ' + assertionString);
}
if (assertion.args.some(function (arg) { return typeof arg === 'string'; })) {
throw new SyntaxError('Only one assertion string is supported (see #225)');
}
if (assertion.args.slice(0, -1).some(hasVarargs)) {
throw new SyntaxError('Only the last argument type can have varargs: ' + assertionString);
}
if ([assertion.subject].concat(assertion.args.slice(0, -1)).some(function (argRequirements) {
return argRequirements.some(function (argRequirement) {
return argRequirement.type.is('assertion');
});
})) {
throw new SyntaxError('Only the last argument type can be <assertion>: ' + assertionString);
}
var lastArgRequirements = assertion.args[assertion.args.length - 1] || [];
var assertionRequirements = lastArgRequirements.filter(function (argRequirement) {
return argRequirement.type.is('assertion');
});
if (assertionRequirements.length > 0 && lastArgRequirements.length > 1) {
throw new SyntaxError('<assertion> cannot be alternated with other types: ' + assertionString);
}
if (assertionRequirements.some(function (argRequirement) {
return argRequirement.maximum !== 1;
})) {
throw new SyntaxError('<assertion+> and <assertion*> are not allowed: ' + assertionString);
}
return this.expandTypeAlternations(assertion);
};
var placeholderSplitRegexp = /(\{(?:\d+)\})/g;
var placeholderRegexp = /\{(\d+)\}/;
Unexpected.prototype.fail = function (arg) {
if (arg instanceof UnexpectedError) {
arg._hasSerializedErrorMessage = false;
throw arg;
}
if (utils.isError(arg)) {
throw arg;
}
var error = new UnexpectedError(this.expect);
if (typeof arg === 'function') {
error.errorMode = 'bubble';
error.output = arg;
} else if (arg && typeof arg === 'object') {
if (typeof arg.message !== 'undefined') {
error.errorMode = 'bubble';
}
error.output = function (output) {
if (typeof arg.message !== 'undefined') {
if (arg.message.isMagicPen) {
output.append(arg.message);
} else if (typeof arg.message === 'function') {
arg.message.call(output, output);
} else {
output.text(String(arg.message));
}
} else {
output.error('Explicit failure');
}
};
var expect = this.expect;
Object.keys(arg).forEach(function (key) {
var value = arg[key];
if (key === 'diff') {
if (typeof value === 'function' && this.parent) {
error.createDiff = function (output, diff, inspect, equal) {
var childOutput = expect.createOutput(output.format);
childOutput.inline = output.inline;
childOutput.output = output.output;
return value(childOutput, function diff(actual, expected) {
return expect.diff(actual, expected, childOutput.clone());
}, function inspect(v, depth) {
return childOutput.clone().appendInspected(v, (depth || defaultDepth) - 1);
}, function (actual, expected) {
return expect.equal(actual, expected);
});
};
} else {
error.createDiff = value;
}
} else if (key !== 'message') {
error[key] = value;
}
}, this);
} else {
var placeholderArgs;
if (arguments.length > 0) {
placeholderArgs = new Array(arguments.length - 1);
for (var i = 1 ; i < arguments.length ; i += 1) {
placeholderArgs[i - 1] = arguments[i];
}
}
error.errorMode = 'bubble';
error.output = function (output) {
var message = arg ? String(arg) : 'Explicit failure';
var tokens = message.split(placeholderSplitRegexp);
tokens.forEach(function (token) {
var match = placeholderRegexp.exec(token);
if (match) {
var index = match[1];
if (index in placeholderArgs) {
var placeholderArg = placeholderArgs[index];
if (placeholderArg && placeholderArg.isMagicPen) {
output.append(placeholderArg);
} else {
output.appendInspected(placeholderArg);
}
} else {
output.text(match[0]);
}
} else {
output.error(token);
}
});
};
}
throw error;
};
function compareSpecificities(a, b) {
for (var i = 0; i < Math.min(a.length, b.length); i += 1) {
var c = b[i] - a[i];
if (c !== 0) {
return c;
}
}
return b.length - a.length;
}
function calculateAssertionSpecificity(assertion) {
return [assertion.subject.type.level].concat(assertion.args.map(function (argRequirement) {
var bonus = argRequirement.minimum === 1 && argRequirement.maximum === 1 ?
0.5 : 0;
return bonus + argRequirement.type.level;
}));
}
Unexpected.prototype.addAssertion = function (patternOrPatterns, handler, childUnexpected) {
var maxArguments;
if (typeof childUnexpected === 'object') {
maxArguments = 3;
} else {
maxArguments = 2;
}
if (arguments.length > maxArguments || typeof handler !== 'function' || (typeof patternOrPatterns !== 'string' && !Array.isArray(patternOrPatterns))) {
var errorMessage = "Syntax: expect.addAssertion(<string|array[string]>, function (expect, subject, ...) { ... });";
if ((typeof handler === 'string' || Array.isArray(handler)) && typeof arguments[2] === 'function') {
errorMessage +=
'\nAs of Unexpected 10, the syntax for adding assertions that apply only to specific\n' +
'types has changed. See http://unexpected.js.org/api/addAssertion/';
}
throw new Error(errorMessage);
}
var patterns = (Array.isArray(patternOrPatterns) ? patternOrPatterns : [patternOrPatterns]);
patterns.forEach(function (pattern) {
if (typeof pattern !== 'string' || pattern === '') {
throw new Error('Assertion patterns must be a non-empty string');
} else {
if (pattern !== pattern.trim()) {
throw new Error("Assertion patterns can't start or end with whitespace:\n\n " + JSON.stringify(pattern));
}
}
});
var that = this;
var assertions = this.assertions;
var defaultValueByFlag = {};
var assertionHandlers = [];
var maxNumberOfArgs = 0;
patterns.forEach(function (pattern) {
var assertionDeclarations = that.parseAssertion(pattern);
assertionDeclarations.forEach(function (assertionDeclaration) {
ensureValidUseOfParenthesesOrBrackets(assertionDeclaration.assertion);
var expandedAssertions = expandAssertion(assertionDeclaration.assertion);
expandedAssertions.forEach(function (expandedAssertion) {
Object.keys(expandedAssertion.flags).forEach(function (flag) {
defaultValueByFlag[flag] = false;
});
maxNumberOfArgs = Math.max(maxNumberOfArgs, assertionDeclaration.args.reduce(function (previous, argDefinition) {
return previous + (argDefinition.maximum === null ? Infinity : argDefinition.maximum);
}, 0));
assertionHandlers.push({
handler: handler,
alternations: expandedAssertion.alternations,
flags: expandedAssertion.flags,
subject: assertionDeclaration.subject,
args: assertionDeclaration.args,
testDescriptionString: expandedAssertion.text,
declaration: pattern,
unexpected: childUnexpected
});
});
});
});
if (handler.length - 2 > maxNumberOfArgs) {
throw new Error('The provided assertion handler takes ' + (handler.length - 2) + ' parameters, but the type signature specifies a maximum of ' + maxNumberOfArgs + ':\n\n ' + JSON.stringify(patterns));
}
assertionHandlers.forEach(function (handler) {
// Make sure that all flags are defined.
handler.flags = extend({}, defaultValueByFlag, handler.flags);
var assertionHandlers = assertions[handler.testDescriptionString];
handler.specificity = calculateAssertionSpecificity(handler);
if (!assertionHandlers) {
assertions[handler.testDescriptionString] = [handler];
} else {
var i = 0;
while (i < assertionHandlers.length && compareSpecificities(handler.specificity, assertionHandlers[i].specificity) > 0) {
i += 1;
}
assertionHandlers.splice(i, 0, handler);
}
});
return this.expect; // for chaining
};
Unexpected.prototype.addType = function (type, childUnexpected) {
var that = this;
var baseType;
if (typeof type.name !== 'string' || !/^[a-z_](?:|[a-z0-9_.-]*[_a-z0-9])$/i.test(type.name)) {
throw new Error('A type must be given a non-empty name and must match ^[a-z_](?:|[a-z0-9_.-]*[_a-z0-9])$');
}
if (typeof type.identify !== 'function' && type.identify !== false) {
throw new Error('Type ' + type.name + ' must specify an identify function or be declared abstract by setting identify to false');
}
if (this.typeByName[type.name]) {
throw new Error('The type with the name ' + type.name + ' already exists');
}
if (type.base) {
baseType = this.getType(type.base);
if (!baseType) {
throw new Error('Unknown base type: ' + type.base);
}
} else {
baseType = anyType;
}
var extendedBaseType = Object.create(baseType);
extendedBaseType.inspect = function (value, depth, output) {
if (!output || !output.isMagicPen) {
throw new Error('You need to pass the output to baseType.inspect() as the third parameter');
}
return baseType.inspect(value, depth, output, function (value, depth) {
return output.clone().appendInspected(value, depth);
});
};
extendedBaseType.diff = function (actual, expected, output) {
if (!output || !output.isMagicPen) {
throw new Error('You need to pass the output to baseType.diff() as the third parameter');
}
return makeDiffResultBackwardsCompatible(baseType.diff(actual, expected,
output.clone(),
function (actual, expected) {
return that.diff(actual, expected, output.clone());
},
function (value, depth) {
return output.clone().appendInspected(value, depth);
},
that.equal.bind(that)));
};
extendedBaseType.equal = function (actual, expected) {
return baseType.equal(actual, expected, that.equal.bind(that));
};
var extendedType = extend({}, baseType, type, { baseType: extendedBaseType });
var originalInspect = extendedType.inspect;
extendedType.inspect = function (obj, depth, output, inspect) {
if (arguments.length < 2 || (!output || !output.isMagicPen)) {
return 'type: ' + type.name;
} else if (childUnexpected) {
var childOutput = childUnexpected.createOutput(output.format);
return originalInspect.call(this, obj, depth, childOutput, inspect) || childOutput;
} else {
return originalInspect.call(this, obj, depth, output, inspect) || output;
}
};
if (childUnexpected) {
extendedType.childUnexpected = childUnexpected;
var originalDiff = extendedType.diff;
extendedType.diff = function (actual, expected, output, inspect, diff, equal) {
var childOutput = childUnexpected.createOutput(output.format);
// Make sure that already buffered up output is preserved:
childOutput.output = output.output;
return originalDiff.call(this, actual, expected, childOutput, inspect, diff, equal) || output;
};
}
if (extendedType.identify === false) {
this.types.push(extendedType);
} else {
this.types.unshift(extendedType);
}
extendedType.level = baseType.level + 1;
extendedType.typeEqualityCache = {};
this.typeByName[extendedType.name] = extendedType;
return this.expect;
};
Unexpected.prototype.addStyle = function () { // ...
this.output.addStyle.apply(this.output, arguments);
return this.expect;
};
Unexpected.prototype.installTheme = function () { // ...
this.output.installTheme.apply(this.output, arguments);
return this.expect;
};
function getPluginName(plugin) {
if (typeof plugin === 'function') {
return utils.getFunctionName(plugin);
} else {
return plugin.name;
}
}
Unexpected.prototype.use = function (plugin) {
if ((typeof plugin !== 'function' && (typeof plugin !== 'object' || typeof plugin.installInto !== 'function')) ||
(typeof plugin.name !== 'undefined' && typeof plugin.name !== 'string') ||
(typeof plugin.dependencies !== 'undefined' && !Array.isArray(plugin.dependencies))) {
throw new Error(
'Plugins must be functions or adhere to the following interface\n' +
'{\n' +
' name: <an optional plugin name>,\n' +
' version: <an optional semver version string>,\n' +
' dependencies: <an optional list of dependencies>,\n' +
' installInto: <a function that will update the given expect instance>\n' +
'}'
);
}
var pluginName = getPluginName(plugin);
var existingPlugin = utils.findFirst(this.installedPlugins, function (installedPlugin) {
if (installedPlugin === plugin) {
return true;
} else {
return pluginName && pluginName === getPluginName(installedPlugin);
}
});
if (existingPlugin) {
if (existingPlugin === plugin || (typeof plugin.version !== 'undefined' && plugin.version === existingPlugin.version)) {
// No-op
return this.expect;
} else {
throw new Error("Another instance of the plugin '" + pluginName + "' " +
"is already installed" +
(typeof existingPlugin.version !== 'undefined' ?
' (version ' + existingPlugin.version +
(typeof plugin.version !== 'undefined' ?
', trying to install ' + plugin.version : '') +
')' : '') +
". Please check your node_modules folder for unmet peerDependencies.");
}
}
if (pluginName === 'unexpected-promise') {
throw new Error('The unexpected-promise plugin was pulled into Unexpected as of 8.5.0. This means that the plugin is no longer supported.');
}
if (plugin.dependencies) {
var installedPlugins = this.installedPlugins;
var instance = this.parent;
while (instance) {
Array.prototype.push.apply(installedPlugins, instance.installedPlugins);
instance = instance.parent;
}
var unfulfilledDependencies = plugin.dependencies.filter(function (dependency) {
return !installedPlugins.some(function (plugin) {
return getPluginName(plugin) === dependency;
});
});
if (unfulfilledDependencies.length === 1) {
throw new Error(pluginName + ' requires plugin ' + unfulfilledDependencies[0]);
} else if (unfulfilledDependencies.length > 1) {
throw new Error(pluginName + ' requires plugins ' +
unfulfilledDependencies.slice(0, -1).join(', ') +
' and ' + unfulfilledDependencies[unfulfilledDependencies.length - 1]);
}
}
this.installedPlugins.push(plugin);
if (typeof plugin === 'function') {
plugin(this.expect);
} else {
plugin.installInto(this.expect);
}
return this.expect; // for chaining
};
Unexpected.prototype.withError = function (body, handler) {
return oathbreaker(makePromise(body).caught(function (e) {
throwIfNonUnexpectedError(e);
return handler(e);
}));
};
Unexpected.prototype.installPlugin = Unexpected.prototype.use; // Legacy alias
function installExpectMethods(unexpected) {
var expect = function () { /// ...
return unexpected._expect(new Context(unexpected), arguments);
};
expect.it = unexpected.it.bind(unexpected);
expect.equal = unexpected.equal.bind(unexpected);
expect.inspect = unexpected.inspect.bind(unexpected);
expect.findTypeOf = unexpected.findTypeOf; // Already bound
expect.fail = function () {
try {
unexpected.fail.apply(unexpected, arguments);
} catch (e) {
if (e && e._isUnexpected) {
unexpected.setErrorMessage(e);
}
throw e;
}
};
expect.createOutput = unexpected.createOutput.bind(unexpected);
expect.diff = unexpected.diff.bind(unexpected);
expect.async = unexpected.async.bind(unexpected);
expect.promise = makePromise;
expect.withError = unexpected.withError;
expect.addAssertion = unexpected.addAssertion.bind(unexpected);
expect.addStyle = unexpected.addStyle.bind(unexpected);
expect.installTheme = unexpected.installTheme.bind(unexpected);
expect.addType = unexpected.addType.bind(unexpected);
expect.getType = unexpected.getType;
expect.clone = unexpected.clone.bind(unexpected);
expect.child = unexpected.child.bind(unexpected);
expect.toString = unexpected.toString.bind(unexpected);
expect.assertions = unexpected.assertions;
expect.use = expect.installPlugin = unexpected.use.bind(unexpected);
expect.output = unexpected.output;
expect.outputFormat = unexpected.outputFormat.bind(unexpected);
expect.notifyPendingPromise = notifyPendingPromise;
expect.hook = function (fn) {
unexpected._expect = fn(unexpected._expect.bind(unexpected));
};
// TODO For testing purpose while we don't have all the pieces yet
expect.parseAssertion = unexpected.parseAssertion.bind(unexpected);
return expect;
}
function calculateLimits(items) {
return items.reduce(function (result, item) {
result.minimum += item.minimum;
result.maximum += item.maximum;
return result;
}, { minimum: 0, maximum: 0 });
}
Unexpected.prototype.throwAssertionNotFoundError = function (subject, testDescriptionString, args) {
var candidateHandlers = this.assertions[testDescriptionString];
var that = this;
if (candidateHandlers) {
this.fail({
message: function (output) {
var subjectOutput = function (output) {
output.appendInspected(subject);
};
var argsOutput = function (output) {
output.appendItems(args, ', ');
};
output.append(createStandardErrorMessage(output.clone(), subjectOutput, testDescriptionString, argsOutput)).nl()
.indentLines();
output.i().error('The assertion does not have a matching signature for:').nl()
.indentLines().i().text('<').text(that.findTypeOf(subject).name).text('>').sp().text(testDescriptionString);
args.forEach(function (arg, i) {
output.sp().text('<').text(that.findTypeOf(arg).name).text('>');
});
output
.outdentLines()
.nl()
.i().text('did you mean:')
.indentLines()
.nl();
var assertionDeclarations = Object.keys(candidateHandlers.reduce(function (result, handler) {
result[handler.declaration] = true;
return result;
}, {})).sort();
assertionDeclarations.forEach(function (declaration, i) {
output.nl(i > 0 ? 1 : 0).i().text(declaration);
});
output.outdentLines();
}
});
}
var assertionsWithScore = [];
var assertionStrings = [];
var instance = this;
while (instance) {
Array.prototype.push.apply(assertionStrings, Object.keys(instance.assertions));
instance = instance.parent;
}
function compareAssertions(a, b) {
var aAssertion = that.lookupAssertionRule(subject, a, args);
var bAssertion = that.lookupAssertionRule(subject, b, args);
if (!aAssertion && !bAssertion) {
return 0;
}
if (aAssertion && !bAssertion) {
return -1;
}
if (!aAssertion && bAssertion) {
return 1;
}
return compareSpecificities(aAssertion.specificity, bAssertion.specificity);
}
assertionStrings.forEach(function (assertionString) {
var score = leven(testDescriptionString, assertionString);
assertionsWithScore.push({
assertion: assertionString,
score: score
});
}, this);
var bestMatch = assertionsWithScore.sort(function (a, b) {
var c = a.score - b.score;
if (c !== 0) {
return c;
}
if (a.assertion < b.assertion) {
return -1;
} else {
return 1;
}
}).slice(0, 10).filter(function (assertionsWithScore, i, arr) {
return Math.abs(assertionsWithScore.score - arr[0].score) <= 2;
}).sort(function (a, b) {
var c = compareAssertions(a.assertion, b.assertion);
if (c !== 0) {
return c;
}
return a.score - b.score;
})[0];
this.fail({
errorMode: 'bubbleThrough',
message: function (output) {
output.error("Unknown assertion '").jsString(testDescriptionString)
.error("', did you mean: '").jsString(bestMatch.assertion).error("'");
}
});
};
Unexpected.prototype.lookupAssertionRule = function (subject, testDescriptionString, args, requireAssertionSuffix) {
var that = this;
if (typeof testDescriptionString !== 'string') {
throw new Error('The expect function requires the second parameter to be a string or an expect.it.');
}
var handlers;
var instance = this;
while (instance) {
var instanceHandlers = instance.assertions[testDescriptionString];
if (instanceHandlers) {
handlers = handlers ? handlers.concat(instanceHandlers) : instanceHandlers;
}
instance = instance.parent;
}
if (!handlers) {
return null;
}
var cachedTypes = {};
function findTypeOf(value, key) {
var type = cachedTypes[key];
if (!type) {
type = that.findTypeOf(value);
cachedTypes[key] = type;
}
return type;
}
function matches(value, assertionType, key, relaxed) {
if (assertionType.is('assertion') && typeof value === 'string') {
return true;
}
if (relaxed) {
if (assertionType.identify === false) {
return that.types.some(function (type) {
return type.identify && type.is(assertionType) && type.identify(value);
});
}
return assertionType.identify(value);
} else {
return findTypeOf(value, key).is(assertionType);
}
}
function matchesHandler(handler, relaxed) {
if (!matches(subject, handler.subject.type, 'subject', relaxed)) {
return false;
}
if (requireAssertionSuffix && !handler.args.some(isAssertionArg)) {
return false;
}
var requireArgumentsLength = calculateLimits(handler.args);
if (args.length < requireArgumentsLength.minimum || requireArgumentsLength.maximum < args.length) {
return false;
} else if (args.length === 0 && requireArgumentsLength.maximum === 0) {
return true;
}
var lastRequirement = handler.args[handler.args.length - 1];
return args.every(function (arg, i) {
if (i < handler.args.length - 1) {
return matches(arg, handler.args[i].type, i, relaxed);
} else {
return matches(arg, lastRequirement.type, i, relaxed);
}
});
}
var j, handler;
for (j = 0; j < handlers.length; j += 1) {
handler = handlers[j];
if (matchesHandler(handler)) {
return handler;
}
}
for (j = 0; j < handlers.length; j += 1) {
handler = handlers[j];
if (matchesHandler(handler, true)) {
return handler;
}
}
return null;
};
function makeExpectFunction(unexpected) {
var expect = installExpectMethods(unexpected);
unexpected.expect = expect;
return expect;
}
Unexpected.prototype.setErrorMessage = function (err) {
err.serializeMessage(this.outputFormat());
};
Unexpected.prototype._expect = function expect(context, args) {
var that = this;
var subject = args[0];
var testDescriptionString = args[1];
if (args.length < 2) {
throw new Error('The expect function requires at least two parameters.');
} else if (testDescriptionString && testDescriptionString._expectIt) {
return that.expect.withError(function () {
return testDescriptionString(subject);
}, function (err) {
that.fail(err);
});
}
function executeExpect(context, subject, testDescriptionString, args) {
var assertionRule = that.lookupAssertionRule(subject, testDescriptionString, args);
if (!assertionRule) {
var tokens = testDescriptionString.split(' ');
OUTER: for (var n = tokens.length - 1; n > 0 ; n -= 1) {
var prefix = tokens.slice(0, n).join(' ');
var remainingTokens = tokens.slice(n);
var argsWithAssertionPrepended = [ remainingTokens.join(' ') ].concat(args);
assertionRule = that.lookupAssertionRule(subject, prefix, argsWithAssertionPrepended, true);
if (assertionRule) {
// Found the longest prefix of the string that yielded a suitable assertion for the given subject and args
// To avoid bogus error messages when shifting later (#394) we require some prefix of the remaining tokens
// to be a valid assertion name:
for (var i = 1 ; i < remainingTokens.length ; i += 1) {
if (that.assertions.hasOwnProperty(remainingTokens.slice(0, i + 1).join(' '))) {
testDescriptionString = prefix;
args = argsWithAssertionPrepended;
break OUTER;
}
}
}
}
if (!assertionRule) {
that.throwAssertionNotFoundError(subject, testDescriptionString, args);
}
}
if (assertionRule && assertionRule.unexpected && assertionRule.unexpected !== that) {
return assertionRule.unexpected.expect.apply(assertionRule.unexpected.expect, [subject, testDescriptionString].concat(args));
}
var flags = extend({}, assertionRule.flags);
var wrappedExpect = function (subject, testDescriptionString) {
if (arguments.length === 0) {
throw new Error('The expect function requires at least one parameter.');
} else if (arguments.length === 1) {
return addAdditionalPromiseMethods(makePromise.resolve(subject), wrappedExpect, subject);
} else if (testDescriptionString && testDescriptionString._expectIt) {
wrappedExpect.errorMode = 'nested';
return wrappedExpect.withError(function () {
return testDescriptionString(subject);
}, function (err) {
wrappedExpect.fail(err);
});
}
testDescriptionString = utils.forwardFlags(testDescriptionString, flags);
var args = new Array(arguments.length - 2);
for (var i = 2 ; i < arguments.length ; i += 1) {
args[i - 2] = arguments[i];
}
return wrappedExpect.callInNestedContext(function () {
return executeExpect(context.child(), subject, testDescriptionString, args);
});
};
utils.setPrototypeOfOrExtend(wrappedExpect, that._wrappedExpectProto);
wrappedExpect.context = context;
wrappedExpect.execute = wrappedExpect;
wrappedExpect.alternations = assertionRule.alternations;
wrappedExpect.flags = flags;
wrappedExpect.subject = subject;
wrappedExpect.testDescription = testDescriptionString;
wrappedExpect.args = args;
wrappedExpect.assertionRule = assertionRule;
wrappedExpect.subjectOutput = function (output) {
output.appendInspected(subject);
};
wrappedExpect.argsOutput = args.map(function (arg, i) {
var argRule = wrappedExpect.assertionRule.args[i];
if (typeof arg === 'string' && (argRule && argRule.type.is('assertion') || wrappedExpect._getAssertionIndices().indexOf(i) >= 0)) {
return new AssertionString(arg);
}
return function (output) {
output.appendInspected(arg);
};
});
// Eager-compute these properties in browsers that don't support getters
// (Object.defineProperty might be polyfilled by es5-sham):
if (!Object.__defineGetter__) {
wrappedExpect.subjectType = wrappedExpect._getSubjectType();
wrappedExpect.argTypes = wrappedExpect._getArgTypes();
}
return oathbreaker(assertionRule.handler.apply(wrappedExpect, [wrappedExpect, subject].concat(args)));
}
try {
var result = executeExpect(context, subject, testDescriptionString, Array.prototype.slice.call(args, 2));
if (isPendingPromise(result)) {
that.expect.notifyPendingPromise(result);
result = result.then(undefined, function (e) {
if (e && e._isUnexpected && context.level === 0) {
that.setErrorMessage(e);
}
throw e;
});
} else {
if (!result || typeof result.then !== 'function') {
result = makePromise.resolve(result);
}
}
return addAdditionalPromiseMethods(result, that.expect, subject);
} catch (e) {
if (e && e._isUnexpected) {
var newError = e;
if (typeof mochaPhantomJS !== 'undefined') {
newError = e.clone();
}
if (context.level === 0) {
that.setErrorMessage(newError);
}
throw newError;
}
throw e;
}
};
Unexpected.prototype.async = function (cb) {
var that = this;
function asyncMisusage(message) {
that._isAsync = false;
that.expect.fail(function (output) {
output.error(message).nl()
.text("Usage: ").nl()
.text("it('test description', expect.async(function () {").nl()
.indentLines()
.i().text("return expect('test.txt', 'to have content', 'Content read asynchroniously');").nl()
.outdentLines()
.text("});");
});
}
if (typeof cb !== 'function' || cb.length !== 0) {
asyncMisusage("expect.async requires a callback without arguments.");
}
return function (done) {
if (that._isAsync) {
asyncMisusage("expect.async can't be within a expect.async context.");
}
that._isAsync = true;
if (typeof done !== 'function') {
asyncMisusage("expect.async should be called in the context of an it-block\n" +
"and the it-block should supply a done callback.");
}
var result;
try {
result = cb();
} finally {
that._isAsync = false;
}
if (!result || typeof result.then !== 'function') {
asyncMisusage("expect.async requires the block to return a promise or throw an exception.");
}
result.then(function () {
that._isAsync = false;
done();
}, function (err) {
that._isAsync = false;
done(err);
});
};
};
Unexpected.prototype.diff = function (a, b, output, recursions, seen) {
output = output || this.createOutput();
var that = this;
var maxRecursions = 100;
recursions = typeof recursions === 'number' ? recursions : maxRecursions;
if (recursions <= 0) {
// detect recursive loops in the structure
seen = seen || [];
if (seen.indexOf(a) !== -1) {
throw new Error('Cannot compare circular structures');
}
seen.push(a);
}
return makeDiffResultBackwardsCompatible(this.findCommonType(a, b).diff(a, b, output, function (actual, expected) {
return that.diff(actual, expected, output.clone(), recursions - 1, seen);
}, function (v, depth) {
return output.clone().appendInspected(v, depth);
}, function (actual, expected) {
return that.equal(actual, expected);
}));
};
Unexpected.prototype.toString = function () {
var assertions = this.assertions;
var seen = {};
var declarations = [];
var pen = magicpen();
Object.keys(assertions).sort().forEach(function (key) {
assertions[key].forEach(function (assertion) {
if (!seen[assertion.declaration]) {
declarations.push(assertion.declaration);
seen[assertion.declaration] = true;
}
});
});
declarations.forEach(function (declaration) {
pen.text(declaration).nl();
});
return pen.toString();
};
Unexpected.prototype.clone = function () {
var clonedAssertions = {};
Object.keys(this.assertions).forEach(function (assertion) {
clonedAssertions[assertion] = [].concat(this.assertions[assertion]);
}, this);
var unexpected = new Unexpected({
assertions: clonedAssertions,
types: [].concat(this.types),
typeByName: extend({}, this.typeByName),
output: this.output.clone(),
format: this.outputFormat(),
installedPlugins: [].concat(this.installedPlugins)
});
// Install the hooks:
unexpected._expect = this._expect;
return makeExpectFunction(unexpected);
};
Unexpected.prototype.child = function () {
var childUnexpected = new Unexpected({
assertions: {},
types: [],
typeByName: {},
output: this.output.clone(),
format: this.outputFormat(),
installedPlugins: []
});
var parent = childUnexpected.parent = this;
var childExpect = makeExpectFunction(childUnexpected);
childExpect.exportAssertion = function (testDescription, handler) {
parent.addAssertion(testDescription, handler, childUnexpected);
return this;
};
childExpect.exportType = function (type) {
parent.addType(type, childUnexpected);
return this;
};
childExpect.exportStyle = function (name, handler) {
parent.addStyle(name, function () { // ...
var childOutput = childExpect.createOutput(this.format);
this.append(handler.apply(childOutput, arguments) || childOutput);
});
return this;
};
return childExpect;
};
Unexpected.prototype.outputFormat = function (format) {
if (typeof format === 'undefined') {
return this._outputFormat;
} else {
this._outputFormat = format;
return this.expect;
}
};
Unexpected.prototype.createOutput = function (format) {
var that = this;
var output = this.output.clone(format || 'text');
output.addStyle('appendInspected', function (value, depth) {
this.append(that.inspect(value, depth, this.clone()));
});
return output;
};
Unexpected.create = function () {
var unexpected = new Unexpected();
return makeExpectFunction(unexpected);
};
var expandAssertion = (function () {
function isFlag(token) {
return token.slice(0, 1) === '[' && token.slice(-1) === ']';
}
function isAlternation(token) {
return token.slice(0, 1) === '(' && token.slice(-1) === ')';
}
function removeEmptyStrings(texts) {
return texts.filter(function (text) {
return text !== '';
});
}
function createPermutations(tokens, index) {
if (index === tokens.length) {
return [{ text: '', flags: {}, alternations: [] }];
}
var token = tokens[index];
var tail = createPermutations(tokens, index + 1);
if (isFlag(token)) {
var flag = token.slice(1, -1);
return tail.map(function (pattern) {
var flags = {};
flags[flag] = true;
return {
text: flag + ' ' + pattern.text,
flags: extend(flags, pattern.flags),
alternations: pattern.alternations
};
}).concat(tail.map(function (pattern) {
var flags = {};
flags[flag] = false;
return {
text: pattern.text,
flags: extend(flags, pattern.flags),
alternations: pattern.alternations
};
}));
} else if (isAlternation(token)) {
return token
.substr(1, token.length - 2) // Remove parentheses
.split(/\|/)
.reduce(function (result, alternation) {
return result.concat(tail.map(function (pattern) {
return {
// Make sure that an empty alternation doesn't produce two spaces:
text: alternation ? alternation + pattern.text : pattern.text.replace(/^ /, ''),
flags: pattern.flags,
alternations: [alternation].concat(pattern.alternations)
};
}));
}, []);
} else {
return tail.map(function (pattern) {
return {
text: token + pattern.text,
flags: pattern.flags,
alternations: pattern.alternations
};
});
}
}
return function (pattern) {
pattern = pattern.replace(/(\[[^\]]+\]) ?/g, '$1');
var splitRegex = /\[[^\]]+\]|\([^\)]+\)/g;
var tokens = [];
var m;
var lastIndex = 0;
while ((m = splitRegex.exec(pattern))) {
tokens.push(pattern.slice(lastIndex, m.index));
tokens.push(pattern.slice(m.index, splitRegex.lastIndex));
lastIndex = splitRegex.lastIndex;
}
tokens.push(pattern.slice(lastIndex));
tokens = removeEmptyStrings(tokens);
var permutations = createPermutations(tokens, 0);
permutations.forEach(function (permutation) {
permutation.text = permutation.text.trim();
if (permutation.text === '') {
// This can only happen if the pattern only contains flags
throw new Error("Assertion patterns must not only contain flags");
}
});
return permutations;
};
}());
function ensureValidUseOfParenthesesOrBrackets(pattern) {
var counts = {
'[': 0,
']': 0,
'(': 0,
')': 0
};
for (var i = 0; i < pattern.length; i += 1) {
var c = pattern.charAt(i);
if (c in counts) {
counts[c] += 1;
}
if (c === ']' && counts['['] >= counts[']']) {
if (counts['['] === counts[']'] + 1) {
throw new Error("Assertion patterns must not contain flags with brackets: '" + pattern + "'");
}
if (counts['('] !== counts[')']) {
throw new Error("Assertion patterns must not contain flags with parentheses: '" + pattern + "'");
}
if (pattern.charAt(i - 1) === '[') {
throw new Error("Assertion patterns must not contain empty flags: '" + pattern + "'");
}
} else if (c === ')' && counts['('] >= counts[')']) {
if (counts['('] === counts[')'] + 1) {
throw new Error("Assertion patterns must not contain alternations with parentheses: '" + pattern + "'");
}
if (counts['['] !== counts[']']) {
throw new Error("Assertion patterns must not contain alternations with brackets: '" + pattern + "'");
}
}
}
if (counts['['] !== counts[']']) {
throw new Error("Assertion patterns must not contain unbalanced brackets: '" + pattern + "'");
}
if (counts['('] !== counts[')']) {
throw new Error("Assertion patterns must not contain unbalanced parentheses: '" + pattern + "'");
}
}
module.exports = Unexpected;
},{"1":1,"10":10,"11":11,"12":12,"13":13,"16":16,"19":19,"3":3,"4":4,"40":40,"44":44,"6":6,"7":7,"8":8,"9":9}],3:[function(require,module,exports){
var utils = require(19);
var defaultDepth = require(8);
var useFullStackTrace = require(18);
var makeDiffResultBackwardsCompatible = require(10);
var errorMethodBlacklist = ['message', 'line', 'sourceId', 'sourceURL', 'stack', 'stackArray'].reduce(function (result, prop) {
result[prop] = true;
return result;
}, {});
function UnexpectedError(expect, parent) {
this.errorMode = (expect && expect.errorMode) || 'default';
var base = Error.call(this, '');
if (Error.captureStackTrace) {
Error.captureStackTrace(this, UnexpectedError);
} else {
// Throw the error to make sure it has its stack serialized:
try { throw base; } catch (err) {}
this.stack = base.stack;
}
this.expect = expect;
this.parent = parent || null;
this.name = 'UnexpectedError';
}
UnexpectedError.prototype = Object.create(Error.prototype);
UnexpectedError.prototype.useFullStackTrace = useFullStackTrace;
var missingOutputMessage = 'You must either provide a format or a magicpen instance';
UnexpectedError.prototype.outputFromOptions = function (options) {
if (!options) {
throw new Error(missingOutputMessage);
}
if (typeof options === 'string') {
return this.expect.createOutput(options);
}
if (options.isMagicPen) {
return options.clone();
}
if (options.output) {
return options.output.clone();
}
if (options.format) {
return this.expect.createOutput(options.format);
}
throw new Error(missingOutputMessage);
};
UnexpectedError.prototype._isUnexpected = true;
UnexpectedError.prototype.isUnexpected = true;
UnexpectedError.prototype.buildDiff = function (options) {
var output = this.outputFromOptions(options);
var expect = this.expect;
return this.createDiff && makeDiffResultBackwardsCompatible(this.createDiff(output, function (actual, expected) {
return expect.diff(actual, expected, output.clone());
}, function (v, depth) {
return output.clone().appendInspected(v, (depth || defaultDepth) - 1);
}, function (actual, expected) {
return expect.equal(actual, expected);
}));
};
UnexpectedError.prototype.getDefaultErrorMessage = function (options) {
var output = this.outputFromOptions(options);
if (this.expect.testDescription) {
output.append(this.expect.standardErrorMessage(output.clone(), options));
} else if (typeof this.output === 'function') {
this.output.call(output, output);
}
var errorWithDiff = this;
while (!errorWithDiff.createDiff && errorWithDiff.parent) {
errorWithDiff = errorWithDiff.parent;
}
if (errorWithDiff && errorWithDiff.createDiff) {
var comparison = errorWithDiff.buildDiff(options);
if (comparison) {
output.nl(2).append(comparison);
}
}
return output;
};
UnexpectedError.prototype.getNestedErrorMessage = function (options) {
var output = this.outputFromOptions(options);
if (this.expect.testDescription) {
output.append(this.expect.standardErrorMessage(output.clone(), options));
} else if (typeof this.output === 'function') {
this.output.call(output, output);
}
var parent = this.parent;
while (parent.getErrorMode() === 'bubble') {
parent = parent.parent;
}
if (typeof options === 'string') {
options = { format: options };
} else if (options && options.isMagicPen) {
options = { output: options };
}
output.nl()
.indentLines()
.i().block(parent.getErrorMessage(utils.extend({}, options || {}, {
compact: this.expect.subject === parent.expect.subject
})));
return output;
};
UnexpectedError.prototype.getDefaultOrNestedMessage = function (options) {
if (this.hasDiff()) {
return this.getDefaultErrorMessage(options);
} else {
return this.getNestedErrorMessage(options);
}
};
UnexpectedError.prototype.hasDiff = function () {
return !!this.getDiffMethod();
};
UnexpectedError.prototype.getDiffMethod = function () {
var errorWithDiff = this;
while (!errorWithDiff.createDiff && errorWithDiff.parent) {
errorWithDiff = errorWithDiff.parent;
}
return errorWithDiff && errorWithDiff.createDiff || null;
};
UnexpectedError.prototype.getDiff = function (options) {
var errorWithDiff = this;
while (!errorWithDiff.createDiff && errorWithDiff.parent) {
errorWithDiff = errorWithDiff.parent;
}
return errorWithDiff && errorWithDiff.buildDiff(options);
};
UnexpectedError.prototype.getDiffMessage = function (options) {
var output = this.outputFromOptions(options);
var comparison = this.getDiff(options);
if (comparison) {
output.append(comparison);
} else if (this.expect.testDescription) {
output.append(this.expect.standardErrorMessage(output.clone(), options));
} else if (typeof this.output === 'function') {
this.output.call(output, output);
}
return output;
};
UnexpectedError.prototype.getErrorMode = function () {
if (!this.parent) {
switch (this.errorMode) {
case 'default':
case 'bubbleThrough':
return this.errorMode;
default:
return 'default';
}
} else {
return this.errorMode;
}
};
UnexpectedError.prototype.getErrorMessage = function (options) {
// Search for any parent error that has an error mode of 'bubbleThrough' through on the
// error these should be bubbled to the top
var errorWithBubbleThrough = this.parent;
while (errorWithBubbleThrough && errorWithBubbleThrough.getErrorMode() !== 'bubbleThrough') {
errorWithBubbleThrough = errorWithBubbleThrough.parent;
}
if (errorWithBubbleThrough) {
return errorWithBubbleThrough.getErrorMessage(options);
}
var errorMode = this.getErrorMode();
switch (errorMode) {
case 'nested': return this.getNestedErrorMessage(options);
case 'default': return this.getDefaultErrorMessage(options);
case 'bubbleThrough': return this.getDefaultErrorMessage(options);
case 'bubble': return this.parent.getErrorMessage(options);
case 'diff': return this.getDiffMessage(options);
case 'defaultOrNested': return this.getDefaultOrNestedMessage(options);
default: throw new Error("Unknown error mode: '" + errorMode + "'");
}
};
function findStackStart(lines) {
for (var i = lines.length - 1; 0 <= i; i -= 1) {
if (lines[i] === '') {
return i + 1;
}
}
return -1;
}
UnexpectedError.prototype.serializeMessage = function (outputFormat) {
if (!this._hasSerializedErrorMessage) {
var htmlFormat = outputFormat === 'html';
if (htmlFormat) {
if (!('htmlMessage' in this)) {
this.htmlMessage = this.getErrorMessage({format: 'html'}).toString();
}
}
this.message = '\n' + this.getErrorMessage({
format: htmlFormat ? 'text' : outputFormat
}).toString() + '\n';
if (this.originalError && this.originalError instanceof Error && typeof this.originalError.stack === 'string') {
// The stack of the original error looks like this:
// <constructor name>: <error message>\n<actual stack trace>
// Try to get hold of <actual stack trace> and append it
// to the error message of this error:
var index = this.originalError.stack.indexOf(this.originalError.message);
if (index === -1) {
// Phantom.js doesn't include the error message in the stack property
this.stack = this.message + '\n' + this.originalError.stack;
} else {
this.stack = this.message + this.originalError.stack.substr(index + this.originalError.message.length);
}
} else if (/^(Unexpected)?Error:?\n/.test(this.stack)) {
// Fix for Jest that does not seem to capture the error message
this.stack = this.stack.replace(/^(Unexpected)?Error:?\n/, this.message);
}
if (this.stack && !this.useFullStackTrace) {
var newStack = [];
var removedFrames = false;
var lines = this.stack.split(/\n/);
var stackStart = findStackStart(lines);
lines.forEach(function (line, i) {
if (stackStart <= i && (/node_modules\/unexpected(?:-[^\/]+)?\//).test(line)) {
removedFrames = true;
} else {
newStack.push(line);
}
});
if (removedFrames) {
var indentation = (/^(\s*)/).exec(lines[lines.length - 1])[1];
if (outputFormat === 'html') {
newStack.push(indentation + 'set the query parameter full-trace=true to see the full stack trace');
} else {
newStack.push(indentation + 'set UNEXPECTED_FULL_TRACE=true to see the full stack trace');
}
}
this.stack = newStack.join('\n');
}
this._hasSerializedErrorMessage = true;
}
};
UnexpectedError.prototype.clone = function () {
var that = this;
var newError = new UnexpectedError(this.expect);
Object.keys(that).forEach(function (key) {
if (!errorMethodBlacklist[key]) {
newError[key] = that[key];
}
});
return newError;
};
UnexpectedError.prototype.getLabel = function () {
var currentError = this;
while (currentError && !currentError.label) {
currentError = currentError.parent;
}
return (currentError && currentError.label) || null;
};
UnexpectedError.prototype.getParents = function () {
var result = [];
var parent = this.parent;
while (parent) {
result.push(parent);
parent = parent.parent;
}
return result;
};
UnexpectedError.prototype.getAllErrors = function () {
var result = this.getParents();
result.unshift(this);
return result;
};
if (Object.__defineGetter__) {
Object.defineProperty(UnexpectedError.prototype, 'htmlMessage', {
enumerable: true,
get: function () {
return this.getErrorMessage({ format: 'html' }).toString();
}
});
}
module.exports = UnexpectedError;
},{"10":10,"18":18,"19":19,"8":8}],4:[function(require,module,exports){
module.exports = function addAdditionalPromiseMethods(promise, expect, subject) {
promise.and = function () { // ...
var args = Array.prototype.slice.call(arguments);
function executeAnd() {
if (expect.findTypeOf(args[0]).is('expect.it')) {
return addAdditionalPromiseMethods(args[0](subject), expect, subject);
} else {
return expect.apply(expect, [subject].concat(args));
}
}
if (this.isFulfilled()) {
return executeAnd();
} else {
return addAdditionalPromiseMethods(this.then(executeAnd), expect, subject);
}
};
return promise;
};
},{}],5:[function(require,module,exports){
(function (Buffer){
/*global setTimeout*/
var utils = require(19);
var arrayChanges = require(24);
var arrayChangesAsync = require(23);
var throwIfNonUnexpectedError = require(16);
var objectIs = utils.objectIs;
var isRegExp = utils.isRegExp;
var extend = utils.extend;
module.exports = function (expect) {
expect.addAssertion('<any> [not] to be (ok|truthy)', function (expect, subject) {
var not = !!expect.flags.not;
var condition = !!subject;
if (condition === not) {
expect.fail();
}
});
expect.addAssertion('<any> [not] to be (ok|truthy) <string>', function (expect, subject, message) {
var not = !!expect.flags.not;
var condition = !!subject;
if (condition === not) {
expect.fail({
errorMode: 'bubble',
message: message
});
}
});
expect.addAssertion('<any> [not] to be <any>', function (expect, subject, value) {
expect(objectIs(subject, value), '[not] to be truthy');
});
expect.addAssertion('<string> [not] to be <string>', function (expect, subject, value) {
expect(subject, '[not] to equal', value);
});
expect.addAssertion('<boolean> [not] to be true', function (expect, subject) {
expect(subject, '[not] to be', true);
});
expect.addAssertion('<boolean> [not] to be false', function (expect, subject) {
expect(subject, '[not] to be', false);
});
expect.addAssertion('<any> [not] to be falsy', function (expect, subject) {
expect(subject, '[!not] to be truthy');
});
expect.addAssertion('<any> [not] to be falsy <string>', function (expect, subject, message) {
var not = !!expect.flags.not;
var condition = !!subject;
if (condition !== not) {
expect.fail({
errorMode: 'bubble',
message: message
});
}
});
expect.addAssertion('<any> [not] to be null', function (expect, subject) {
expect(subject, '[not] to be', null);
});
expect.addAssertion('<any> [not] to be undefined', function (expect, subject) {
expect(typeof subject === 'undefined', '[not] to be truthy');
});
expect.addAssertion('<any> to be defined', function (expect, subject) {
expect(subject, 'not to be undefined');
});
expect.addAssertion('<number|NaN> [not] to be NaN', function (expect, subject) {
expect(isNaN(subject), '[not] to be truthy');
});
expect.addAssertion('<number> [not] to be close to <number> <number?>', function (expect, subject, value, epsilon) {
expect.errorMode = 'bubble';
if (typeof epsilon !== 'number') {
epsilon = 1e-9;
}
expect.withError(function () {
expect(Math.abs(subject - value), '[not] to be less than or equal to', epsilon);
}, function (e) {
expect.fail(function (output) {
output.error('expected ')
.appendInspected(subject).sp()
.error(expect.testDescription).sp()
.appendInspected(value).sp()
.text('(epsilon: ')
.jsNumber(epsilon.toExponential())
.text(')');
});
});
});
expect.addAssertion('<any> [not] to be (a|an) <type>', function (expect, subject, type) {
expect.argsOutput[0] = function (output) {
output.text(type.name);
};
expect(type.identify(subject), '[not] to be true');
});
expect.addAssertion('<any> [not] to be (a|an) <string>', function (expect, subject, typeName) {
typeName = /^reg(?:exp?|ular expression)$/.test(typeName) ? 'regexp' : typeName;
expect.argsOutput[0] = function (output) {
output.jsString(typeName);
};
if (!expect.getType(typeName)) {
expect.errorMode = 'nested';
expect.fail(function (output) {
output.error('Unknown type:').sp().jsString(typeName);
});
}
expect(expect.subjectType.is(typeName), '[not] to be truthy');
});
expect.addAssertion('<any> [not] to be (a|an) <function>', function (expect, subject, Constructor) {
var className = utils.getFunctionName(Constructor);
if (className) {
expect.argsOutput[0] = function (output) {
output.text(className);
};
}
expect(subject instanceof Constructor, '[not] to be truthy');
});
expect.addAssertion('<any> [not] to be one of <array>', function (expect, subject, superset) {
var found = false;
for (var i = 0; i < superset.length; i += 1) {
found = found || objectIs(subject, superset[i]);
}
if (found === expect.flags.not) { expect.fail(); }
});
// Alias for common '[not] to be (a|an)' assertions
expect.addAssertion('<any> [not] to be an (object|array)', function (expect, subject) {
expect(subject, '[not] to be an', expect.alternations[0]);
});
expect.addAssertion('<any> [not] to be a (boolean|number|string|function|regexp|regex|regular expression)', function (expect, subject) {
expect(subject, '[not] to be a', expect.alternations[0]);
});
expect.addAssertion('<string> to be (the empty|an empty|a non-empty) string', function (expect, subject) {
expect(subject, expect.alternations[0] === 'a non-empty' ? 'not to be empty' : 'to be empty');
});
expect.addAssertion('<array-like> to be (the empty|an empty|a non-empty) array', function (expect, subject) {
expect(subject, expect.alternations[0] === 'a non-empty' ? 'not to be empty' : 'to be empty');
});
expect.addAssertion('<string> to match <regexp>', function (expect, subject, regexp) {
return expect.withError(function () {
var captures = subject.match(regexp);
expect(captures, 'to be truthy');
return captures;
}, function (e) {
e.label = 'should match';
expect.fail(e);
});
});
expect.addAssertion('<string> not to match <regexp>', function (expect, subject, regexp) {
return expect.withError(function () {
expect(regexp.test(subject), 'to be false');
}, function (e) {
expect.fail({
label: 'should not match',
diff: function (output) {
output.inline = false;
var lastIndex = 0;
function flushUntilIndex(i) {
if (i > lastIndex) {
output.text(subject.substring(lastIndex, i));
lastIndex = i;
}
}
subject.replace(new RegExp(regexp.source, 'g'), function ($0, index) {
flushUntilIndex(index);
lastIndex += $0.length;
output.removedHighlight($0);
});
flushUntilIndex(subject.length);
return output;
}
});
});
});
expect.addAssertion('<object|function> [not] to have own property <string>', function (expect, subject, key) {
expect(subject.hasOwnProperty(key), '[not] to be truthy');
return subject[key];
});
expect.addAssertion('<object|function> [not] to have property <string>', function (expect, subject, key) {
expect(subject[key], '[!not] to be undefined');
return subject[key];
});
expect.addAssertion('<object|function> to have [own] property <string> <any>', function (expect, subject, key, expectedPropertyValue) {
return expect(subject, 'to have [own] property', key).then(function (actualPropertyValue) {
expect.argsOutput = function () {
this.appendInspected(key).sp().error('with a value of').sp().appendInspected(expectedPropertyValue);
};
expect(actualPropertyValue, 'to equal', expectedPropertyValue);
return actualPropertyValue;
});
});
expect.addAssertion('<object|function> [not] to have [own] properties <array>', function (expect, subject, properties) {
properties.forEach(function (property) {
expect(subject, '[not] to have [own] property', property);
});
});
expect.addAssertion('<object|function> to have [own] properties <object>', function (expect, subject, properties) {
expect.withError(function () {
Object.keys(properties).forEach(function (property) {
var value = properties[property];
if (typeof value === 'undefined') {
expect(subject, 'not to have [own] property', property);
} else {
expect(subject, 'to have [own] property', property, value);
}
});
}, function (e) {
expect.fail({
diff: function (output, diff) {
output.inline = false;
var expected = extend({}, properties);
var actual = {};
var propertyNames = expect.findTypeOf(subject).getKeys(subject);
// Might put duplicates into propertyNames, but that does not matter:
for (var propertyName in subject) {
if (!subject.hasOwnProperty(propertyName)) {
propertyNames.push(propertyName);
}
}
propertyNames.forEach(function (propertyName) {
if ((!expect.flags.own || subject.hasOwnProperty(propertyName)) && !(propertyName in properties)) {
expected[propertyName] = subject[propertyName];
}
if ((!expect.flags.own || subject.hasOwnProperty(propertyName)) && !(propertyName in actual)) {
actual[propertyName] = subject[propertyName];
}
});
return utils.wrapConstructorNameAroundOutput(diff(actual, expected), subject);
}
});
});
});
expect.addAssertion('<string|array-like> [not] to have length <number>', function (expect, subject, length) {
if (!expect.flags.not) {
expect.errorMode = 'nested';
}
expect(subject.length, '[not] to be', length);
});
expect.addAssertion('<string|array-like> [not] to be empty', function (expect, subject) {
expect(subject, '[not] to have length', 0);
});
expect.addAssertion('<string|array-like|object> to be non-empty', function (expect, subject) {
expect(subject, 'not to be empty');
});
expect.addAssertion('<object> to [not] [only] have keys <array>', function (expect, subject, keys) {
var keysInSubject = {};
var subjectKeys = expect.findTypeOf(subject).getKeys(subject);
subjectKeys.forEach(function (key) {
keysInSubject[key] = true;
});
if (expect.flags.not && keys.length === 0) {
return;
}
var hasKeys = keys.every(function (key) {
return keysInSubject[key];
});
if (expect.flags.only) {
expect(hasKeys, 'to be truthy');
expect.withError(function () {
expect(subjectKeys.length === keys.length, '[not] to be truthy');
}, function (err) {
expect.fail({
diff: !expect.flags.not && function (output, diff, inspect, equal) {
output.inline = true;
var keyInValue = {};
keys.forEach(function (key) {
keyInValue[key] = true;
});
var subjectType = expect.findTypeOf(subject);
var subjectIsArrayLike = subjectType.is('array-like');
subjectType.prefix(output, subject);
output.nl().indentLines();
subjectKeys.forEach(function (key, index) {
output.i().block(function () {
this.property(key, inspect(subject[key]), subjectIsArrayLike);
subjectType.delimiter(this, index, subjectKeys.length);
if (!keyInValue[key]) {
this.sp().annotationBlock(function () {
this.error('should be removed');
});
}
}).nl();
});
output.outdentLines();
subjectType.suffix(output, subject);
return output;
}
});
});
} else {
expect(hasKeys, '[not] to be truthy');
}
});
expect.addAssertion('<object> [not] to be empty', function (expect, subject) {
if (expect.flags.not && !expect.findTypeOf(subject).getKeys(subject).length) {
return expect.fail();
}
expect(subject, 'to [not] only have keys', []);
});
expect.addAssertion('<object> not to have keys <array>', function (expect, subject, keys) {
expect(subject, 'to not have keys', keys);
});
expect.addAssertion('<object> not to have key <string>', function (expect, subject, value) {
expect(subject, 'to not have keys', [ value ]);
});
expect.addAssertion('<object> not to have keys <string+>', function (expect, subject, value) {
expect(subject, 'to not have keys', Array.prototype.slice.call(arguments, 2));
});
expect.addAssertion('<object> to [not] [only] have key <string>', function (expect, subject, value) {
expect(subject, 'to [not] [only] have keys', [ value ]);
});
expect.addAssertion('<object> to [not] [only] have keys <string+>', function (expect, subject) {
expect(subject, 'to [not] [only] have keys', Array.prototype.slice.call(arguments, 2));
});
expect.addAssertion('<string> [not] to contain <string+>', function (expect, subject) {
var args = Array.prototype.slice.call(arguments, 2);
args.forEach(function (arg) {
if (arg === '') {
throw new Error("The '" + expect.testDescription + "' assertion does not support the empty string");
}
});
expect.withError(function () {
args.forEach(function (arg) {
expect(subject.indexOf(arg) !== -1, '[not] to be truthy');
});
}, function (e) {
expect.fail({
diff: function (output) {
output.inline = false;
var lastIndex = 0;
function flushUntilIndex(i) {
if (i > lastIndex) {
output.text(subject.substring(lastIndex, i));
lastIndex = i;
}
}
if (expect.flags.not) {
subject.replace(new RegExp(args.map(function (arg) {
return utils.escapeRegExpMetaChars(arg);
}).join('|'), 'g'), function ($0, index) {
flushUntilIndex(index);
lastIndex += $0.length;
output.removedHighlight($0);
});
flushUntilIndex(subject.length);
} else {
var ranges = [];
args.forEach(function (arg) {
var needle = arg;
var partial = false;
while (needle.length > 1) {
var found = false;
lastIndex = -1;
var index;
do {
index = subject.indexOf(needle, lastIndex + 1);
if (index !== -1) {
found = true;
ranges.push({
startIndex: index,
endIndex: index + needle.length,
partial: partial
});
}
lastIndex = index;
} while (lastIndex !== -1);
if (found) {
break;
}
needle = arg.substr(0, needle.length - 1);
partial = true;
}
});
lastIndex = 0;
ranges.sort(function (a, b) {
return a.startIndex - b.startIndex;
}).forEach(function (range) {
flushUntilIndex(range.startIndex);
var firstUncoveredIndex = Math.max(range.startIndex, lastIndex);
if (range.endIndex > firstUncoveredIndex) {
if (range.partial) {
output.partialMatch(subject.substring(firstUncoveredIndex, range.endIndex));
} else {
output.match(subject.substring(firstUncoveredIndex, range.endIndex));
}
lastIndex = range.endIndex;
}
});
flushUntilIndex(subject.length);
}
return output;
}
});
});
});
expect.addAssertion('<array-like> [not] to contain <any+>', function (expect, subject) {
var args = Array.prototype.slice.call(arguments, 2);
expect.withError(function () {
args.forEach(function (arg) {
expect(subject && Array.prototype.some.call(subject, function (item) {
return expect.equal(item, arg);
}), '[not] to be truthy');
});
}, function (e) {
expect.fail({
diff: expect.flags.not && function (output, diff, inspect, equal) {
return diff(subject, Array.prototype.filter.call(subject, function (item) {
return !args.some(function (arg) {
return equal(item, arg);
});
}));
}
});
});
});
expect.addAssertion('<string> [not] to begin with <string>', function (expect, subject, value) {
if (value === '') {
throw new Error("The '" + expect.testDescription + "' assertion does not support a prefix of the empty string");
}
expect.withError(function () {
expect(subject.substr(0, value.length), '[not] to equal', value);
}, function (err) {
expect.fail({
diff: function (output) {
output.inline = false;
if (expect.flags.not) {
output.removedHighlight(value).text(subject.substr(value.length));
} else {
var i = 0;
while (subject[i] === value[i]) {
i += 1;
}
if (i === 0) {
// No common prefix, omit diff
return null;
} else {
output
.partialMatch(subject.substr(0, i))
.text(subject.substr(i));
}
}
return output;
}
});
});
});
expect.addAssertion('<string> [not] to end with <string>', function (expect, subject, value) {
if (value === '') {
throw new Error("The '" + expect.testDescription + "' assertion does not support a suffix of the empty string");
}
expect.withError(function () {
expect(subject.substr(-value.length), '[not] to equal', value);
}, function (err) {
expect.fail({
diff: function (output) {
output.inline = false;
if (expect.flags.not) {
output.text(subject.substr(0, subject.length - value.length)).removedHighlight(value);
} else {
var i = 0;
while (subject[subject.length - 1 - i] === value[value.length - 1 - i]) {
i += 1;
}
if (i === 0) {
// No common suffix, omit diff
return null;
}
output
.text(subject.substr(0, subject.length - i))
.partialMatch(subject.substr(subject.length - i, subject.length));
}
return output;
}
});
});
});
expect.addAssertion('<number> [not] to be finite', function (expect, subject) {
expect(isFinite(subject), '[not] to be truthy');
});
expect.addAssertion('<number> [not] to be infinite', function (expect, subject) {
expect(!isNaN(subject) && !isFinite(subject), '[not] to be truthy');
});
expect.addAssertion('<number> [not] to be within <number> <number>', function (expect, subject, start, finish) {
expect.argsOutput = function (output) {
output.appendInspected(start).text('..').appendInspected(finish);
};
expect(subject >= start && subject <= finish, '[not] to be truthy');
});
expect.addAssertion('<string> [not] to be within <string> <string>', function (expect, subject, start, finish) {
expect.argsOutput = function (output) {
output.appendInspected(start).text('..').appendInspected(finish);
};
expect(subject >= start && subject <= finish, '[not] to be truthy');
});
expect.addAssertion('<number> [not] to be (less than|below) <number>', function (expect, subject, value) {
expect(subject < value, '[not] to be truthy');
});
expect.addAssertion('<string> [not] to be (less than|below) <string>', function (expect, subject, value) {
expect(subject < value, '[not] to be truthy');
});
expect.addAssertion('<number> [not] to be less than or equal to <number>', function (expect, subject, value) {
expect(subject <= value, '[not] to be truthy');
});
expect.addAssertion('<string> [not] to be less than or equal to <string>', function (expect, subject, value) {
expect(subject <= value, '[not] to be truthy');
});
expect.addAssertion('<number> [not] to be (greater than|above) <number>', function (expect, subject, value) {
expect(subject > value, '[not] to be truthy');
});
expect.addAssertion('<string> [not] to be (greater than|above) <string>', function (expect, subject, value) {
expect(subject > value, '[not] to be truthy');
});
expect.addAssertion('<number> [not] to be greater than or equal to <number>', function (expect, subject, value) {
expect(subject >= value, '[not] to be truthy');
});
expect.addAssertion('<string> [not] to be greater than or equal to <string>', function (expect, subject, value) {
expect(subject >= value, '[not] to be truthy');
});
expect.addAssertion('<number> [not] to be positive', function (expect, subject) {
expect(subject, '[not] to be greater than', 0);
});
expect.addAssertion('<number> [not] to be negative', function (expect, subject) {
expect(subject, '[not] to be less than', 0);
});
expect.addAssertion('<any> to equal <any>', function (expect, subject, value) {
expect.withError(function () {
expect(expect.equal(value, subject), 'to be truthy');
}, function (e) {
expect.fail({
label: 'should equal',
diff: function (output, diff) {
return diff(subject, value);
}
});
});
});
expect.addAssertion('<any> not to equal <any>', function (expect, subject, value) {
expect(expect.equal(value, subject), 'to be falsy');
});
expect.addAssertion('<function> to error', function (expect, subject) {
return expect.promise(function () {
return subject();
}).then(function () {
expect.fail();
}, function (error) {
return error;
});
});
expect.addAssertion('<function> to error [with] <any>', function (expect, subject, arg) {
return expect(subject, 'to error').then(function (error) {
expect.errorMode = 'nested';
return expect.withError(function () {
if (error.isUnexpected && (typeof arg === 'string' || isRegExp(arg))) {
return expect(error, 'to have message', arg);
} else {
return expect(error, 'to satisfy', arg);
}
}, function (e) {
e.originalError = error;
throw e;
});
});
});
expect.addAssertion('<function> not to error', function (expect, subject) {
var threw = false;
return expect.promise(function () {
try {
return subject();
} catch (e) {
threw = true;
throw e;
}
}).caught(function (error) {
expect.errorMode = 'nested';
expect.fail({
output: function (output) {
output.error(threw ? 'threw' : 'returned promise rejected with').error(': ')
.appendErrorMessage(error);
},
originalError: error
});
});
});
expect.addAssertion('<function> not to throw', function (expect, subject) {
var threw = false;
var error;
try {
subject();
} catch (e) {
error = e;
threw = true;
}
if (threw) {
expect.errorMode = 'nested';
expect.fail({
output: function (output) {
output.error('threw: ').appendErrorMessage(error);
},
originalError: error
});
}
});
expect.addAssertion('<function> to (throw|throw error|throw exception)', function (expect, subject) {
try {
subject();
} catch (e) {
return e;
}
expect.errorMode = 'nested';
expect.fail('did not throw');
});
expect.addAssertion('<function> to throw (a|an) <function>', function (expect, subject, value) {
var constructorName = utils.getFunctionName(value);
if (constructorName) {
expect.argsOutput[0] = function (output) {
output.jsFunctionName(constructorName);
};
}
expect.errorMode = 'nested';
return expect(subject, 'to throw').then(function (error) {
expect(error, 'to be a', value);
});
});
expect.addAssertion('<function> to (throw|throw error|throw exception) <any>', function (expect, subject, arg) {
expect.errorMode = 'nested';
return expect(subject, 'to throw').then(function (error) {
var isUnexpected = error && error._isUnexpected;
// in the presence of a matcher an error must have been thrown.
expect.errorMode = 'nested';
return expect.withError(function () {
if (isUnexpected && (typeof arg === 'string' || isRegExp(arg))) {
return expect(error.getErrorMessage('text').toString(), 'to satisfy', arg);
} else {
return expect(error, 'to satisfy', arg);
}
}, function (err) {
err.originalError = error;
throw err;
});
});
});
expect.addAssertion('<function> to have arity <number>', function (expect, subject, value) {
expect(subject.length, 'to equal', value);
});
expect.addAssertion([
'<object> to have values [exhaustively] satisfying <any>',
'<object> to have values [exhaustively] satisfying <assertion>',
'<object> to be (a map|a hash|an object) whose values [exhaustively] satisfy <any>',
'<object> to be (a map|a hash|an object) whose values [exhaustively] satisfy <assertion>'
], function (expect, subject, nextArg) {
expect.errorMode = 'nested';
expect(subject, 'not to be empty');
expect.errorMode = 'bubble';
var keys = expect.subjectType.getKeys(subject);
var expected = {};
keys.forEach(function (key, index) {
if (typeof nextArg === 'string') {
expected[key] = function (s) {
return expect.shift(s);
};
} else if (typeof nextArg === 'function') {
expected[key] = function (s) {
return nextArg._expectIt
? nextArg(s, expect.context)
: nextArg(s, index);
};
} else {
expected[key] = nextArg;
}
});
return expect.withError(function () {
return expect(subject, 'to [exhaustively] satisfy', expected);
}, function (err) {
expect.fail({
message: function (output) {
output.append(expect.standardErrorMessage(output.clone(), { compact: true }));
},
diff: function (output) {
var diff = err.getDiff({ output: output });
diff.inline = true;
return diff;
}
});
});
});
expect.addAssertion([
'<array-like> to have items [exhaustively] satisfying <any>',
'<array-like> to have items [exhaustively] satisfying <assertion>',
'<array-like> to be an array whose items [exhaustively] satisfy <any>',
'<array-like> to be an array whose items [exhaustively] satisfy <assertion>'
], function (expect, subject) { // ...
var extraArgs = Array.prototype.slice.call(arguments, 2);
expect.errorMode = 'nested';
expect(subject, 'not to be empty');
expect.errorMode = 'bubble';
return expect.withError(function () {
return expect.apply(expect, [subject, 'to have values [exhaustively] satisfying'].concat(extraArgs));
}, function (err) {
expect.fail({
message: function (output) {
output.append(expect.standardErrorMessage(output.clone(), { compact: true }));
},
diff: function (output) {
var diff = err.getDiff({ output: output });
diff.inline = true;
return diff;
}
});
});
});
expect.addAssertion([
'<object> to have keys satisfying <any>',
'<object> to have keys satisfying <assertion>',
'<object> to be (a map|a hash|an object) whose (keys|properties) satisfy <any>',
'<object> to be (a map|a hash|an object) whose (keys|properties) satisfy <assertion>'
], function (expect, subject) {
expect.errorMode = 'nested';
expect(subject, 'not to be empty');
expect.errorMode = 'default';
var keys = expect.subjectType.getKeys(subject);
var extraArgs = Array.prototype.slice.call(arguments, 2);
return expect.apply(expect, [keys, 'to have items satisfying'].concat(extraArgs));
});
expect.addAssertion([
'<object> to have a value [exhaustively] satisfying <any>',
'<object> to have a value [exhaustively] satisfying <assertion>'
], function (expect, subject, nextArg) {
expect.errorMode = 'nested';
expect(subject, 'not to be empty');
expect.errorMode = 'bubble';
var keys = expect.subjectType.getKeys(subject);
return expect.promise.any(keys.map(function (key, index) {
var expected;
if (typeof nextArg === 'string') {
expected = function (s) {
return expect.shift(s);
};
} else if (typeof nextArg === 'function') {
expected = function (s) {
return nextArg(s, index);
};
} else {
expected = nextArg;
}
return expect.promise(function () {
return expect(subject[key], 'to [exhaustively] satisfy', expected);
});
})).catch(function (e) {
return expect.fail(function (output) {
output.append(expect.standardErrorMessage(output.clone(), { compact: true }));
});
});
});
expect.addAssertion([
'<array-like> to have an item [exhaustively] satisfying <any>',
'<array-like> to have an item [exhaustively] satisfying <assertion>'
], function (expect, subject) { // ...
expect.errorMode = 'nested';
expect(subject, 'not to be empty');
expect.errorMode = 'bubble';
var extraArgs = Array.prototype.slice.call(arguments, 2);
return expect.withError(function () {
return expect.apply(expect, [subject, 'to have a value [exhaustively] satisfying'].concat(extraArgs));
}, function (err) {
expect.fail(function (output) {
output.append(expect.standardErrorMessage(output.clone(), { compact: true }));
});
});
});
expect.addAssertion('<object> to be canonical', function (expect, subject) {
var stack = [];
(function traverse(obj) {
var i;
for (i = 0 ; i < stack.length ; i += 1) {
if (stack[i] === obj) {
return;
}
}
if (obj && typeof obj === 'object') {
var keys = Object.keys(obj);
for (i = 0 ; i < keys.length - 1 ; i += 1) {
expect(keys[i], 'to be less than', keys[i + 1]);
}
stack.push(obj);
keys.forEach(function (key) {
traverse(obj[key]);
});
stack.pop();
}
}(subject));
});
expect.addAssertion('<Error> to have message <any>', function (expect, subject, value) {
expect.errorMode = 'nested';
return expect(subject.isUnexpected ? subject.getErrorMessage('text').toString() : subject.message, 'to satisfy', value);
});
expect.addAssertion('<Error> to [exhaustively] satisfy <Error>', function (expect, subject, value) {
expect(subject.constructor, 'to be', value.constructor);
var unwrappedValue = expect.argTypes[0].unwrap(value);
return expect.withError(function () {
return expect(subject, 'to [exhaustively] satisfy', unwrappedValue);
}, function (e) {
expect.fail({
diff: function (output, diff) {
output.inline = false;
var unwrappedSubject = expect.subjectType.unwrap(subject);
return utils.wrapConstructorNameAroundOutput(
diff(unwrappedSubject, unwrappedValue),
subject
);
}
});
});
});
expect.addAssertion('<Error> to [exhaustively] satisfy <object>', function (expect, subject, value) {
var valueType = expect.argTypes[0];
var subjectKeys = expect.subjectType.getKeys(subject);
var valueKeys = valueType.getKeys(value);
var convertedSubject = {};
subjectKeys.concat(valueKeys).forEach(function (key) {
convertedSubject[key] = subject[key];
});
return expect(convertedSubject, 'to [exhaustively] satisfy', value);
});
expect.addAssertion('<Error> to [exhaustively] satisfy <regexp|string>', function (expect, subject, value) {
return expect(subject.message, 'to [exhaustively] satisfy', value);
});
expect.addAssertion('<Error> to [exhaustively] satisfy <any>', function (expect, subject, value) {
return expect(subject.message, 'to [exhaustively] satisfy', value);
});
expect.addAssertion('<binaryArray> to [exhaustively] satisfy <expect.it>', function (expect, subject, value) {
return expect.withError(function () {
return value(subject, expect.context);
}, function (e) {
expect.fail({
diff: function (output, diff, inspect, equal) {
output.inline = false;
return output.appendErrorMessage(e);
}
});
});
});
expect.addAssertion('<UnexpectedError> to [exhaustively] satisfy <function>', function (expect, subject, value) {
return expect.promise(function () {
subject.serializeMessage(expect.outputFormat());
return value(subject);
});
});
expect.addAssertion('<any|Error> to [exhaustively] satisfy <function>', function (expect, subject, value) {
return expect.promise(function () {
return value(subject);
});
});
if (typeof Buffer !== 'undefined') {
expect.addAssertion('<Buffer> [when] decoded as <string> <assertion?>', function (expect, subject, value) {
return expect.shift(subject.toString(value));
});
}
expect.addAssertion('<any> not to [exhaustively] satisfy [assertion] <any>', function (expect, subject, value) {
return expect.promise(function (resolve, reject) {
return expect.promise(function () {
return expect(subject, 'to [exhaustively] satisfy [assertion]', value);
}).then(function () {
try {
expect.fail();
} catch (e) {
reject(e);
}
}).caught(function (e) {
if (!e || !e._isUnexpected) {
reject(e);
} else {
resolve();
}
});
});
});
expect.addAssertion('<any> to [exhaustively] satisfy assertion <any>', function (expect, subject, value) {
expect.errorMode = 'bubble'; // to satisfy assertion 'to be a number' => to be a number
return expect(subject, 'to [exhaustively] satisfy', value);
});
expect.addAssertion('<any> to [exhaustively] satisfy assertion <assertion>', function (expect, subject) {
expect.errorMode = 'bubble'; // to satisfy assertion 'to be a number' => to be a number
return expect.shift();
});
expect.addAssertion('<any> to [exhaustively] satisfy [assertion] <expect.it>', function (expect, subject, value) {
return expect.withError(function () {
return value(subject, expect.context);
}, function (e) {
expect.fail({
diff: function (output) {
output.inline = false;
return output.appendErrorMessage(e);
}
});
});
});
expect.addAssertion('<regexp> to [exhaustively] satisfy <regexp>', function (expect, subject, value) {
expect(subject, 'to equal', value);
});
expect.addAssertion('<string> to [exhaustively] satisfy <regexp>', function (expect, subject, value) {
expect.errorMode = 'bubble';
return expect(subject, 'to match', value);
});
expect.addAssertion('<function> to [exhaustively] satisfy <function>', function (expect, subject, value) {
expect.errorMode = 'bubble';
expect(subject, 'to equal', value);
});
expect.addAssertion('<binaryArray> to [exhaustively] satisfy <binaryArray>', function (expect, subject, value) {
expect.errorMode = 'bubble';
expect(subject, 'to equal', value);
});
expect.addAssertion('<any> to [exhaustively] satisfy <any>', function (expect, subject, value) {
expect.errorMode = 'bubble';
expect(subject, 'to equal', value);
});
expect.addAssertion('<array-like> to [exhaustively] satisfy <array-like>', function (expect, subject, value) {
expect.errorMode = 'bubble';
var i;
var valueType = expect.argTypes[0];
var valueKeys = valueType.getKeys(value);
var keyPromises = {};
valueKeys.forEach(function (valueKey) {
keyPromises[valueKey] = expect.promise(function () {
var valueKeyType = expect.findTypeOf(value[valueKey]);
if (valueKeyType.is('function')) {
return value[valueKey](subject[valueKey]);
} else {
return expect(subject[valueKey], 'to [exhaustively] satisfy', value[valueKey]);
}
});
});
return expect.promise.all([
expect.promise(function () {
expect(subject, 'to only have keys', valueKeys);
}),
expect.promise.all(keyPromises)
]).caught(function () {
var subjectType = expect.subjectType;
return expect.promise.settle(keyPromises).then(function () {
var toSatisfyMatrix = new Array(subject.length);
for (i = 0 ; i < subject.length ; i += 1) {
toSatisfyMatrix[i] = new Array(value.length);
if (i < value.length) {
toSatisfyMatrix[i][i] = keyPromises[i].isFulfilled() || keyPromises[i].reason();
}
}
if (subject.length > 10 || value.length > 10) {
var indexByIndexChanges = [];
for (i = 0 ; i < subject.length ; i += 1) {
var promise = keyPromises[i];
if (i < value.length) {
indexByIndexChanges.push({
type: promise.isFulfilled() ? 'equal' : 'similar',
value: subject[i],
expected: value[i],
actualIndex: i,
expectedIndex: i,
last: i === Math.max(subject.length, value.length) - 1
});
} else {
indexByIndexChanges.push({
type: 'remove',
value: subject[i],
actualIndex: i,
last: i === subject.length - 1
});
}
}
for (i = subject.length ; i < value.length ; i += 1) {
indexByIndexChanges.push({
type: 'insert',
value: value[i],
expectedIndex: i
});
}
return failWithChanges(indexByIndexChanges);
}
var isAsync = false;
var nonNumericalKeysAndSymbols = !subjectType.numericalPropertiesOnly &&
utils.uniqueNonNumericalStringsAndSymbols(subjectType.getKeys(subject), valueType.getKeys(value));
var changes = arrayChanges(subject, value, function equal(a, b, aIndex, bIndex) {
toSatisfyMatrix[aIndex] = toSatisfyMatrix[aIndex] || [];
var existingResult = toSatisfyMatrix[aIndex][bIndex];
if (typeof existingResult !== 'undefined') {
return existingResult === true;
}
var result;
try {
result = expect(a, 'to [exhaustively] satisfy', b);
} catch (err) {
throwIfNonUnexpectedError(err);
toSatisfyMatrix[aIndex][bIndex] = err;
return false;
}
result.then(function () {}, function () {});
if (result.isPending()) {
isAsync = true;
return false;
}
toSatisfyMatrix[aIndex][bIndex] = true;
return true;
}, function (a, b) {
return subjectType.similar(a, b);
}, nonNumericalKeysAndSymbols);
if (isAsync) {
return expect.promise(function (resolve, reject) {
arrayChangesAsync(subject, value, function equal(a, b, aIndex, bIndex, cb) {
toSatisfyMatrix[aIndex] = toSatisfyMatrix[aIndex] || [];
var existingResult = toSatisfyMatrix[aIndex][bIndex];
if (typeof existingResult !== 'undefined') {
return cb(existingResult === true);
}
expect.promise(function () {
return expect(a, 'to [exhaustively] satisfy', b);
}).then(function () {
toSatisfyMatrix[aIndex][bIndex] = true;
cb(true);
}, function (err) {
toSatisfyMatrix[aIndex][bIndex] = err;
cb(false);
});
}, function (a, b, aIndex, bIndex, cb) {
cb(subjectType.similar(a, b));
}, nonNumericalKeysAndSymbols, resolve);
}).then(failWithChanges);
} else {
return failWithChanges(changes);
}
function failWithChanges(changes) {
expect.errorMode = 'default';
expect.fail({
diff: function (output, diff, inspect, equal) {
output.inline = true;
var indexOfLastNonInsert = changes.reduce(function (previousValue, diffItem, index) {
return (diffItem.type === 'insert') ? previousValue : index;
}, -1);
var prefixOutput = subjectType.prefix(output.clone(), subject);
output
.append(prefixOutput)
.nl(prefixOutput.isEmpty() ? 0 : 1);
if (subjectType.indent) {
output.indentLines();
}
var packing = utils.packArrows(changes); // NOTE: Will have side effects in changes if the packing results in too many arrow lanes
output.arrowsAlongsideChangeOutputs(packing, changes.map(function (diffItem, index) {
var delimiterOutput = subjectType.delimiter(output.clone(), index, indexOfLastNonInsert + 1);
var type = diffItem.type;
if (type === 'moveTarget') {
return output.clone();
} else {
return output.clone().block(function () {
if (type === 'moveSource') {
this.property(diffItem.actualIndex, inspect(diffItem.value), true)
.amend(delimiterOutput.sp()).error('// should be moved');
} else if (type === 'insert') {
this.annotationBlock(function () {
var index = typeof diffItem.actualIndex !== 'undefined' ? diffItem.actualIndex : diffItem.expectedIndex;
if (expect.findTypeOf(diffItem.value).is('function')) {
this.error('missing: ')
.property(index, output.clone().block(function () {
this.omitSubject = undefined;
var promise = keyPromises[diffItem.expectedIndex];
if (promise.isRejected()) {
this.appendErrorMessage(promise.reason());
} else {
this.appendInspected(diffItem.value);
}
}), true);
} else {
this.error('missing ').property(index, inspect(diffItem.value), true);
}
});
} else {
this.property(diffItem.actualIndex, output.clone().block(function () {
if (type === 'remove') {
this.append(inspect(diffItem.value).amend(delimiterOutput.sp()).error('// should be removed'));
} else if (type === 'equal') {
this.append(inspect(diffItem.value).amend(delimiterOutput));
} else {
var toSatisfyResult = toSatisfyMatrix[diffItem.actualIndex][diffItem.expectedIndex];
var valueDiff = toSatisfyResult && toSatisfyResult !== true && toSatisfyResult.getDiff({ output: output.clone() });
if (valueDiff && valueDiff.inline) {
this.append(valueDiff.amend(delimiterOutput));
} else {
this.append(inspect(diffItem.value).amend(delimiterOutput)).sp().annotationBlock(function () {
this.omitSubject = diffItem.value;
var label = toSatisfyResult.getLabel();
if (label) {
this.error(label).sp()
.block(inspect(diffItem.expected));
if (valueDiff) {
this.nl(2).append(valueDiff);
}
} else {
this.appendErrorMessage(toSatisfyResult);
}
});
}
}
}), true);
}
});
}
}));
if (subjectType.indent) {
output.outdentLines();
}
var suffixOutput = subjectType.suffix(output.clone(), subject);
output
.nl(suffixOutput.isEmpty() ? 0 : 1)
.append(suffixOutput);
return output;
}
});
}
});
});
});
expect.addAssertion('<object> to [exhaustively] satisfy <object>', function (expect, subject, value) {
var valueType = expect.argTypes[0];
var subjectType = expect.subjectType;
var subjectIsArrayLike = subjectType.is('array-like');
if (subject === value) {
return;
}
if (valueType.is('array-like') && !subjectIsArrayLike) {
expect.fail();
}
var promiseByKey = {};
var keys = valueType.getKeys(value);
var subjectKeys = subjectType.getKeys(subject);
if (!subjectIsArrayLike) {
// Find all non-enumerable subject keys present in value, but not returned by subjectType.getKeys:
keys.forEach(function (key) {
if (Object.prototype.hasOwnProperty.call(subject, key) && subjectKeys.indexOf(key) === -1) {
subjectKeys.push(key);
}
});
}
keys.forEach(function (key, index) {
promiseByKey[key] = expect.promise(function () {
var valueKeyType = expect.findTypeOf(value[key]);
if (valueKeyType.is('expect.it')) {
expect.context.thisObject = subject;
return value[key](subject[key], expect.context);
} else if (valueKeyType.is('function')) {
return value[key](subject[key]);
} else {
return expect(subject[key], 'to [exhaustively] satisfy', value[key]);
}
});
});
return expect.promise.all([
expect.promise(function () {
if (expect.flags.exhaustively) {
var nonOwnKeysWithDefinedValues = keys.filter(function (key) {
return !Object.prototype.hasOwnProperty.call(subject, key) && typeof subject[key] !== 'undefined';
});
var valueKeysWithDefinedValues = keys.filter(function (key) {
return typeof value[key] !== 'undefined';
});
var subjectKeysWithDefinedValues = subjectKeys.filter(function (key) {
return typeof subject[key] !== 'undefined';
});
expect(valueKeysWithDefinedValues.length - nonOwnKeysWithDefinedValues.length, 'to equal', subjectKeysWithDefinedValues.length);
}
}),
expect.promise.all(promiseByKey)
]).caught(function () {
return expect.promise.settle(promiseByKey).then(function () {
expect.fail({
diff: function (output, diff, inspect, equal) {
output.inline = true;
var subjectIsArrayLike = subjectType.is('array-like');
var keys = utils.uniqueStringsAndSymbols(subjectKeys, valueType.getKeys(value)).filter(function (key) {
// Skip missing keys expected to be missing so they don't get rendered in the diff
return key in subject || typeof value[key] !== 'undefined';
});
var prefixOutput = subjectType.prefix(output.clone(), subject);
output
.append(prefixOutput)
.nl(prefixOutput.isEmpty() ? 0 : 1);
if (subjectType.indent) {
output.indentLines();
}
keys.forEach(function (key, index) {
output.nl(index > 0 ? 1 : 0).i().block(function () {
var valueOutput;
var annotation = output.clone();
var conflicting;
if (Object.prototype.hasOwnProperty.call(promiseByKey, key) && promiseByKey[key].isRejected()) {
conflicting = promiseByKey[key].reason();
}
var missingArrayIndex = subjectType.is('array-like') && !(key in subject);
var isInlineDiff = true;
output.omitSubject = subject[key];
if (!(key in value)) {
if (expect.flags.exhaustively) {
annotation.error('should be removed');
} else {
conflicting = null;
}
} else if (!(key in subject)) {
if (expect.findTypeOf(value[key]).is('function')) {
if (promiseByKey[key].isRejected()) {
output.error('// missing:').sp();
valueOutput = output.clone().appendErrorMessage(promiseByKey[key].reason());
} else {
output.error('// missing').sp();
valueOutput = output.clone().error('should satisfy').sp().block(inspect(value[key]));
}
} else {
output.error('// missing').sp();
valueOutput = inspect(value[key]);
}
} else if (conflicting || missingArrayIndex) {
var keyDiff = conflicting && conflicting.getDiff({ output: output });
isInlineDiff = !keyDiff || keyDiff.inline ;
if (missingArrayIndex) {
output.error('// missing').sp();
}
if (keyDiff && keyDiff.inline) {
valueOutput = keyDiff;
} else if (typeof value[key] === 'function') {
isInlineDiff = false;
annotation.appendErrorMessage(conflicting);
} else if (!keyDiff || (keyDiff && !keyDiff.inline)) {
annotation.error((conflicting && conflicting.getLabel()) || 'should satisfy').sp()
.block(inspect(value[key]));
if (keyDiff) {
annotation.nl(2).append(keyDiff);
}
} else {
valueOutput = keyDiff;
}
}
if (!valueOutput) {
if (missingArrayIndex || !(key in subject)) {
valueOutput = output.clone();
} else {
valueOutput = inspect(subject[key]);
}
}
var omitDelimiter =
missingArrayIndex ||
index >= subjectKeys.length - 1;
if (!omitDelimiter) {
valueOutput.amend(subjectType.delimiter(output.clone(), index, keys.length));
}
var annotationOnNextLine = !isInlineDiff &&
output.preferredWidth < this.size().width + valueOutput.size().width + annotation.size().width;
if (!annotation.isEmpty()) {
if (!valueOutput.isEmpty()) {
if (annotationOnNextLine) {
valueOutput.nl();
} else {
valueOutput.sp();
}
}
valueOutput.annotationBlock(function () {
this.append(annotation);
});
}
if (!isInlineDiff) {
valueOutput = output.clone().block(valueOutput);
}
this.property(key, valueOutput, subjectIsArrayLike);
});
});
if (subjectType.indent) {
output.outdentLines();
}
var suffixOutput = subjectType.suffix(output.clone(), subject);
return output
.nl(suffixOutput.isEmpty() ? 0 : 1)
.append(suffixOutput);
}
});
});
});
});
function wrapDiffWithTypePrefixAndSuffix(e, type, subject) {
var createDiff = e.getDiffMethod();
if (createDiff) {
return function (output) { // ...
type.prefix.call(type, output, subject);
var result = createDiff.apply(this, arguments);
type.suffix.call(type, output, subject);
return result;
};
}
}
expect.addAssertion('<wrapperObject> to [exhaustively] satisfy <wrapperObject>', function (expect, subject, value) {
var type = expect.findCommonType(subject, value);
expect(type.is('wrapperObject'), 'to be truthy');
return expect.withError(function () {
return expect(type.unwrap(subject), 'to [exhaustively] satisfy', type.unwrap(value));
}, function (e) {
expect.fail({
label: e.getLabel(),
diff: wrapDiffWithTypePrefixAndSuffix(e, type, subject)
});
});
});
expect.addAssertion('<wrapperObject> to [exhaustively] satisfy <any>', function (expect, subject, value) {
var subjectType = expect.subjectType;
return expect.withError(function () {
return expect(subjectType.unwrap(subject), 'to [exhaustively] satisfy', value);
}, function (e) {
expect.fail({
label: e.getLabel(),
diff: wrapDiffWithTypePrefixAndSuffix(e, subjectType, subject)
});
});
});
expect.addAssertion('<function> [when] called with <array-like> <assertion?>', function (expect, subject, args) { // ...
expect.errorMode = 'nested';
expect.argsOutput[0] = function (output) {
output.appendItems(args, ', ');
};
var thisObject = expect.context.thisObject || null;
return expect.shift(subject.apply(thisObject, args));
});
expect.addAssertion('<function> [when] called <assertion?>', function (expect, subject) {
expect.errorMode = 'nested';
var thisObject = expect.context.thisObject || null;
return expect.shift(subject.call(thisObject));
});
function instantiate(Constructor, args) {
function ProxyConstructor() {
return Constructor.apply(this, args);
}
ProxyConstructor.prototype = Constructor.prototype;
return new ProxyConstructor();
}
expect.addAssertion([
'<array-like> [when] passed as parameters to [async] <function> <assertion?>',
'<array-like> [when] passed as parameters to [constructor] <function> <assertion?>'
], function (expect, subject, fn) { // ...
expect.errorMode = 'nested';
var args = subject;
if (expect.flags.async) {
return expect.promise(function (run) {
args = [].concat(args);
args.push(run(function (err, result) {
expect(err, 'to be falsy');
return expect.shift(result);
}));
fn.apply(null, args);
});
} else {
return expect.shift(expect.flags.constructor ? instantiate(fn, args) : fn.apply(fn, args));
}
});
expect.addAssertion([
'<any> [when] passed as parameter to [async] <function> <assertion?>',
'<any> [when] passed as parameter to [constructor] <function> <assertion?>'
], function (expect, subject, fn) { // ...
expect.errorMode = 'nested';
var args = [subject];
if (expect.flags.async) {
return expect.promise(function (run) {
args = [].concat(args);
args.push(run(function (err, result) {
expect(err, 'to be falsy');
return expect.shift(result);
}));
fn.apply(null, args);
});
} else {
return expect.shift(expect.flags.constructor ? instantiate(fn, args) : fn.apply(fn, args));
}
});
expect.addAssertion([
'<array-like> [when] sorted [numerically] <assertion?>',
'<array-like> [when] sorted by <function> <assertion?>'
], function (expect, subject, compareFunction) {
if (expect.flags.numerically) {
compareFunction = function (a, b) {
return a - b;
};
}
return expect.shift(Array.prototype.slice.call(subject).sort(compareFunction));
});
expect.addAssertion('<Promise> to be rejected', function (expect, subject) {
expect.errorMode = 'nested';
return expect.promise(function () {
return subject;
}).then(function (obj) {
expect.fail(function (output) {
output.appendInspected(subject).sp().text('unexpectedly fulfilled');
if (typeof obj !== 'undefined') {
output.sp().text('with').sp().appendInspected(obj);
}
});
}, function (err) {
return err;
});
});
expect.addAssertion('<function> to be rejected', function (expect, subject) {
expect.errorMode = 'nested';
return expect(expect.promise(function () {
return subject();
}), 'to be rejected');
});
expect.addAssertion([
'<Promise> to be rejected with <any>',
'<Promise> to be rejected with error [exhaustively] satisfying <any>'
], function (expect, subject, value) {
expect.errorMode = 'nested';
return expect(subject, 'to be rejected').tap(function (err) {
return expect.withError(function () {
if (err && err._isUnexpected && (typeof value === 'string' || isRegExp(value))) {
return expect(err, 'to have message', value);
} else {
return expect(err, 'to [exhaustively] satisfy', value);
}
}, function (e) {
e.originalError = err;
throw e;
});
});
});
expect.addAssertion([
'<function> to be rejected with <any>',
'<function> to be rejected with error [exhaustively] satisfying <any>'
], function (expect, subject, value) {
expect.errorMode = 'nested';
return expect(expect.promise(function () {
return subject();
}), 'to be rejected with error [exhaustively] satisfying', value);
});
expect.addAssertion('<Promise> to be fulfilled', function (expect, subject) {
expect.errorMode = 'nested';
return expect.promise(function () {
return subject;
}).caught(function (err) {
expect.fail({
output: function (output) {
output.appendInspected(subject).sp().text('unexpectedly rejected');
if (typeof err !== 'undefined') {
output.sp().text('with').sp().appendInspected(err);
}
},
originalError: err
});
});
});
expect.addAssertion('<function> to be fulfilled', function (expect, subject) {
expect.errorMode = 'nested';
return expect(expect.promise(function () {
return subject();
}), 'to be fulfilled');
});
expect.addAssertion([
'<Promise> to be fulfilled with <any>',
'<Promise> to be fulfilled with value [exhaustively] satisfying <any>'
], function (expect, subject, value) {
expect.errorMode = 'nested';
return expect(subject, 'to be fulfilled').tap(function (fulfillmentValue) {
return expect(fulfillmentValue, 'to [exhaustively] satisfy', value);
});
});
expect.addAssertion([
'<function> to be fulfilled with <any>',
'<function> to be fulfilled with value [exhaustively] satisfying <any>'
], function (expect, subject, value) {
expect.errorMode = 'nested';
return expect(expect.promise(function () {
return subject();
}), 'to be fulfilled with value [exhaustively] satisfying', value);
});
expect.addAssertion('<Promise> when rejected <assertion>', function (expect, subject, nextAssertion) {
expect.errorMode = 'nested';
return expect.promise(function () {
return subject;
}).then(function (fulfillmentValue) {
if (typeof nextAssertion === 'string') {
expect.argsOutput = function (output) {
output.error(nextAssertion);
var rest = expect.args.slice(1);
if (rest.length > 0) {
output.sp().appendItems(rest, ', ');
}
};
}
expect.fail(function (output) {
output.appendInspected(subject).sp().text('unexpectedly fulfilled');
if (typeof fulfillmentValue !== 'undefined') {
output.sp().text('with').sp().appendInspected(fulfillmentValue);
}
});
}, function (err) {
return expect.withError(function () {
return expect.shift(err);
}, function (e) {
e.originalError = err;
throw e;
});
});
});
expect.addAssertion('<function> when rejected <assertion>', function (expect, subject) {
expect.errorMode = 'nested';
return expect.apply(expect, [expect.promise(function () {
return subject();
}), 'when rejected'].concat(Array.prototype.slice.call(arguments, 2)));
});
expect.addAssertion('<Promise> when fulfilled <assertion>', function (expect, subject, nextAssertion) {
expect.errorMode = 'nested';
return expect.promise(function () {
return subject;
}).then(function (fulfillmentValue) {
return expect.shift(fulfillmentValue);
}, function (err) {
// typeof nextAssertion === 'string' because expect.it is handled by the above (and shift only supports those two):
expect.argsOutput = function (output) {
output.error(nextAssertion);
var rest = expect.args.slice(1);
if (rest.length > 0) {
output.sp().appendItems(rest, ', ');
}
};
expect.fail({
output: function (output) {
output.appendInspected(subject).sp().text('unexpectedly rejected');
if (typeof err !== 'undefined') {
output.sp().text('with').sp().appendInspected(err);
}
},
originalError: err
});
});
});
expect.addAssertion('<function> when fulfilled <assertion>', function (expect, subject) {
expect.errorMode = 'nested';
return expect.apply(expect, [expect.promise(function () {
return subject();
}), 'when fulfilled'].concat(Array.prototype.slice.call(arguments, 2)));
});
expect.addAssertion('<function> to call the callback', function (expect, subject) {
expect.errorMode = 'nested';
return expect.promise(function (run) {
var async = false;
var calledTwice = false;
var callbackArgs;
function cb() {
if (callbackArgs) {
calledTwice = true;
} else {
callbackArgs = Array.prototype.slice.call(arguments);
}
if (async) {
setTimeout(assert, 0);
}
}
var assert = run(function () {
if (calledTwice) {
expect.fail(function () {
this.error('The callback was called twice');
});
}
return callbackArgs;
});
subject(cb);
async = true;
if (callbackArgs) {
return assert();
}
});
});
expect.addAssertion('<function> to call the callback without error', function (expect, subject) {
return expect(subject, 'to call the callback').then(function (callbackArgs) {
var err = callbackArgs[0];
if (err) {
expect.errorMode = 'nested';
expect.fail({
message: function (output) {
output.error('called the callback with: ');
if (err.getErrorMessage) {
output.appendErrorMessage(err);
} else {
output.appendInspected(err);
}
}
});
} else {
return callbackArgs.slice(1);
}
});
});
expect.addAssertion('<function> to call the callback with error', function (expect, subject) {
return expect(subject, 'to call the callback').spread(function (err) {
expect(err, 'to be truthy');
return err;
});
});
expect.addAssertion('<function> to call the callback with error <any>', function (expect, subject, value) {
return expect(subject, 'to call the callback with error').tap(function (err) {
expect.errorMode = 'nested';
if (err && err._isUnexpected && (typeof value === 'string' || isRegExp(value))) {
return expect(err, 'to have message', value);
} else {
return expect(err, 'to satisfy', value);
}
});
});
};
}).call(this,require(28).Buffer)
},{"16":16,"19":19,"23":23,"24":24,"28":28}],6:[function(require,module,exports){
var AssertionString = require(1);
module.exports = function createStandardErrorMessage(output, subject, testDescription, args, options) {
options = options || {};
var preamble = 'expected';
var subjectOutput = output.clone();
if (subject) {
subject.call(subjectOutput, subjectOutput);
}
var argsOutput = output.clone();
if (typeof args === 'function') {
args.call(argsOutput, argsOutput);
} else {
if (args.length > 0) {
var previousWasAssertion = false;
args.forEach(function (arg, index) {
var isAssertion = arg && typeof arg === 'object' && arg instanceof AssertionString;
if (0 < index) {
if (!isAssertion && !previousWasAssertion) {
argsOutput.text(',');
}
argsOutput.sp();
}
if (isAssertion) {
argsOutput.error(arg.text);
} else {
arg.call(argsOutput, argsOutput);
}
previousWasAssertion = isAssertion;
});
}
}
var subjectSize = subjectOutput.size();
var argsSize = argsOutput.size();
var width = preamble.length + subjectSize.width + argsSize.width + testDescription.length;
var height = Math.max(subjectSize.height, argsSize.height);
if ('omitSubject' in output && output.omitSubject === options.subject) {
var matchTestDescription = /^(not )?to (.*)/.exec(testDescription);
if (matchTestDescription) {
output.error('should ');
if (matchTestDescription[1]) {
output.error('not ');
}
testDescription = matchTestDescription[2];
} else {
testDescription = 'expected: ' + testDescription;
}
} else if (options.compact && options.compactSubject && (subjectSize.height > 1 || subjectSize.width > (options.compactWidth || 35))) {
output.error('expected').sp();
options.compactSubject.call(output, output);
output.sp();
} else {
output.error(preamble);
if (subjectSize.height > 1) {
output.nl();
} else {
output.sp();
}
output.append(subjectOutput);
if (subjectSize.height > 1 || (height === 1 && width > output.preferredWidth)) {
output.nl();
} else {
output.sp();
}
}
output.error(testDescription);
if (argsSize.height > 1) {
output.nl();
} else if (argsSize.width > 0) {
output.sp();
}
output.append(argsOutput);
return output;
};
},{"1":1}],7:[function(require,module,exports){
var createStandardErrorMessage = require(6);
var makePromise = require(11);
var isPendingPromise = require(9);
var oathbreaker = require(13);
var UnexpectedError = require(3);
var addAdditionalPromiseMethods = require(4);
var utils = require(19);
function isAssertionArg(arg) {
return arg.type.is('assertion');
}
function lookupAssertionsInParentChain(assertionString, unexpected) {
var assertions = [];
for (var instance = unexpected ; instance ; instance = instance.parent) {
if (instance.assertions[assertionString]) {
Array.prototype.push.apply(assertions, instance.assertions[assertionString]);
}
}
return assertions;
}
function findSuffixAssertions(assertionString, unexpected) {
if (typeof assertionString !== 'string') {
return null;
}
var straightforwardAssertions = lookupAssertionsInParentChain(assertionString, unexpected);
if (straightforwardAssertions.length > 0) {
return straightforwardAssertions;
}
var tokens = assertionString.split(' ');
for (var n = tokens.length - 1 ; n > 0 ; n -= 1) {
var suffix = tokens.slice(n).join(' ');
var suffixAssertions = lookupAssertionsInParentChain(suffix, unexpected);
if (findSuffixAssertions(tokens.slice(0, n).join(' '), unexpected) && suffixAssertions.length > 0) {
return suffixAssertions;
}
}
return null;
}
module.exports = function createWrappedExpectProto(unexpected) {
var wrappedExpectProto = {
promise: makePromise,
errorMode: 'default',
equal: unexpected.equal,
inspect: unexpected.inspect,
createOutput: unexpected.createOutput.bind(unexpected),
findTypeOf: unexpected.findTypeOf.bind(unexpected),
findTypeOfWithParentType: unexpected.findTypeOfWithParentType.bind(unexpected),
findCommonType: unexpected.findCommonType.bind(unexpected),
it: function () { // ...
var length = arguments.length;
var args = new Array(length);
for (var i = 0 ; i < length ; i += 1) {
args[i] = arguments[i];
}
if (typeof args[0] === 'string') {
args[0] = utils.forwardFlags(args[0], this.flags);
}
return unexpected.it.apply(unexpected, args);
},
diff: unexpected.diff,
getType: unexpected.getType,
output: unexpected.output,
outputFormat: unexpected.outputFormat.bind(unexpected),
format: unexpected.format,
withError: unexpected.withError,
fail: function () {
var args = arguments;
var expect = this.context.expect;
this.callInNestedContext(function () {
expect.fail.apply(expect, args);
});
},
standardErrorMessage: function (output, options) {
var that = this;
options = typeof options === 'object' ? options : {};
if ('omitSubject' in output) {
options.subject = this.subject;
}
if (options && options.compact) {
options.compactSubject = function (output) {
output.jsFunctionName(that.subjectType.name);
};
}
return createStandardErrorMessage(output, that.subjectOutput, that.testDescription, that.argsOutput, options);
},
callInNestedContext: function (callback) {
var that = this;
try {
var result = oathbreaker(callback());
if (isPendingPromise(result)) {
result = result.then(undefined, function (e) {
if (e && e._isUnexpected) {
var wrappedError = new UnexpectedError(that, e);
wrappedError.originalError = e.originalError;
throw wrappedError;
}
throw e;
});
} else if (!result || typeof result.then !== 'function') {
result = makePromise.resolve(result);
}
return addAdditionalPromiseMethods(result, that.execute, that.subject);
} catch (e) {
if (e && e._isUnexpected) {
var wrappedError = new UnexpectedError(that, e);
wrappedError.originalError = e.originalError;
throw wrappedError;
}
throw e;
}
},
shift: function (subject, assertionIndex) {
if (arguments.length <= 1) {
if (arguments.length === 0) {
subject = this.subject;
}
assertionIndex = -1;
for (var i = 0 ; i < this.assertionRule.args.length ; i += 1) {
var type = this.assertionRule.args[i].type;
if (type.is('assertion') || type.is('expect.it')) {
assertionIndex = i;
break;
}
}
} else if (arguments.length === 3) {
// The 3-argument syntax for wrappedExpect.shift is deprecated, please omit the first (expect) arg
subject = arguments[1];
assertionIndex = arguments[2];
}
if (assertionIndex !== -1) {
var args = this.args.slice(0, assertionIndex);
var rest = this.args.slice(assertionIndex);
var nextArgumentType = this.findTypeOf(rest[0]);
if (arguments.length > 1) {
// Legacy
this.argsOutput = function (output) {
args.forEach(function (arg, index) {
if (0 < index) {
output.text(', ');
}
output.appendInspected(arg);
});
if (args.length > 0) {
output.sp();
}
if (nextArgumentType.is('string')) {
output.error(rest[0]);
} else if (rest.length > 0) {
output.appendInspected(rest[0]);
}
if (rest.length > 1) {
output.sp();
}
rest.slice(1).forEach(function (arg, index) {
if (0 < index) {
output.text(', ');
}
output.appendInspected(arg);
});
};
}
if (nextArgumentType.is('expect.it')) {
var that = this;
return this.withError(function () {
return rest[0](subject);
}, function (err) {
that.fail(err);
});
} else if (nextArgumentType.is('string')) {
return this.execute.apply(this.execute, [subject].concat(rest));
} else {
return subject;
}
} else {
// No assertion to delegate to. Provide the new subject as the fulfillment value:
return subject;
}
},
_getSubjectType: function () {
return this.findTypeOfWithParentType(this.subject, this.assertionRule.subject.type);
},
_getArgTypes: function (index) {
var lastIndex = this.assertionRule.args.length - 1;
return this.args.map(function (arg, index) {
return this.findTypeOfWithParentType(arg, this.assertionRule.args[Math.min(index, lastIndex)].type);
}, this);
},
_getAssertionIndices: function () {
if (!this._assertionIndices) {
var assertionIndices = [];
var args = this.args;
var currentAssertionRule = this.assertionRule;
var offset = 0;
OUTER: while (true) {
if (currentAssertionRule.args.length > 1 && isAssertionArg(currentAssertionRule.args[currentAssertionRule.args.length - 2])) {
assertionIndices.push(offset + currentAssertionRule.args.length - 2);
var suffixAssertions = findSuffixAssertions(args[offset + currentAssertionRule.args.length - 2], unexpected);
if (suffixAssertions) {
for (var i = 0 ; i < suffixAssertions.length ; i += 1) {
if (suffixAssertions[i].args.some(isAssertionArg)) {
offset += currentAssertionRule.args.length - 1;
currentAssertionRule = suffixAssertions[i];
continue OUTER;
}
}
}
}
// No further assertions found,
break;
}
this._assertionIndices = assertionIndices;
}
return this._assertionIndices;
}
};
if (Object.__defineGetter__) {
Object.defineProperty(wrappedExpectProto, 'subjectType', {
enumerable: true,
get: function () {
return this.assertionRule && this._getSubjectType();
}
});
Object.defineProperty(wrappedExpectProto, 'argTypes', {
enumerable: true,
get: function () {
return this.assertionRule && this._getArgTypes();
}
});
}
utils.setPrototypeOfOrExtend(wrappedExpectProto, Function.prototype);
return wrappedExpectProto;
};
},{"11":11,"13":13,"19":19,"3":3,"4":4,"6":6,"9":9}],8:[function(require,module,exports){
(function (process){
/*global window*/
var defaultDepth = 3;
var matchDepthParameter =
typeof window !== 'undefined' &&
typeof window.location !== 'undefined' &&
window.location.search.match(/[?&]depth=(\d+)(?:$|&)/);
if (matchDepthParameter) {
defaultDepth = parseInt(matchDepthParameter[1], 10);
} else if (typeof process !== 'undefined' && process.env.UNEXPECTED_DEPTH) {
defaultDepth = parseInt(process.env.UNEXPECTED_DEPTH, 10);
}
module.exports = defaultDepth;
}).call(this,require(53))
},{"53":53}],9:[function(require,module,exports){
module.exports = function isPendingPromise(obj) {
return obj && typeof obj.then === 'function' && typeof obj.isPending === 'function' && obj.isPending();
};
},{}],10:[function(require,module,exports){
module.exports = function makeDiffResultBackwardsCompatible(diff) {
if (diff) {
if (diff.isMagicPen) {
// New format: { [MagicPen], inline: <boolean> }
// Make backwards compatible by adding a 'diff' property that points
// to the instance itself.
diff.diff = diff;
} else {
// Old format: { inline: <boolean>, diff: <magicpen> }
// Upgrade to the new format by moving the inline property to
// the magicpen instance, and remain backwards compatibly by adding
// the diff property pointing to the instance itself.
diff.diff.inline = diff.inline;
diff = diff.diff;
diff.diff = diff;
}
}
return diff;
};
},{}],11:[function(require,module,exports){
var Promise = require(56);
var oathbreaker = require(13);
var throwIfNonUnexpectedError = require(16);
function makePromise(body) {
if (typeof body !== 'function') {
throw new TypeError('expect.promise(...) requires a function argument to be supplied.\n' +
'See http://unexpected.js.org/api/promise/ for more details.');
}
if (body.length === 2) {
return new Promise(body);
}
return new Promise(function (resolve, reject) {
var runningTasks = 0;
var resolvedValue;
var outerFunctionHasReturned = false;
function fulfillIfDone() {
if (outerFunctionHasReturned && runningTasks === 0) {
resolve(resolvedValue);
}
}
function noteResolvedValue(value) {
if (typeof value !== 'undefined' && typeof resolvedValue === 'undefined') {
resolvedValue = value;
}
}
var runner = function (cb) {
runningTasks += 1;
return function () {
runningTasks -= 1;
var result;
try {
if (typeof cb === 'function') {
result = oathbreaker(cb.apply(null, arguments));
if (isPromise(result)) {
runningTasks += 1;
result.then(function (value) {
noteResolvedValue(value);
runningTasks -= 1;
fulfillIfDone();
}, reject);
} else {
noteResolvedValue(result);
}
}
} catch (e) {
return reject(e);
}
fulfillIfDone();
return result;
};
};
try {
var result = oathbreaker(body(runner));
if (isPromise(result)) {
runningTasks += 1;
result.then(function (value) {
noteResolvedValue(value);
runningTasks -= 1;
fulfillIfDone();
}, reject);
} else {
noteResolvedValue(result);
}
} catch (e) {
return reject(e);
}
outerFunctionHasReturned = true;
fulfillIfDone();
});
}
function isPromise(obj) {
return obj && typeof obj === 'object' && typeof obj.then === 'function';
}
function extractPromisesFromObject(obj) {
if (isPromise(obj)) {
return [obj];
} else if (obj && typeof obj === 'object') {
var promises = [];
// Object or Array
Object.keys(obj).forEach(function (key) {
Array.prototype.push.apply(promises, extractPromisesFromObject(obj[key]));
});
return promises;
}
return [];
}
['all', 'any', 'settle'].forEach(function (staticMethodName) {
makePromise[staticMethodName] = function (obj) {
var result = Promise[staticMethodName](extractPromisesFromObject(obj));
if (staticMethodName === 'settle') {
return result.then(function (promises) {
promises.forEach(function (promise) {
if (promise.isRejected()) {
throwIfNonUnexpectedError(promise.reason());
}
});
return promises;
});
}
return result;
};
});
// Expose all of Bluebird's static methods, except the ones related to long stack traces,
// unhandled rejections and the scheduler, which we need to manage ourselves:
Object.keys(Promise).forEach(function (staticMethodName) {
if (!/^_|^on|^setScheduler|ongStackTraces/.test(staticMethodName) && typeof Promise[staticMethodName] === 'function' && typeof makePromise[staticMethodName] === 'undefined') {
makePromise[staticMethodName] = Promise[staticMethodName];
}
});
module.exports = makePromise;
},{"13":13,"16":16,"56":56}],12:[function(require,module,exports){
/*global afterEach, jasmine*/
var pendingPromisesForTheCurrentTest = [];
var afterEachRegistered = false;
var currentSpec = null;
if (typeof jasmine === 'object') {
// Add a custom reporter that allows us to capture the name of the currently executing spec:
jasmine.getEnv().addReporter({
specStarted: function (spec) {
currentSpec = spec;
},
specDone: function (spec) {
currentSpec = null;
}
});
}
function isPendingOrHasUnhandledRejection(promise) {
return promise.isPending() || (promise.isRejected() && promise.reason().uncaught);
}
function registerAfterEachHook() {
if (typeof afterEach === 'function' && !afterEachRegistered) {
afterEachRegistered = true;
try {
afterEach(function () {
var error;
var testPassed = true;
if (pendingPromisesForTheCurrentTest.some(isPendingOrHasUnhandledRejection)) {
var displayName;
if (this.currentTest) {
// mocha
testPassed = this.currentTest.state === 'passed';
displayName = this.currentTest.title;
} else if (typeof currentSpec === 'object') {
testPassed = currentSpec.failedExpectations.length === 0;
displayName = currentSpec.fullName;
}
error = new Error(displayName + ': You have created a promise that was not returned from the it block');
}
pendingPromisesForTheCurrentTest = [];
if (error && testPassed) {
throw error;
}
});
} catch (e) {
// The benchmark suite fails when attempting to add an afterEach
}
}
}
// When running in jasmine/node.js, afterEach is available immediately,
// but doesn't work within the it block. Register the hook immediately:
registerAfterEachHook();
module.exports = function notifyPendingPromise(promise) {
pendingPromisesForTheCurrentTest.push(promise);
// Register the afterEach hook lazily (mocha/node.js):
registerAfterEachHook();
};
},{}],13:[function(require,module,exports){
var workQueue = require(20);
var Promise = require(56);
var useFullStackTrace = require(18);
module.exports = function oathbreaker(value) {
if (!value || typeof value.then !== 'function') {
return value;
}
if (!value.isRejected) {
// this is not a bluebird promise
return value;
}
if (value.isFulfilled()) {
return value;
}
if (value.isRejected()) {
value.caught(function () {
// Ignore - already handled
});
throw value.reason();
}
var onResolve = function () {};
var onReject = function () {};
var evaluated = false;
var error;
value.then(function (obj) {
evaluated = true;
onResolve(value);
}, function (err) {
evaluated = true;
error = err;
onReject(err);
});
workQueue.drain();
if (evaluated && error) {
if (error._isUnexpected && Error.captureStackTrace) {
Error.captureStackTrace(error);
}
throw error;
} else if (evaluated) {
return value;
} else if (value._captureStackTrace && !useFullStackTrace) {
value._captureStackTrace(true);
}
return new Promise(function (resolve, reject) {
onResolve = resolve;
onReject = reject;
});
};
},{"18":18,"20":20,"56":56}],14:[function(require,module,exports){
module.exports = /([\x00-\x09\x0B-\x1F\x7F-\x9F\xAD\u0378\u0379\u037F-\u0383\u038B\u038D\u03A2\u0528-\u0530\u0557\u0558\u0560\u0588\u058B-\u058E\u0590\u05C8-\u05CF\u05EB-\u05EF\u05F5-\u0605\u061C\u061D\u06DD\u070E\u070F\u074B\u074C\u07B2-\u07BF\u07FB-\u07FF\u082E\u082F\u083F\u085C\u085D\u085F-\u089F\u08A1\u08AD-\u08E3\u08FF\u0978\u0980\u0984\u098D\u098E\u0991\u0992\u09A9\u09B1\u09B3-\u09B5\u09BA\u09BB\u09C5\u09C6\u09C9\u09CA\u09CF-\u09D6\u09D8-\u09DB\u09DE\u09E4\u09E5\u09FC-\u0A00\u0A04\u0A0B-\u0A0E\u0A11\u0A12\u0A29\u0A31\u0A34\u0A37\u0A3A\u0A3B\u0A3D\u0A43-\u0A46\u0A49\u0A4A\u0A4E-\u0A50\u0A52-\u0A58\u0A5D\u0A5F-\u0A65\u0A76-\u0A80\u0A84\u0A8E\u0A92\u0AA9\u0AB1\u0AB4\u0ABA\u0ABB\u0AC6\u0ACA\u0ACE\u0ACF\u0AD1-\u0ADF\u0AE4\u0AE5\u0AF2-\u0B00\u0B04\u0B0D\u0B0E\u0B11\u0B12\u0B29\u0B31\u0B34\u0B3A\u0B3B\u0B45\u0B46\u0B49\u0B4A\u0B4E-\u0B55\u0B58-\u0B5B\u0B5E\u0B64\u0B65\u0B78-\u0B81\u0B84\u0B8B-\u0B8D\u0B91\u0B96-\u0B98\u0B9B\u0B9D\u0BA0-\u0BA2\u0BA5-\u0BA7\u0BAB-\u0BAD\u0BBA-\u0BBD\u0BC3-\u0BC5\u0BC9\u0BCE\u0BCF\u0BD1-\u0BD6\u0BD8-\u0BE5\u0BFB-\u0C00\u0C04\u0C0D\u0C11\u0C29\u0C34\u0C3A-\u0C3C\u0C45\u0C49\u0C4E-\u0C54\u0C57\u0C5A-\u0C5F\u0C64\u0C65\u0C70-\u0C77\u0C80\u0C81\u0C84\u0C8D\u0C91\u0CA9\u0CB4\u0CBA\u0CBB\u0CC5\u0CC9\u0CCE-\u0CD4\u0CD7-\u0CDD\u0CDF\u0CE4\u0CE5\u0CF0\u0CF3-\u0D01\u0D04\u0D0D\u0D11\u0D3B\u0D3C\u0D45\u0D49\u0D4F-\u0D56\u0D58-\u0D5F\u0D64\u0D65\u0D76-\u0D78\u0D80\u0D81\u0D84\u0D97-\u0D99\u0DB2\u0DBC\u0DBE\u0DBF\u0DC7-\u0DC9\u0DCB-\u0DCE\u0DD5\u0DD7\u0DE0-\u0DF1\u0DF5-\u0E00\u0E3B-\u0E3E\u0E5C-\u0E80\u0E83\u0E85\u0E86\u0E89\u0E8B\u0E8C\u0E8E-\u0E93\u0E98\u0EA0\u0EA4\u0EA6\u0EA8\u0EA9\u0EAC\u0EBA\u0EBE\u0EBF\u0EC5\u0EC7\u0ECE\u0ECF\u0EDA\u0EDB\u0EE0-\u0EFF\u0F48\u0F6D-\u0F70\u0F98\u0FBD\u0FCD\u0FDB-\u0FFF\u10C6\u10C8-\u10CC\u10CE\u10CF\u1249\u124E\u124F\u1257\u1259\u125E\u125F\u1289\u128E\u128F\u12B1\u12B6\u12B7\u12BF\u12C1\u12C6\u12C7\u12D7\u1311\u1316\u1317\u135B\u135C\u137D-\u137F\u139A-\u139F\u13F5-\u13FF\u169D-\u169F\u16F1-\u16FF\u170D\u1715-\u171F\u1737-\u173F\u1754-\u175F\u176D\u1771\u1774-\u177F\u17DE\u17DF\u17EA-\u17EF\u17FA-\u17FF\u180F\u181A-\u181F\u1878-\u187F\u18AB-\u18AF\u18F6-\u18FF\u191D-\u191F\u192C-\u192F\u193C-\u193F\u1941-\u1943\u196E\u196F\u1975-\u197F\u19AC-\u19AF\u19CA-\u19CF\u19DB-\u19DD\u1A1C\u1A1D\u1A5F\u1A7D\u1A7E\u1A8A-\u1A8F\u1A9A-\u1A9F\u1AAE-\u1AFF\u1B4C-\u1B4F\u1B7D-\u1B7F\u1BF4-\u1BFB\u1C38-\u1C3A\u1C4A-\u1C4C\u1C80-\u1CBF\u1CC8-\u1CCF\u1CF7-\u1CFF\u1DE7-\u1DFB\u1F16\u1F17\u1F1E\u1F1F\u1F46\u1F47\u1F4E\u1F4F\u1F58\u1F5A\u1F5C\u1F5E\u1F7E\u1F7F\u1FB5\u1FC5\u1FD4\u1FD5\u1FDC\u1FF0\u1FF1\u1FF5\u1FFF\u200B-\u200F\u202A-\u202E\u2060-\u206F\u2072\u2073\u208F\u209D-\u209F\u20BA-\u20CF\u20F1-\u20FF\u218A-\u218F\u23F4-\u23FF\u2427-\u243F\u244B-\u245F\u2700\u2B4D-\u2B4F\u2B5A-\u2BFF\u2C2F\u2C5F\u2CF4-\u2CF8\u2D26\u2D28-\u2D2C\u2D2E\u2D2F\u2D68-\u2D6E\u2D71-\u2D7E\u2D97-\u2D9F\u2DA7\u2DAF\u2DB7\u2DBF\u2DC7\u2DCF\u2DD7\u2DDF\u2E3C-\u2E7F\u2E9A\u2EF4-\u2EFF\u2FD6-\u2FEF\u2FFC-\u2FFF\u3040\u3097\u3098\u3100-\u3104\u312E-\u3130\u318F\u31BB-\u31BF\u31E4-\u31EF\u321F\u32FF\u4DB6-\u4DBF\u9FCD-\u9FFF\uA48D-\uA48F\uA4C7-\uA4CF\uA62C-\uA63F\uA698-\uA69E\uA6F8-\uA6FF\uA78F\uA794-\uA79F\uA7AB-\uA7F7\uA82C-\uA82F\uA83A-\uA83F\uA878-\uA87F\uA8C5-\uA8CD\uA8DA-\uA8DF\uA8FC-\uA8FF\uA954-\uA95E\uA97D-\uA97F\uA9CE\uA9DA-\uA9DD\uA9E0-\uA9FF\uAA37-\uAA3F\uAA4E\uAA4F\uAA5A\uAA5B\uAA7C-\uAA7F\uAAC3-\uAADA\uAAF7-\uAB00\uAB07\uAB08\uAB0F\uAB10\uAB17-\uAB1F\uAB27\uAB2F-\uABBF\uABEE\uABEF\uABFA-\uABFF\uD7A4-\uD7AF\uD7C7-\uD7CA\uD7FC-\uF8FF\uFA6E\uFA6F\uFADA-\uFAFF\uFB07-\uFB12\uFB18-\uFB1C\uFB37\uFB3D\uFB3F\uFB42\uFB45\uFBC2-\uFBD2\uFD40-\uFD4F\uFD90\uFD91\uFDC8-\uFDEF\uFDFE\uFDFF\uFE1A-\uFE1F\uFE27-\uFE2F\uFE53\uFE67\uFE6C-\uFE6F\uFE75\uFEFD-\uFF00\uFFBF-\uFFC1\uFFC8\uFFC9\uFFD0\uFFD1\uFFD8\uFFD9\uFFDD-\uFFDF\uFFE7\uFFEF-\uFFFB\uFFFE\uFFFF])/g;
},{}],15:[function(require,module,exports){
var utils = require(19);
var stringDiff = require(34);
var specialCharRegExp = require(14);
module.exports = function (expect) {
expect.installTheme({ styles: {
jsBoolean: 'jsPrimitive',
jsNumber: 'jsPrimitive',
error: ['red', 'bold'],
success: ['green', 'bold'],
diffAddedLine: 'green',
diffAddedHighlight: ['bgGreen', 'white'],
diffAddedSpecialChar: ['bgGreen', 'cyan', 'bold'],
diffRemovedLine: 'red',
diffRemovedHighlight: ['bgRed', 'white'],
diffRemovedSpecialChar: ['bgRed', 'cyan', 'bold'],
partialMatchHighlight: ['bgYellow']
}});
expect.installTheme('html', {
palette: [
'#993333', '#669933', '#314575', '#337777', '#710071', '#319916',
'#BB1A53', '#999933', '#4311C2', '#996633', '#993399', '#333399',
'#228842', '#C24747', '#336699', '#663399'
],
styles: {
jsComment: '#969896',
jsFunctionName: '#795da3',
jsKeyword: '#a71d5d',
jsPrimitive: '#0086b3',
jsRegexp: '#183691',
jsString: '#df5000',
jsKey: '#555'
}
});
expect.installTheme('ansi', {
palette: [
'#FF1A53', '#E494FF', '#1A53FF', '#FF1AC6', '#1AFF53', '#D557FF',
'#81FF57', '#C6FF1A', '#531AFF', '#AFFF94', '#C61AFF', '#53FF1A',
'#FF531A', '#1AFFC6', '#FFC61A', '#1AC6FF'
],
styles: {
jsComment: 'gray',
jsFunctionName: 'jsKeyword',
jsKeyword: 'magenta',
jsNumber: [],
jsPrimitive: 'cyan',
jsRegexp: 'green',
jsString: 'cyan',
jsKey: '#666',
diffAddedHighlight: ['bgGreen', 'black'],
diffRemovedHighlight: ['bgRed', 'black'],
partialMatchHighlight: ['bgYellow', 'black']
}
});
expect.addStyle('colorByIndex', function (content, index) {
var palette = this.theme().palette;
if (palette) {
var color = palette[index % palette.length];
this.text(content, color);
} else {
this.text(content);
}
});
expect.addStyle('singleQuotedString', function (content) {
content = String(content);
this.jsString("'")
.jsString(content.replace(/[\\\x00-\x1f']/g, function ($0) {
if ($0 === '\n') {
return '\\n';
} else if ($0 === '\r') {
return '\\r';
} else if ($0 === "'") {
return "\\'";
} else if ($0 === '\\') {
return '\\\\';
} else if ($0 === '\t') {
return '\\t';
} else if ($0 === '\b') {
return '\\b';
} else if ($0 === '\f') {
return '\\f';
} else {
var charCode = $0.charCodeAt(0);
return '\\x' + (charCode < 16 ? '0' : '') + charCode.toString(16);
}
}))
.jsString("'");
});
expect.addStyle('property', function (key, inspectedValue, isArrayLike) {
var keyOmitted = false;
var isSymbol;
isSymbol = typeof key === 'symbol';
if (isSymbol) {
this.text('[').sp().appendInspected(key).sp().text(']').text(':');
} else {
key = String(key);
if (/^[a-z\$\_][a-z0-9\$\_]*$/i.test(key)) {
this.text(key, 'jsKey').text(':');
} else if (/^(?:0|[1-9][0-9]*)$/.test(key)) {
if (isArrayLike) {
keyOmitted = true;
} else {
this.jsNumber(key).text(':');
}
} else {
this.singleQuotedString(key).text(':');
}
}
if (!inspectedValue.isEmpty()) {
if (!keyOmitted) {
if (key.length > 5 && inspectedValue.isBlock() && inspectedValue.isMultiline()) {
this.indentLines();
this.nl().i();
} else {
this.sp();
}
}
this.append(inspectedValue);
}
});
// Intended to be redefined by a plugin that offers syntax highlighting:
expect.addStyle('code', function (content, language) {
this.text(content);
});
expect.addStyle('annotationBlock', function () {
var pen = this.getContentFromArguments(arguments);
var height = pen.size().height;
this.block(function () {
for (var i = 0; i < height; i += 1) {
if (0 < i) {
this.nl();
}
this.error('//');
}
});
this.sp().block(pen);
});
expect.addStyle('commentBlock', function () {
var pen = this.getContentFromArguments(arguments);
var height = pen.size().height;
this.block(function () {
for (var i = 0; i < height; i += 1) {
if (0 < i) {
this.nl();
}
this.jsComment('//');
}
});
this.sp().block(pen);
});
expect.addStyle('removedHighlight', function (content) {
this.alt({
text: function () {
content.split(/(\n)/).forEach(function (fragment) {
if (fragment === '\n') {
this.nl();
} else {
this.block(function () {
this.text(fragment).nl().text(fragment.replace(/[\s\S]/g, '^'));
});
}
}, this);
},
fallback: function () {
this.diffRemovedHighlight(content);
}
});
});
expect.addStyle('match', function (content) {
this.alt({
text: function () {
content.split(/(\n)/).forEach(function (fragment) {
if (fragment === '\n') {
this.nl();
} else {
this.block(function () {
this.text(fragment).nl().text(fragment.replace(/[\s\S]/g, '^'));
});
}
}, this);
},
fallback: function () {
this.diffAddedHighlight(content);
}
});
});
expect.addStyle('partialMatch', function (content) {
this.alt({
text: function () {
// We haven't yet come up with a good styling for partial matches in text mode
this.match(content);
},
fallback: function () {
this.partialMatchHighlight(content);
}
});
});
expect.addStyle('shouldEqualError', function (expected) {
this.error(typeof expected === 'undefined' ? 'should be' : 'should equal').sp().block(function () {
this.appendInspected(expected);
});
});
expect.addStyle('errorName', function (error) {
if (typeof error.name === 'string' && error.name !== 'Error') {
this.text(error.name);
} else if (error.constructor && typeof error.constructor.name === 'string') {
this.text(error.constructor.name);
} else {
this.text('Error');
}
});
expect.addStyle('appendErrorMessage', function (error, options) {
if (error && error.isUnexpected) {
this.append(error.getErrorMessage(utils.extend({ output: this }, options)));
} else {
this.appendInspected(error);
}
});
expect.addStyle('appendItems', function (items, separator) {
var that = this;
separator = separator || '';
items.forEach(function (item, index) {
if (0 < index) {
that.append(separator);
}
that.appendInspected(item);
});
});
expect.addStyle('stringDiffFragment', function (ch, text, baseStyle, markUpSpecialCharacters) {
text.split(/\n/).forEach(function (line, i, lines) {
if (this.isAtStartOfLine()) {
this.alt({
text: ch,
fallback: function () {
if (line === '' && ch !== ' ' && (i === 0 || i !== lines.length - 1)) {
this[ch === '+' ? 'diffAddedSpecialChar' : 'diffRemovedSpecialChar']('\\n');
}
}
});
}
var matchTrailingSpace = line.match(/^(.*[^ ])?( +)$/);
if (matchTrailingSpace) {
line = matchTrailingSpace[1] || '';
}
if (markUpSpecialCharacters) {
line.split(specialCharRegExp).forEach(function (part) {
if (specialCharRegExp.test(part)) {
this[{'+': 'diffAddedSpecialChar', '-': 'diffRemovedSpecialChar'}[ch] || baseStyle](utils.escapeChar(part));
} else {
this[baseStyle](part);
}
}, this);
} else {
this[baseStyle](line);
}
if (matchTrailingSpace) {
this[{'+': 'diffAddedHighlight', '-': 'diffRemovedHighlight'}[ch] || baseStyle](matchTrailingSpace[2]);
}
if (i !== lines.length - 1) {
this.nl();
}
}, this);
});
expect.addStyle('stringDiff', function (actual, expected, options) {
options = options || {};
var type = options.type || 'WordsWithSpace';
var diffLines = [];
var lastPart;
stringDiff.diffLines(actual, expected).forEach(function (part) {
if (lastPart && lastPart.added && part.removed) {
diffLines.push({
oldValue: part.value,
newValue: lastPart.value,
replaced: true
});
lastPart = null;
} else {
if (lastPart) {
diffLines.push(lastPart);
}
lastPart = part;
}
});
if (lastPart) {
diffLines.push(lastPart);
}
diffLines.forEach(function (part, index) {
if (part.replaced) {
var oldValue = part.oldValue;
var newValue = part.newValue;
var newLine = this.clone();
var oldEndsWithNewline = oldValue.slice(-1) === '\n';
var newEndsWithNewline = newValue.slice(-1) === '\n';
if (oldEndsWithNewline) {
oldValue = oldValue.slice(0, -1);
}
if (newEndsWithNewline) {
newValue = newValue.slice(0, -1);
}
stringDiff['diff' + type](oldValue, newValue).forEach(function (part) {
if (part.added) {
newLine.stringDiffFragment('+', part.value, 'diffAddedHighlight', options.markUpSpecialCharacters);
} else if (part.removed) {
this.stringDiffFragment('-', part.value, 'diffRemovedHighlight', options.markUpSpecialCharacters);
} else {
newLine.stringDiffFragment('+', part.value, 'diffAddedLine');
this.stringDiffFragment('-', part.value, 'diffRemovedLine');
}
}, this);
if (newEndsWithNewline && !oldEndsWithNewline) {
newLine.diffAddedSpecialChar('\\n');
}
if (oldEndsWithNewline && !newEndsWithNewline) {
this.diffRemovedSpecialChar('\\n');
}
this.nl().append(newLine).nl(oldEndsWithNewline && index < diffLines.length - 1 ? 1 : 0);
} else {
var endsWithNewline = /\n$/.test(part.value);
var value = endsWithNewline ?
part.value.slice(0, -1) :
part.value;
if (part.added) {
this.stringDiffFragment('+', value, 'diffAddedLine', options.markUpSpecialCharacters);
} else if (part.removed) {
this.stringDiffFragment('-', value, 'diffRemovedLine', options.markUpSpecialCharacters);
} else {
this.stringDiffFragment(' ', value, 'text');
}
if (endsWithNewline) {
this.nl();
}
}
}, this);
});
expect.addStyle('arrow', function (options) {
options = options || {};
var styles = options.styles || [];
var i;
this.nl(options.top || 0).sp(options.left || 0).text('┌', styles);
for (i = 1 ; i < options.width ; i += 1) {
this.text(i === options.width - 1 && options.direction === 'up' ? '▷' : '─', styles);
}
this.nl();
for (i = 1 ; i < options.height - 1 ; i += 1) {
this.sp(options.left || 0).text('│', styles).nl();
}
this.sp(options.left || 0).text('└', styles);
for (i = 1 ; i < options.width ; i += 1) {
this.text(i === options.width - 1 && options.direction === 'down' ? '▷' : '─', styles);
}
});
var flattenBlocksInLines = require(48);
expect.addStyle('merge', function (pens) {
var flattenedPens = pens.map(function (pen) {
return flattenBlocksInLines(pen.output);
}).reverse();
var maxHeight = flattenedPens.reduce(function (maxHeight, pen) {
return Math.max(maxHeight, pen.length);
}, 0);
var blockNumbers = new Array(flattenedPens.length);
var blockOffsets = new Array(flattenedPens.length);
// As long as there's at least one pen with a line left:
for (var lineNumber = 0 ; lineNumber < maxHeight ; lineNumber += 1) {
if (lineNumber > 0) {
this.nl();
}
var i;
for (i = 0 ; i < blockNumbers.length ; i += 1) {
blockNumbers[i] = 0;
blockOffsets[i] = 0;
}
var contentLeft;
do {
contentLeft = false;
var hasOutputChar = false;
for (i = 0 ; i < flattenedPens.length ; i += 1) {
var currentLine = flattenedPens[i][lineNumber];
if (currentLine) {
while (currentLine[blockNumbers[i]] && blockOffsets[i] >= currentLine[blockNumbers[i]].args.content.length) {
blockNumbers[i] += 1;
blockOffsets[i] = 0;
}
var currentBlock = currentLine[blockNumbers[i]];
if (currentBlock) {
contentLeft = true;
if (!hasOutputChar) {
var ch = currentBlock.args.content.charAt(blockOffsets[i]);
if (ch !== ' ') {
this.text(ch, currentBlock.args.styles);
hasOutputChar = true;
}
}
blockOffsets[i] += 1;
}
}
}
if (!hasOutputChar && contentLeft) {
this.sp();
}
} while (contentLeft);
}
});
expect.addStyle('arrowsAlongsideChangeOutputs', function (packing, changeOutputs) {
if (packing) {
var topByChangeNumber = {};
var top = 0;
changeOutputs.forEach(function (changeOutput, index) {
topByChangeNumber[index] = top;
top += changeOutput.size().height;
});
var that = this;
var arrows = [];
packing.forEach(function (columnSet, i, packing) {
columnSet.forEach(function (entry) {
arrows.push(that.clone().arrow({
left: i * 2,
top: topByChangeNumber[entry.start],
width: 1 + (packing.length - i) * 2,
height: topByChangeNumber[entry.end] - topByChangeNumber[entry.start] + 1,
direction: entry.direction
}));
});
});
if (arrows.length === 1) {
this.block(arrows[0]);
} else if (arrows.length > 1) {
this.block(function () {
this.merge(arrows);
});
}
} else {
this.i();
}
this.block(function () {
changeOutputs.forEach(function (changeOutput, index) {
this.nl(index > 0 ? 1 : 0);
if (!changeOutput.isEmpty()) {
this.sp(packing ? 1 : 0).append(changeOutput);
}
}, this);
});
});
};
},{"14":14,"19":19,"34":34,"48":48}],16:[function(require,module,exports){
module.exports = function throwIfNonUnexpectedError(err) {
if (err && err.message === 'aggregate error') {
for (var i = 0 ; i < err.length ; i += 1) {
throwIfNonUnexpectedError(err[i]);
}
} else if (!err || !err._isUnexpected) {
throw err;
}
};
},{}],17:[function(require,module,exports){
(function (Buffer){
var utils = require(19);
var isRegExp = utils.isRegExp;
var leftPad = utils.leftPad;
var arrayChanges = require(24);
var leven = require(40);
var detectIndent = require(33);
var defaultDepth = require(8);
var AssertionString = require(1);
module.exports = function (expect) {
expect.addType({
name: 'wrapperObject',
identify: false,
equal: function (a, b, equal) {
return a === b || equal(this.unwrap(a), this.unwrap(b));
},
inspect: function (value, depth, output, inspect) {
output.append(this.prefix(output.clone(), value));
output.append(inspect(this.unwrap(value), depth));
output.append(this.suffix(output.clone(), value));
return output;
},
diff: function (actual, expected, output, diff, inspect) {
output.inline = true;
actual = this.unwrap(actual);
expected = this.unwrap(expected);
var comparison = diff(actual, expected);
var prefixOutput = this.prefix(output.clone(), actual);
var suffixOutput = this.suffix(output.clone(), actual);
if (comparison && comparison.inline) {
return output.append(prefixOutput).append(comparison).append(suffixOutput);
} else {
return output.append(prefixOutput).nl()
.indentLines()
.i().block(function () {
this.append(inspect(actual)).sp().annotationBlock(function () {
this.shouldEqualError(expected, inspect);
if (comparison) {
this.nl(2).append(comparison);
}
});
}).nl()
.outdentLines()
.append(suffixOutput);
}
}
});
if (typeof Symbol === 'function') {
expect.addType({
name: 'Symbol',
identify: function (obj) {
return typeof obj === 'symbol';
},
inspect: function (obj, depth, output, inspect) {
return output
.jsKeyword('Symbol')
.text('(')
.singleQuotedString(obj.toString().replace(/^Symbol\(|\)$/g, ''))
.text(')');
}
});
}
// If Symbol support is not detected, default to passing undefined to
// Array.prototype.sort, which means "natural" (asciibetical) sort.
var keyComparator;
if (typeof Symbol === 'function') {
// Comparator that puts symbols last:
keyComparator = function (a, b) {
var aIsSymbol, bIsSymbol;
var aString = a;
var bString = b;
aIsSymbol = typeof a === 'symbol';
bIsSymbol = typeof b === 'symbol';
if (aIsSymbol) {
if (bIsSymbol) {
aString = a.toString();
bString = b.toString();
} else {
return 1;
}
} else if (bIsSymbol) {
return -1;
}
if (aString < bString) {
return -1;
} else if (aString > bString) {
return 1;
}
return 0;
};
}
expect.addType({
name: 'object',
indent: true,
forceMultipleLines: false,
identify: function (obj) {
return obj && typeof obj === 'object';
},
prefix: function (output, obj) {
var constructor = obj.constructor;
var constructorName = constructor && typeof constructor === 'function' && constructor !== Object && utils.getFunctionName(constructor);
if (constructorName && constructorName !== 'Object') {
output.text(constructorName + '(');
}
return output.text('{');
},
suffix: function (output, obj) {
output.text('}');
var constructor = obj.constructor;
var constructorName = constructor && typeof constructor === 'function' && constructor !== Object && utils.getFunctionName(constructor);
if (constructorName && constructorName !== 'Object') {
output.text(')');
}
return output;
},
delimiter: function (output, i, length) {
if (i < length - 1) {
output.text(',');
}
return output;
},
getKeys: Object.getOwnPropertySymbols ? function (obj) {
var keys = Object.keys(obj);
var symbols = Object.getOwnPropertySymbols(obj);
if (symbols.length > 0) {
return keys.concat(symbols);
} else {
return keys;
}
} : Object.keys,
equal: function (a, b, equal) {
if (a === b) {
return true;
}
if (b.constructor !== a.constructor) {
return false;
}
var actualKeys = this.getKeys(a).filter(function (key) {
return typeof a[key] !== 'undefined';
}),
expectedKeys = this.getKeys(b).filter(function (key) {
return typeof b[key] !== 'undefined';
});
// having the same number of owned properties (keys incorporates hasOwnProperty)
if (actualKeys.length !== expectedKeys.length) {
return false;
}
//the same set of keys (although not necessarily the same order),
actualKeys.sort(keyComparator);
expectedKeys.sort(keyComparator);
// cheap key test
for (var i = 0; i < actualKeys.length; i += 1) {
if (actualKeys[i] !== expectedKeys[i]) {
return false;
}
}
//equivalent values for every corresponding key, and
// possibly expensive deep test
for (var j = 0; j < actualKeys.length; j += 1) {
var key = actualKeys[j];
if (!equal(a[key], b[key])) {
return false;
}
}
return true;
},
inspect: function (obj, depth, output, inspect) {
var keys = this.getKeys(obj);
if (keys.length === 0) {
this.prefix(output, obj);
this.suffix(output, obj);
return output;
}
var type = this;
var inspectedItems = keys.map(function (key, index) {
var propertyDescriptor = Object.getOwnPropertyDescriptor && Object.getOwnPropertyDescriptor(obj, key);
var hasGetter = propertyDescriptor && propertyDescriptor.get;
var hasSetter = propertyDescriptor && propertyDescriptor.set;
var propertyOutput = output.clone();
if (hasSetter && !hasGetter) {
propertyOutput.text('set').sp();
}
// Inspect the setter function if there's no getter:
var value = (hasSetter && !hasGetter) ? hasSetter : obj[key];
var inspectedValue = inspect(value);
if (value && value._expectIt) {
inspectedValue = output.clone().block(inspectedValue);
}
propertyOutput.property(key, inspectedValue);
propertyOutput.amend(type.delimiter(output.clone(), index, keys.length));
if (hasGetter && hasSetter) {
propertyOutput.sp().jsComment('/* getter/setter */');
} else if (hasGetter) {
propertyOutput.sp().jsComment('/* getter */');
}
return propertyOutput;
});
var maxLineLength = output.preferredWidth - (depth === Infinity ? 0 : depth) * 2 - 2;
var width = 0;
var compact = inspectedItems.length > 5 || inspectedItems.every(function (inspectedItem) {
if (inspectedItem.isMultiline()) {
return false;
}
width += inspectedItem.size().width;
return width < maxLineLength;
});
var itemsOutput = output.clone();
if (compact) {
var currentLineLength = 0;
inspectedItems.forEach(function (inspectedItem, index) {
var size = inspectedItem.size();
currentLineLength += size.width + 1;
if (index > 0) {
if (size.height === 1 && currentLineLength < maxLineLength) {
itemsOutput.sp();
} else {
itemsOutput.nl();
currentLineLength = size.width;
}
if (size.height > 1) {
// Make sure that we don't append more to this line
currentLineLength = maxLineLength;
}
}
itemsOutput.append(inspectedItem);
});
} else {
inspectedItems.forEach(function (inspectedItem, index) {
if (index > 0) {
itemsOutput.nl();
}
itemsOutput.append(inspectedItem);
});
}
var prefixOutput = this.prefix(output.clone(), obj);
var suffixOutput = this.suffix(output.clone(), obj);
output.append(prefixOutput);
if (this.forceMultipleLines || itemsOutput.isMultiline()) {
if (!prefixOutput.isEmpty()) {
output.nl();
}
if (this.indent) {
output.indentLines().i();
}
output.block(itemsOutput);
if (this.indent) {
output.outdentLines();
}
if (!suffixOutput.isEmpty()) {
output.nl();
}
} else {
output
.sp(prefixOutput.isEmpty() ? 0 : 1)
.append(itemsOutput)
.sp(suffixOutput.isEmpty() ? 0 : 1);
}
return output.append(suffixOutput);
},
diff: function (actual, expected, output, diff, inspect, equal) {
if (actual.constructor !== expected.constructor) {
return output.text('Mismatching constructors ')
.text(actual.constructor && utils.getFunctionName(actual.constructor) || actual.constructor)
.text(' should be ').text(expected.constructor && utils.getFunctionName(expected.constructor) || expected.constructor);
}
output.inline = true;
var actualKeys = this.getKeys(actual);
var keys = utils.uniqueStringsAndSymbols(actualKeys, this.getKeys(expected));
var prefixOutput = this.prefix(output.clone(), actual);
output
.append(prefixOutput)
.nl(prefixOutput.isEmpty() ? 0 : 1);
if (this.indent) {
output.indentLines();
}
var type = this;
keys.forEach(function (key, index) {
output.nl(index > 0 ? 1 : 0).i().block(function () {
var valueOutput;
var annotation = output.clone();
var conflicting = !equal(actual[key], expected[key]);
var isInlineDiff = false;
if (conflicting) {
if (!(key in expected)) {
annotation.error('should be removed');
isInlineDiff = true;
} else if (!(key in actual)) {
this.error('// missing').sp();
valueOutput = output.clone().appendInspected(expected[key]);
isInlineDiff = true;
} else {
var keyDiff = diff(actual[key], expected[key]);
if (!keyDiff || (keyDiff && !keyDiff.inline)) {
annotation.shouldEqualError(expected[key]);
if (keyDiff) {
annotation.nl(2).append(keyDiff);
}
} else {
isInlineDiff = true;
valueOutput = keyDiff;
}
}
} else {
isInlineDiff = true;
}
if (!valueOutput) {
valueOutput = inspect(actual[key], conflicting ? Infinity : null);
}
valueOutput.amend(type.delimiter(output.clone(), index, actualKeys.length));
if (!isInlineDiff) {
valueOutput = output.clone().block(valueOutput);
}
this.property(key, valueOutput);
if (!annotation.isEmpty()) {
this.sp().annotationBlock(annotation);
}
});
});
if (this.indent) {
output.outdentLines();
}
var suffixOutput = this.suffix(output.clone(), actual);
return output
.nl(suffixOutput.isEmpty() ? 0 : 1)
.append(suffixOutput);
},
similar: function (a, b) {
if (a === null || b === null) {
return false;
}
var typeA = typeof a;
var typeB = typeof b;
if (typeA !== typeB) {
return false;
}
if (typeA === 'string') {
return leven(a, b) < a.length / 2;
}
if (typeA !== 'object' || !a) {
return false;
}
if (utils.isArray(a) && utils.isArray(b)) {
return true;
}
var aKeys = this.getKeys(a);
var bKeys = this.getKeys(b);
var numberOfSimilarKeys = 0;
var requiredSimilarKeys = Math.round(Math.max(aKeys.length, bKeys.length) / 2);
return aKeys.concat(bKeys).some(function (key) {
if (key in a && key in b) {
numberOfSimilarKeys += 1;
}
return numberOfSimilarKeys >= requiredSimilarKeys;
});
}
});
expect.addType({
name: 'type',
base: 'object',
identify: function (value) {
return value && value._unexpectedType;
},
inspect: function (value, depth, output) {
return output.text('type: ').jsKeyword(value.name);
}
});
expect.addType({
name: 'array-like',
base: 'object',
identify: false,
numericalPropertiesOnly: true,
getKeys: function (obj) {
var keys = new Array(obj.length);
for (var i = 0 ; i < obj.length ; i += 1) {
keys[i] = i;
}
if (!this.numericalPropertiesOnly) {
Object.keys(obj).forEach(function (key) {
if (!utils.numericalRegExp.test(key)) {
keys.push(key);
}
});
}
return keys;
},
equal: function (a, b, equal) {
if (a === b) {
return true;
} else if (a.constructor === b.constructor && a.length === b.length) {
var i;
if (this.numericalPropertiesOnly) {
for (i = 0; i < a.length; i += 1) {
if (!equal(a[i], b[i])) {
return false;
}
}
} else {
var aKeys = this.getKeys(a);
var bKeys = this.getKeys(b);
if (aKeys.length !== bKeys.length) {
return false;
}
for (i = 0; i < aKeys.length; i += 1) {
if (!equal(a[aKeys[i]], b[aKeys[i]])) {
return false;
}
}
}
return true;
} else {
return false;
}
},
prefix: function (output) {
return output.text('[');
},
suffix: function (output) {
return output.text(']');
},
inspect: function (arr, depth, output, inspect) {
var prefixOutput = this.prefix(output.clone(), arr);
var suffixOutput = this.suffix(output.clone(), arr);
var keys = this.getKeys(arr);
if (keys.length === 0) {
return output.append(prefixOutput).append(suffixOutput);
}
if (depth === 1 && arr.length > 10) {
return output.append(prefixOutput).text('...').append(suffixOutput);
}
var inspectedItems = keys.map(function (key) {
var inspectedValue;
if (key in arr) {
inspectedValue = inspect(arr[key]);
} else if (utils.numericalRegExp.test(key)) {
// Sparse array entry
inspectedValue = output.clone();
} else {
// Not present non-numerical property returned by getKeys
inspectedValue = inspect(undefined);
}
return output.clone().property(key, inspectedValue, true);
});
var currentDepth = defaultDepth - Math.min(defaultDepth, depth);
var maxLineLength = (output.preferredWidth - 20) - currentDepth * output.indentationWidth - 2;
var width = 0;
var multipleLines = this.forceMultipleLines || inspectedItems.some(function (o) {
if (o.isMultiline()) {
return true;
}
var size = o.size();
width += size.width;
return width > maxLineLength;
});
var type = this;
inspectedItems.forEach(function (inspectedItem, index) {
inspectedItem.amend(type.delimiter(output.clone(), index, keys.length));
});
if (multipleLines) {
output.append(prefixOutput);
if (!prefixOutput.isEmpty()) {
output.nl();
}
if (this.indent) {
output.indentLines();
}
inspectedItems.forEach(function (inspectedItem, index) {
output.nl(index > 0 ? 1 : 0).i().block(inspectedItem);
});
if (this.indent) {
output.outdentLines();
}
if (!suffixOutput.isEmpty()) {
output.nl();
}
return output.append(suffixOutput);
} else {
output
.append(prefixOutput)
.sp(prefixOutput.isEmpty() ? 0 : 1);
inspectedItems.forEach(function (inspectedItem, index) {
output.append(inspectedItem);
var lastIndex = index === inspectedItems.length - 1;
if (!lastIndex) {
output.sp();
}
});
return output
.sp(suffixOutput.isEmpty() ? 0 : 1)
.append(suffixOutput);
}
},
diffLimit: 512,
diff: function (actual, expected, output, diff, inspect, equal) {
output.inline = true;
if (Math.max(actual.length, expected.length) > this.diffLimit) {
output.jsComment('Diff suppressed due to size > ' + this.diffLimit);
return output;
}
if (actual.constructor !== expected.constructor) {
return this.baseType.diff(actual, expected, output);
}
var prefixOutput = this.prefix(output.clone(), actual);
output
.append(prefixOutput)
.nl(prefixOutput.isEmpty() ? 0 : 1);
if (this.indent) {
output.indentLines();
}
var type = this;
var changes = arrayChanges(actual, expected, equal, function (a, b) {
return type.similar(a, b);
}, !type.numericalPropertiesOnly && utils.uniqueNonNumericalStringsAndSymbols(this.getKeys(actual), this.getKeys(expected)));
var indexOfLastNonInsert = changes.reduce(function (previousValue, diffItem, index) {
return (diffItem.type === 'insert') ? previousValue : index;
}, -1);
var packing = utils.packArrows(changes); // NOTE: Will have side effects in changes if the packing results in too many arrow lanes
output.arrowsAlongsideChangeOutputs(packing, changes.map(function (diffItem, index) {
var delimiterOutput = type.delimiter(output.clone(), index, indexOfLastNonInsert + 1);
if (diffItem.type === 'moveTarget') {
return output.clone();
} else {
return output.clone().block(function () {
if (diffItem.type === 'moveSource') {
this.property(diffItem.actualIndex, inspect(diffItem.value), true)
.amend(delimiterOutput.sp()).error('// should be moved');
} else if (diffItem.type === 'insert') {
this.annotationBlock(function () {
this.error('missing ').block(function () {
var index = typeof diffItem.actualIndex !== 'undefined' ? diffItem.actualIndex : diffItem.expectedIndex;
this.property(index, inspect(diffItem.value), true);
});
});
} else if (diffItem.type === 'remove') {
this.block(function () {
this.property(diffItem.actualIndex, inspect(diffItem.value), true)
.amend(delimiterOutput.sp()).error('// should be removed');
});
} else if (diffItem.type === 'equal') {
this.block(function () {
this.property(diffItem.actualIndex, inspect(diffItem.value), true)
.amend(delimiterOutput);
});
} else {
this.block(function () {
var valueDiff = diff(diffItem.value, diffItem.expected);
this.property(diffItem.actualIndex, output.clone().block(function () {
if (valueDiff && valueDiff.inline) {
this.append(valueDiff.amend(delimiterOutput));
} else if (valueDiff) {
this.append(inspect(diffItem.value).amend(delimiterOutput.sp())).annotationBlock(function () {
this.shouldEqualError(diffItem.expected, inspect).nl(2).append(valueDiff);
});
} else {
this.append(inspect(diffItem.value).amend(delimiterOutput.sp())).annotationBlock(function () {
this.shouldEqualError(diffItem.expected, inspect);
});
}
}), true);
});
}
});
}
}));
if (this.indent) {
output.outdentLines();
}
var suffixOutput = this.suffix(output.clone(), actual);
return output
.nl(suffixOutput.isEmpty() ? 0 : 1)
.append(suffixOutput);
}
});
expect.addType({
name: 'array',
base: 'array-like',
numericalPropertiesOnly: false,
identify: function (arr) {
return utils.isArray(arr);
}
});
expect.addType({
name: 'arguments',
base: 'array-like',
prefix: function (output) {
return output.text('arguments(', 'cyan');
},
suffix: function (output) {
return output.text(')', 'cyan');
},
identify: function (obj) {
return Object.prototype.toString.call(obj) === '[object Arguments]';
}
});
var errorMethodBlacklist = ['message', 'name', 'description', 'line', 'column', 'sourceId', 'sourceURL', 'stack', 'stackArray'].reduce(function (result, prop) {
result[prop] = true;
return result;
}, {});
expect.addType({
base: 'object',
name: 'Error',
identify: function (value) {
return utils.isError(value);
},
getKeys: function (value) {
var keys = this.baseType.getKeys(value).filter(function (key) {
return !errorMethodBlacklist[key];
});
keys.unshift('message');
return keys;
},
unwrap: function (value) {
return this.getKeys(value).reduce(function (result, key) {
result[key] = value[key];
return result;
}, {});
},
equal: function (a, b, equal) {
return a === b ||
(equal(a.message, b.message) && this.baseType.equal(a, b));
},
inspect: function (value, depth, output, inspect) {
output.errorName(value).text('(');
var keys = this.getKeys(value);
if (keys.length === 1 && keys[0] === 'message') {
if (value.message !== '') {
output.append(inspect(value.message));
}
} else {
output.append(inspect(this.unwrap(value), depth));
}
return output.text(')');
},
diff: function (actual, expected, output, diff) {
if (actual.constructor !== expected.constructor) {
return output.text('Mismatching constructors ')
.errorName(actual)
.text(' should be ').errorName(expected);
}
output = diff(this.unwrap(actual), this.unwrap(expected));
if (output) {
output = output.clone().errorName(actual).text('(').append(output).text(')');
output.inline = false;
}
return output;
}
});
var unexpectedErrorMethodBlacklist = ['output', '_isUnexpected', 'htmlMessage', '_hasSerializedErrorMessage', 'expect', 'assertion', 'originalError'].reduce(function (result, prop) {
result[prop] = true;
return result;
}, {});
expect.addType({
base: 'Error',
name: 'UnexpectedError',
identify: function (value) {
return value && typeof value === 'object' &&
value._isUnexpected && this.baseType.identify(value);
},
getKeys: function (value) {
return this.baseType.getKeys(value).filter(function (key) {
return !unexpectedErrorMethodBlacklist[key];
});
},
inspect: function (value, depth, output) {
output.jsFunctionName(this.name).text('(');
var errorMessage = value.getErrorMessage(output);
if (errorMessage.isMultiline()) {
output.nl().indentLines().i().block(errorMessage).nl();
} else {
output.append(errorMessage);
}
return output.text(')');
}
});
expect.addType({
name: 'date',
identify: function (obj) {
return Object.prototype.toString.call(obj) === '[object Date]';
},
equal: function (a, b) {
return a.getTime() === b.getTime();
},
inspect: function (date, depth, output, inspect) {
// TODO: Inspect "new" as an operator and Date as a built-in once we have the styles defined:
var dateStr = date.toUTCString().replace(/UTC/, 'GMT');
var milliseconds = date.getUTCMilliseconds();
if (milliseconds > 0) {
var millisecondsStr = String(milliseconds);
while (millisecondsStr.length < 3) {
millisecondsStr = '0' + millisecondsStr;
}
dateStr = dateStr.replace(' GMT', '.' + millisecondsStr + ' GMT');
}
return output.jsKeyword('new').sp().text('Date(').append(inspect(dateStr).text(')'));
}
});
expect.addType({
base: 'any',
name: 'function',
identify: function (f) {
return typeof f === 'function';
},
getKeys: Object.keys,
equal: function (a, b) {
return a === b;
},
inspect: function (f, depth, output, inspect) {
var source = f.toString().replace(/\r\n?|\n\r?/g, '\n');
var name = utils.getFunctionName(f) || '';
var preamble;
var body;
var bodyIndent;
var matchSource = source.match(/^\s*((?:async )?\s*(?:\S+\s*=>|\([^\)]*\)\s*=>|function \w*?\s*\([^\)]*\)))([\s\S]*)$/);
if (matchSource) {
preamble = matchSource[1];
body = matchSource[2];
var matchBodyAndIndent = body.match(/^(\s*\{)([\s\S]*?)([ ]*)\}\s*$/);
var openingBrace;
var closingBrace = '}';
if (matchBodyAndIndent) {
openingBrace = matchBodyAndIndent[1];
body = matchBodyAndIndent[2];
bodyIndent = matchBodyAndIndent[3] || '';
if (bodyIndent.length === 1) {
closingBrace = ' }';
}
}
// Remove leading indentation unless the function is a one-liner or it uses multiline string literals
if (/\n/.test(body) && !/\\\n/.test(body)) {
body = body.replace(new RegExp('^ {' + bodyIndent.length + '}', 'mg'), '');
var indent = detectIndent(body);
body = body.replace(new RegExp('^(?:' + indent.indent + ')+', 'mg'), function ($0) {
return utils.leftPad('', ($0.length / indent.amount) * output.indentationWidth, ' ');
});
}
if (!name || name === 'anonymous') {
name = '';
}
if (/^\s*\[native code\]\s*$/.test(body)) {
body = ' /* native code */ ';
closingBrace = '}';
} else if (/^\s*$/.test(body)) {
body = '';
} else if (/^\s*[^\r\n]{1,30}\s*$/.test(body) && body.indexOf('//') === -1) {
body = ' ' + body.trim() + ' ';
closingBrace = '}';
} else {
body = body.replace(/^((?:.*\n){3}( *).*\n)[\s\S]*?\n[\s\S]*?\n((?:.*\n){3})$/, '$1$2// ... lines removed ...\n$3');
}
if (matchBodyAndIndent) {
body = openingBrace + body + closingBrace;
} else {
// Strip trailing space from arrow function body
body = body.replace(/[ ]*$/, '');
}
} else {
preamble = 'function ' + name + '( /*...*/ ) ';
body = '{ /*...*/ }';
}
return output.code(preamble + body, 'javascript');
}
});
expect.addType({
base: 'function',
name: 'expect.it',
identify: function (f) {
return typeof f === 'function' && f._expectIt;
},
inspect: function (f, depth, output, inspect) {
output.text('expect.it(');
var orBranch = false;
f._expectations.forEach(function (expectation, index) {
if (expectation === f._OR) {
orBranch = true;
return;
}
if (orBranch) {
output.text(')\n .or(');
} else if (0 < index) {
output.text(')\n .and(');
}
var args = Array.prototype.slice.call(expectation);
args.forEach(function (arg, i) {
if (0 < i) {
output.text(', ');
}
output.append(inspect(arg));
});
orBranch = false;
});
return output.amend(')');
}
});
expect.addType({
name: 'Promise',
base: 'object',
identify: function (obj) {
return obj && this.baseType.identify(obj) && typeof obj.then === 'function';
},
inspect: function (promise, depth, output, inspect) {
output.jsFunctionName('Promise');
if (promise.isPending && promise.isPending()) {
output.sp().yellow('(pending)');
} else if (promise.isFulfilled && promise.isFulfilled()) {
output.sp().green('(fulfilled)');
if (promise.value) {
var value = promise.value();
if (typeof value !== 'undefined') {
output.sp().text('=>').sp().append(inspect(value));
}
}
} else if (promise.isRejected && promise.isRejected()) {
output.sp().red('(rejected)');
var reason = promise.reason();
if (typeof reason !== 'undefined') {
output.sp().text('=>').sp().append(inspect(promise.reason()));
}
}
return output;
}
});
expect.addType({
name: 'regexp',
base: 'object',
identify: isRegExp,
equal: function (a, b) {
return a === b || (
a.source === b.source &&
a.global === b.global &&
a.ignoreCase === b.ignoreCase &&
a.multiline === b.multiline
);
},
inspect: function (regExp, depth, output) {
return output.jsRegexp(regExp);
},
diff: function (actual, expected, output, diff, inspect) {
output.inline = false;
return output.stringDiff(String(actual), String(expected), {type: 'Chars', markUpSpecialCharacters: true});
}
});
expect.addType({
name: 'binaryArray',
base: 'array-like',
digitWidth: 2,
hexDumpWidth: 16,
identify: false,
prefix: function (output) {
return output.code(this.name + '([', 'javascript');
},
suffix: function (output) {
return output.code('])', 'javascript');
},
equal: function (a, b) {
if (a === b) {
return true;
}
if (a.length !== b.length) { return false; }
for (var i = 0; i < a.length; i += 1) {
if (a[i] !== b[i]) { return false; }
}
return true;
},
hexDump: function (obj, maxLength) {
var hexDump = '';
if (typeof maxLength !== 'number' || maxLength === 0) {
maxLength = obj.length;
}
for (var i = 0 ; i < maxLength ; i += this.hexDumpWidth) {
if (hexDump.length > 0) {
hexDump += '\n';
}
var hexChars = '',
asciiChars = ' │';
for (var j = 0 ; j < this.hexDumpWidth ; j += 1) {
if (i + j < maxLength) {
var octet = obj[i + j];
hexChars += leftPad(octet.toString(16).toUpperCase(), this.digitWidth, '0') + ' ';
asciiChars += String.fromCharCode(octet).replace(/\n/g, '␊').replace(/\r/g, '␍');
} else if (this.digitWidth === 2) {
hexChars += ' ';
}
}
if (this.digitWidth === 2) {
hexDump += hexChars + asciiChars + '│';
} else {
hexDump += hexChars.replace(/\s+$/, '');
}
}
return hexDump;
},
inspect: function (obj, depth, output) {
this.prefix(output, obj);
var codeStr = '';
for (var i = 0 ; i < Math.min(this.hexDumpWidth, obj.length) ; i += 1) {
if (i > 0) {
codeStr += ', ';
}
var octet = obj[i];
codeStr += '0x' + leftPad(octet.toString(16).toUpperCase(), this.digitWidth, '0');
}
if (obj.length > this.hexDumpWidth) {
codeStr += ' /* ' + (obj.length - this.hexDumpWidth) + ' more */ ';
}
output.code(codeStr, 'javascript');
this.suffix(output, obj);
return output;
},
diffLimit: 512,
diff: function (actual, expected, output, diff, inspect) {
output.inline = false;
if (Math.max(actual.length, expected.length) > this.diffLimit) {
output.jsComment('Diff suppressed due to size > ' + this.diffLimit);
} else {
output.stringDiff(this.hexDump(actual), this.hexDump(expected), {type: 'Chars', markUpSpecialCharacters: false})
.replaceText(/[\x00-\x1f\x7f-\xff␊␍]/g, '.').replaceText(/[│ ]/g, function (styles, content) {
this.text(content);
});
}
return output;
}
});
[8, 16, 32].forEach(function (numBits) {
['Int', 'Uint'].forEach(function (intOrUint) {
var constructorName = intOrUint + numBits + 'Array',
Constructor = this[constructorName];
if (typeof Constructor !== 'undefined') {
expect.addType({
name: constructorName,
base: 'binaryArray',
hexDumpWidth: 128 / numBits,
digitWidth: numBits / 4,
identify: function (obj) {
return obj instanceof Constructor;
}
});
}
}, this);
}, this);
if (typeof Buffer !== 'undefined') {
expect.addType({
name: 'Buffer',
base: 'binaryArray',
identify: Buffer.isBuffer
});
}
expect.addType({
name: 'string',
identify: function (value) {
return typeof value === 'string';
},
inspect: function (value, depth, output) {
return output.singleQuotedString(value);
},
diffLimit: 4096,
diff: function (actual, expected, output, diff, inspect) {
if (Math.max(actual.length, expected.length) > this.diffLimit) {
output.jsComment('Diff suppressed due to size > ' + this.diffLimit);
return output;
}
output.stringDiff(actual, expected, {type: 'WordsWithSpace', markUpSpecialCharacters: true});
output.inline = false;
return output;
}
});
expect.addType({
name: 'number',
identify: function (value) {
return typeof value === 'number' && !isNaN(value);
},
inspect: function (value, depth, output) {
if (value === 0 && 1 / value === -Infinity) {
value = '-0';
} else {
value = String(value);
}
return output.jsNumber(String(value));
}
});
expect.addType({
name: 'NaN',
identify: function (value) {
return typeof value === 'number' && isNaN(value);
},
inspect: function (value, depth, output) {
return output.jsPrimitive(value);
}
});
expect.addType({
name: 'boolean',
identify: function (value) {
return typeof value === 'boolean';
},
inspect: function (value, depth, output) {
return output.jsPrimitive(value);
}
});
expect.addType({
name: 'undefined',
identify: function (value) {
return typeof value === 'undefined';
},
inspect: function (value, depth, output) {
return output.jsPrimitive(value);
}
});
expect.addType({
name: 'null',
identify: function (value) {
return value === null;
},
inspect: function (value, depth, output) {
return output.jsPrimitive(value);
}
});
expect.addType({
name: 'assertion',
identify: function (value) {
return value instanceof AssertionString;
}
});
};
}).call(this,require(28).Buffer)
},{"1":1,"19":19,"24":24,"28":28,"33":33,"40":40,"8":8}],18:[function(require,module,exports){
(function (process){
/*global window*/
var Promise = require(56);
var useFullStackTrace = false;
if (typeof window !== 'undefined' && typeof window.location !== 'undefined') {
useFullStackTrace = !!window.location.search.match(/[?&]full-trace=true(?:$|&)/);
}
if (typeof process !== 'undefined' && process.env && process.env.UNEXPECTED_FULL_TRACE) {
Promise.longStackTraces();
useFullStackTrace = true;
}
module.exports = useFullStackTrace;
}).call(this,require(53))
},{"53":53,"56":56}],19:[function(require,module,exports){
/* eslint-disable no-proto */
var canSetPrototype = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array);
var greedyIntervalPacker = require(36);
var setPrototypeOf = Object.setPrototypeOf || function setPrototypeOf(obj, proto) {
obj.__proto__ = proto;
return obj;
};
/* eslint-enable no-proto */
var utils = module.exports = {
objectIs: Object.is || function (a, b) {
// Polyfill from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is
if (a === 0 && b === 0) {
return 1 / a === 1 / b;
}
if (a !== a) {
return b !== b;
}
return a === b;
},
isArray: function (ar) {
return Object.prototype.toString.call(ar) === '[object Array]';
},
isRegExp: function (re) {
return (Object.prototype.toString.call(re) === '[object RegExp]');
},
isError: function (err) {
return typeof err === 'object' && (Object.prototype.toString.call(err) === '[object Error]' || err instanceof Error);
},
extend: function (target) {
for (var i = 1; i < arguments.length; i += 1) {
var source = arguments[i];
if (source) {
Object.keys(source).forEach(function (key) {
target[key] = source[key];
});
}
}
return target;
},
findFirst: function (arr, predicate) {
for (var i = 0 ; i < arr.length ; i += 1) {
if (predicate(arr[i])) {
return arr[i];
}
}
return null;
},
leftPad: function (str, width, ch) {
ch = ch || ' ';
while (str.length < width) {
str = ch + str;
}
return str;
},
escapeRegExpMetaChars: function (str) {
return str.replace(/[[\]{}()*+?.\\^$|]/g, '\\$&');
},
escapeChar: function (ch) {
if (ch === '\t') {
return '\\t';
} else if (ch === '\r') {
return '\\r';
} else {
var charCode = ch.charCodeAt(0);
var hexChars = charCode.toString(16).toUpperCase();
if (charCode < 256) {
return '\\x' + utils.leftPad(hexChars, 2, '0');
} else {
return '\\u' + utils.leftPad(hexChars, 4, '0');
}
}
},
getFunctionName: function (f) {
if (typeof f.name === 'string') {
return f.name;
}
var matchFunctionName = Function.prototype.toString.call(f).match(/function ([^\(]+)/);
if (matchFunctionName) {
return matchFunctionName[1];
}
if (f === Object) {
return 'Object';
}
if (f === Function) {
return 'Function';
}
return '';
},
wrapConstructorNameAroundOutput: function (output, obj) {
var constructor = obj.constructor;
var constructorName = constructor && constructor !== Object && utils.getFunctionName(constructor);
if (constructorName && constructorName !== 'Object') {
return output.clone().text(constructorName + '(').append(output).text(')');
} else {
return output;
}
},
setPrototypeOfOrExtend: canSetPrototype ? setPrototypeOf : function extend(target, source) {
for (var prop in source) {
if (source.hasOwnProperty(prop)) {
target[prop] = source[prop];
}
}
return target;
},
uniqueStringsAndSymbols: function () { // [filterFn], item1, item2...
var filterFn;
if (typeof arguments[0] === 'function') {
filterFn = arguments[0];
}
var index = {};
var uniqueStringsAndSymbols = [];
function visit(item) {
if (Array.isArray(item)) {
item.forEach(visit);
} else if (!Object.prototype.hasOwnProperty.call(index, item) && (!filterFn || filterFn(item))) {
index[item] = true;
uniqueStringsAndSymbols.push(item);
}
}
for (var i = filterFn ? 1 : 0 ; i < arguments.length ; i += 1) {
visit(arguments[i]);
}
return uniqueStringsAndSymbols;
},
uniqueNonNumericalStringsAndSymbols: function () { // ...
return utils.uniqueStringsAndSymbols(function (stringOrSymbol) {
return typeof stringOrSymbol === 'symbol' || !utils.numericalRegExp.test(stringOrSymbol);
}, Array.prototype.slice.call(arguments));
},
forwardFlags: function (testDescriptionString, flags) {
return testDescriptionString.replace(/\[(!?)([^\]]+)\] ?/g, function (match, negate, flag) {
return Boolean(flags[flag]) !== Boolean(negate) ? flag + ' ' : '';
}).trim();
},
numericalRegExp: /^(?:0|[1-9][0-9]*)$/,
packArrows: function (changes) {
var moveSourceAndTargetByActualIndex = {};
changes.forEach(function (diffItem, index) {
if (diffItem.type === 'moveSource') {
diffItem.changeIndex = index;
(moveSourceAndTargetByActualIndex[diffItem.actualIndex] = moveSourceAndTargetByActualIndex[diffItem.actualIndex] || {}).source = diffItem;
} else if (diffItem.type === 'moveTarget') {
diffItem.changeIndex = index;
(moveSourceAndTargetByActualIndex[diffItem.actualIndex] = moveSourceAndTargetByActualIndex[diffItem.actualIndex] || {}).target = diffItem;
}
});
var moveIndices = Object.keys(moveSourceAndTargetByActualIndex);
if (moveIndices.length > 0) {
var arrowSpecs = [];
moveIndices.sort(function (a, b) {
// Order by distance between change indices descending
return Math.abs(moveSourceAndTargetByActualIndex[b].source.changeIndex - moveSourceAndTargetByActualIndex[b].target.changeIndex) - Math.abs(moveSourceAndTargetByActualIndex[a].source.changeIndex - moveSourceAndTargetByActualIndex[a].target.changeIndex);
}).forEach(function (actualIndex, i, keys) {
var moveSourceAndMoveTarget = moveSourceAndTargetByActualIndex[actualIndex];
var firstChangeIndex = Math.min(moveSourceAndMoveTarget.source.changeIndex, moveSourceAndMoveTarget.target.changeIndex);
var lastChangeIndex = Math.max(moveSourceAndMoveTarget.source.changeIndex, moveSourceAndMoveTarget.target.changeIndex);
arrowSpecs.push({
start: firstChangeIndex,
end: lastChangeIndex,
direction: moveSourceAndMoveTarget.source.changeIndex < moveSourceAndMoveTarget.target.changeIndex ? 'down' : 'up'
});
});
var packing = greedyIntervalPacker(arrowSpecs);
while (packing.length > 3) {
// The arrow packing takes up too many lanes. Turn the moveSource/moveTarget items into inserts and removes
packing.shift().forEach(function (entry) {
changes[entry.direction === 'up' ? entry.start : entry.end].type = 'insert';
changes[entry.direction === 'up' ? entry.end : entry.start].type = 'remove';
});
}
return packing;
}
}
};
},{"36":36}],20:[function(require,module,exports){
var Promise = require(56);
var workQueue = {
queue: [],
drain: function () {
this.queue.forEach(function (fn) {
fn();
});
this.queue = [];
}
};
var scheduler = Promise.setScheduler(function (fn) {
workQueue.queue.push(fn);
scheduler(function () {
workQueue.drain();
});
});
Promise.prototype._notifyUnhandledRejection = function () {
var that = this;
scheduler(function () {
if (that._isRejectionUnhandled()) {
if (workQueue.onUnhandledRejection) { // for testing
workQueue.onUnhandledRejection(that.reason());
} else {
throw that.reason();
}
}
});
};
module.exports = workQueue;
},{"56":56}],21:[function(require,module,exports){
module.exports = require(2).create()
.use(require(15))
.use(require(17))
.use(require(5));
// Add an inspect method to all the promises we return that will make the REPL, console.log, and util.inspect render it nicely in node.js:
require(56).prototype.inspect = function () {
return module.exports.createOutput(require(44).defaultFormat).appendInspected(this).toString();
};
},{"15":15,"17":17,"2":2,"44":44,"5":5,"56":56}],22:[function(require,module,exports){
'use strict';
var styles = module.exports = {
modifiers: {
reset: [0, 0],
bold: [1, 22], // 21 isn't widely supported and 22 does the same thing
dim: [2, 22],
italic: [3, 23],
underline: [4, 24],
inverse: [7, 27],
hidden: [8, 28],
strikethrough: [9, 29]
},
colors: {
black: [30, 39],
red: [31, 39],
green: [32, 39],
yellow: [33, 39],
blue: [34, 39],
magenta: [35, 39],
cyan: [36, 39],
white: [37, 39],
gray: [90, 39]
},
bgColors: {
bgBlack: [40, 49],
bgRed: [41, 49],
bgGreen: [42, 49],
bgYellow: [43, 49],
bgBlue: [44, 49],
bgMagenta: [45, 49],
bgCyan: [46, 49],
bgWhite: [47, 49]
}
};
// fix humans
styles.colors.grey = styles.colors.gray;
Object.keys(styles).forEach(function (groupName) {
var group = styles[groupName];
Object.keys(group).forEach(function (styleName) {
var style = group[styleName];
styles[styleName] = group[styleName] = {
open: '\u001b[' + style[0] + 'm',
close: '\u001b[' + style[1] + 'm'
};
});
Object.defineProperty(styles, groupName, {
value: group,
enumerable: false
});
});
},{}],23:[function(require,module,exports){
/*global setTimeout */
var arrayDiff = require(25);
var MAX_STACK_DEPTH = 1000;
function extend(target) {
for (var i = 1; i < arguments.length; i += 1) {
var source = arguments[i];
Object.keys(source).forEach(function (key) {
target[key] = source[key];
});
}
return target;
}
module.exports = function arrayChanges(actual, expected, equal, similar, includeNonNumericalProperties, arrayChangesCallback) {
if (typeof includeNonNumericalProperties === 'function') {
arrayChangesCallback = includeNonNumericalProperties;
includeNonNumericalProperties = false;
}
var mutatedArray = new Array(actual.length);
for (var k = 0; k < actual.length; k += 1) {
mutatedArray[k] = {
type: 'similar',
actualIndex: k,
value: actual[k]
};
}
similar = similar || function (a, b, aIndex, bIndex, callback) {
return callback(false);
};
arrayDiff([].concat(actual), [].concat(expected), function (a, b, aIndex, bIndex, callback) {
equal(a, b, aIndex, bIndex, function (isEqual) {
if (isEqual) {
return callback(true);
}
similar(a, b, aIndex, bIndex, function (isSimilar) {
return callback(isSimilar);
});
});
}, function (itemsDiff) {
function offsetIndex(index) {
var offsetIndex = 0;
var i;
for (i = 0; i < mutatedArray.length && offsetIndex < index; i += 1) {
if (mutatedArray[i].type !== 'remove' && mutatedArray[i].type !== 'moveSource') {
offsetIndex++;
}
}
return i;
}
var removes = itemsDiff.filter(function (diffItem) {
return diffItem.type === 'remove';
});
var removedItems = 0;
removes.forEach(function (diffItem) {
var removeIndex = removedItems + diffItem.index;
mutatedArray.slice(removeIndex, diffItem.howMany + removeIndex).forEach(function (v) {
v.type = 'remove';
});
removedItems += diffItem.howMany;
});
var moves = itemsDiff.filter(function (diffItem) {
return diffItem.type === 'move';
});
moves.forEach(function (diffItem) {
var moveFromIndex = offsetIndex(diffItem.from + 1) - 1;
var removed = mutatedArray.slice(moveFromIndex, diffItem.howMany + moveFromIndex);
var added = removed.map(function (v) {
return extend({}, v, { last: false, type: 'moveTarget' });
});
removed.forEach(function (v) {
v.type = 'moveSource';
});
var insertIndex = offsetIndex(diffItem.to);
Array.prototype.splice.apply(mutatedArray, [insertIndex, 0].concat(added));
});
var inserts = itemsDiff.filter(function (diffItem) {
return diffItem.type === 'insert';
});
inserts.forEach(function (diffItem) {
var added = new Array(diffItem.values.length);
for (var i = 0 ; i < diffItem.values.length ; i += 1) {
added[i] = {
type: 'insert',
value: diffItem.values[i]
};
}
Array.prototype.splice.apply(mutatedArray, [offsetIndex(diffItem.index), 0].concat(added));
});
var offset = 0;
mutatedArray.forEach(function (diffItem, index) {
var type = diffItem.type;
if (type === 'remove' || type === 'moveSource') {
offset -= 1;
} else if (type === 'similar') {
diffItem.expected = expected[offset + index];
diffItem.expectedIndex = offset + index;
}
});
var conflicts = mutatedArray.reduce(function (conflicts, item) {
return item.type === 'similar' || item.type === 'moveSource' || item.type === 'moveTarget' ? conflicts : conflicts + 1;
}, 0);
var end = Math.max(actual.length, expected.length);
var countConflicts = function (i, c, stackCallsRemaining, callback) {
if (i >= end || c > conflicts) {
// Do a setTimeout to let the stack unwind
return setTimeout(function () {
callback(c);
}, 0);
}
similar(actual[i], expected[i], i, i, function (areSimilar) {
if (!areSimilar) {
c += 1;
if (stackCallsRemaining === 0) {
return setTimeout(function () {
countConflicts(i + 1, c, MAX_STACK_DEPTH, callback);
});
}
return countConflicts(i + 1, c, stackCallsRemaining - 1, callback);
}
equal(actual[i], expected[i], i, i, function (areEqual) {
if (!areEqual) {
c += 1;
}
if (stackCallsRemaining === 0) {
return setTimeout(function () {
countConflicts(i + 1, c, MAX_STACK_DEPTH, callback);
});
}
return countConflicts(i + 1, c, stackCallsRemaining - 1, callback);
});
});
};
countConflicts(0, 0, MAX_STACK_DEPTH, function (c) {
if (c <= conflicts) {
mutatedArray = [];
var j;
for (j = 0; j < Math.min(actual.length, expected.length); j += 1) {
mutatedArray.push({
type: 'similar',
actualIndex: j,
expectedIndex: j,
value: actual[j],
expected: expected[j]
});
}
if (actual.length < expected.length) {
for (; j < Math.max(actual.length, expected.length); j += 1) {
mutatedArray.push({
type: 'insert',
value: expected[j]
});
}
} else {
for (; j < Math.max(actual.length, expected.length); j += 1) {
mutatedArray.push({
type: 'remove',
value: actual[j]
});
}
}
}
var setEqual = function (i, stackCallsRemaining, callback) {
if (i >= mutatedArray.length) {
return callback();
}
var diffItem = mutatedArray[i];
if (diffItem.type === 'similar') {
return equal(diffItem.value, diffItem.expected, diffItem.actualIndex, diffItem.expectedIndex, function (areEqual) {
if (areEqual) {
mutatedArray[i].type = 'equal';
}
if (stackCallsRemaining === 0) {
return setTimeout(function () {
setEqual(i + 1, MAX_STACK_DEPTH, callback);
});
}
setEqual(i + 1, stackCallsRemaining - 1, callback);
});
}
if (stackCallsRemaining === 0) {
return setTimeout(function () {
setEqual(i + 1, MAX_STACK_DEPTH, callback);
});
}
return setEqual(i + 1, stackCallsRemaining - 1, callback);
};
if (includeNonNumericalProperties) {
var nonNumericalKeys;
if (Array.isArray(includeNonNumericalProperties)) {
nonNumericalKeys = includeNonNumericalProperties;
} else {
var isSeenByNonNumericalKey = {};
nonNumericalKeys = [];
[actual, expected].forEach(function (obj) {
Object.keys(obj).forEach(function (key) {
if (!/^(?:0|[1-9][0-9]*)$/.test(key) && !isSeenByNonNumericalKey[key]) {
isSeenByNonNumericalKey[key] = true;
nonNumericalKeys.push(key);
}
});
if (Object.getOwnPropertySymbols) {
Object.getOwnPropertySymbols(obj).forEach(function (symbol) {
if (!isSeenByNonNumericalKey[symbol]) {
isSeenByNonNumericalKey[symbol] = true;
nonNumericalKeys.push(symbol);
}
});
}
});
}
nonNumericalKeys.forEach(function (key) {
if (key in actual) {
if (key in expected) {
mutatedArray.push({
type: 'similar',
expectedIndex: key,
actualIndex: key,
value: actual[key],
expected: expected[key]
});
} else {
mutatedArray.push({
type: 'remove',
actualIndex: key,
value: actual[key]
});
}
} else {
mutatedArray.push({
type: 'insert',
expectedIndex: key,
value: expected[key]
});
}
});
}
setEqual(0, MAX_STACK_DEPTH, function () {
if (mutatedArray.length > 0) {
mutatedArray[mutatedArray.length - 1].last = true;
}
arrayChangesCallback(mutatedArray);
});
});
});
};
},{"25":25}],24:[function(require,module,exports){
var arrayDiff = require(26);
function extend(target) {
for (var i = 1; i < arguments.length; i += 1) {
var source = arguments[i];
Object.keys(source).forEach(function (key) {
target[key] = source[key];
});
}
return target;
}
module.exports = function arrayChanges(actual, expected, equal, similar, includeNonNumericalProperties) {
var mutatedArray = new Array(actual.length);
for (var k = 0; k < actual.length; k += 1) {
mutatedArray[k] = {
type: 'similar',
value: actual[k],
actualIndex: k
};
}
equal = equal || function (a, b) {
return a === b;
};
similar = similar || function (a, b) {
return false;
};
var itemsDiff = arrayDiff(Array.prototype.slice.call(actual), Array.prototype.slice.call(expected), function (a, b, aIndex, bIndex) {
return equal(a, b, aIndex, bIndex) || similar(a, b, aIndex, bIndex);
});
function offsetIndex(index) {
var offsetIndex = 0;
var i;
for (i = 0; i < mutatedArray.length && offsetIndex < index; i += 1) {
if (mutatedArray[i].type !== 'remove' && mutatedArray[i].type !== 'moveSource') {
offsetIndex++;
}
}
return i;
}
var removes = itemsDiff.filter(function (diffItem) {
return diffItem.type === 'remove';
});
var removedItems = 0;
removes.forEach(function (diffItem) {
var removeIndex = removedItems + diffItem.index;
mutatedArray.slice(removeIndex, diffItem.howMany + removeIndex).forEach(function (v) {
v.type = 'remove';
});
removedItems += diffItem.howMany;
});
var moves = itemsDiff.filter(function (diffItem) {
return diffItem.type === 'move';
});
moves.forEach(function (diffItem) {
var moveFromIndex = offsetIndex(diffItem.from + 1) - 1;
var removed = mutatedArray.slice(moveFromIndex, diffItem.howMany + moveFromIndex);
var added = removed.map(function (v) {
return extend({}, v, { last: false, type: 'moveTarget' });
});
removed.forEach(function (v) {
v.type = 'moveSource';
});
var insertIndex = offsetIndex(diffItem.to);
Array.prototype.splice.apply(mutatedArray, [insertIndex, 0].concat(added));
});
var inserts = itemsDiff.filter(function (diffItem) {
return diffItem.type === 'insert';
});
inserts.forEach(function (diffItem) {
var added = new Array(diffItem.values.length);
for (var i = 0 ; i < diffItem.values.length ; i += 1) {
added[i] = {
type: 'insert',
value: diffItem.values[i],
expectedIndex: diffItem.index
};
}
var insertIndex = offsetIndex(diffItem.index);
Array.prototype.splice.apply(mutatedArray, [insertIndex, 0].concat(added));
});
var offset = 0;
mutatedArray.forEach(function (diffItem, index) {
var type = diffItem.type;
if (type === 'remove' || type === 'moveSource') {
offset -= 1;
} else if (type === 'similar') {
diffItem.expected = expected[offset + index];
diffItem.expectedIndex = offset + index;
}
});
var conflicts = mutatedArray.reduce(function (conflicts, item) {
return item.type === 'similar' || item.type === 'moveSource' || item.type === 'moveTarget' ? conflicts : conflicts + 1;
}, 0);
var c, i;
for (i = 0, c = 0; i < Math.max(actual.length, expected.length) && c <= conflicts; i += 1) {
if (
i >= actual.length || i >= expected.length || (!equal(actual[i], expected[i], i, i) && !similar(actual[i], expected[i], i, i))
) {
c += 1;
}
}
if (c <= conflicts) {
mutatedArray = [];
var j;
for (j = 0; j < Math.min(actual.length, expected.length); j += 1) {
mutatedArray.push({
type: 'similar',
value: actual[j],
expected: expected[j],
actualIndex: j,
expectedIndex: j
});
}
if (actual.length < expected.length) {
for (; j < Math.max(actual.length, expected.length); j += 1) {
mutatedArray.push({
type: 'insert',
value: expected[j],
expectedIndex: j
});
}
} else {
for (; j < Math.max(actual.length, expected.length); j += 1) {
mutatedArray.push({
type: 'remove',
value: actual[j],
actualIndex: j
});
}
}
}
mutatedArray.forEach(function (diffItem) {
if (diffItem.type === 'similar' && equal(diffItem.value, diffItem.expected, diffItem.actualIndex, diffItem.expectedIndex)) {
diffItem.type = 'equal';
}
});
if (includeNonNumericalProperties) {
var nonNumericalKeys;
if (Array.isArray(includeNonNumericalProperties)) {
nonNumericalKeys = includeNonNumericalProperties;
} else {
var isSeenByNonNumericalKey = {};
nonNumericalKeys = [];
[actual, expected].forEach(function (obj) {
Object.keys(obj).forEach(function (key) {
if (!/^(?:0|[1-9][0-9]*)$/.test(key) && !isSeenByNonNumericalKey[key]) {
isSeenByNonNumericalKey[key] = true;
nonNumericalKeys.push(key);
}
});
if (Object.getOwnPropertySymbols) {
Object.getOwnPropertySymbols(obj).forEach(function (symbol) {
if (!isSeenByNonNumericalKey[symbol]) {
isSeenByNonNumericalKey[symbol] = true;
nonNumericalKeys.push(symbol);
}
});
}
});
}
nonNumericalKeys.forEach(function (key) {
if (key in actual) {
if (key in expected) {
mutatedArray.push({
type: equal(actual[key], expected[key], key, key) ? 'equal' : 'similar',
expectedIndex: key,
actualIndex: key,
value: actual[key],
expected: expected[key]
});
} else {
mutatedArray.push({
type: 'remove',
actualIndex: key,
value: actual[key]
});
}
} else {
mutatedArray.push({
type: 'insert',
expectedIndex: key,
value: expected[key]
});
}
});
}
if (mutatedArray.length > 0) {
mutatedArray[mutatedArray.length - 1].last = true;
}
return mutatedArray;
};
},{"26":26}],25:[function(require,module,exports){
module.exports = arrayDiff;
var MAX_STACK_DEPTH = 1000;
// Based on some rough benchmarking, this algorithm is about O(2n) worst case,
// and it can compute diffs on random arrays of length 1024 in about 34ms,
// though just a few changes on an array of length 1024 takes about 0.5ms
arrayDiff.InsertDiff = InsertDiff;
arrayDiff.RemoveDiff = RemoveDiff;
arrayDiff.MoveDiff = MoveDiff;
function InsertDiff(index, values) {
this.index = index;
this.values = values;
}
InsertDiff.prototype.type = 'insert';
InsertDiff.prototype.toJSON = function() {
return {
type: this.type
, index: this.index
, values: this.values
};
};
function RemoveDiff(index, howMany) {
this.index = index;
this.howMany = howMany;
}
RemoveDiff.prototype.type = 'remove';
RemoveDiff.prototype.toJSON = function() {
return {
type: this.type
, index: this.index
, howMany: this.howMany
};
};
function MoveDiff(from, to, howMany) {
this.from = from;
this.to = to;
this.howMany = howMany;
}
MoveDiff.prototype.type = 'move';
MoveDiff.prototype.toJSON = function() {
return {
type: this.type
, from: this.from
, to: this.to
, howMany: this.howMany
};
};
function strictEqual(a, b, indexA, indexB, callback) {
return callback(a === b);
}
function arrayDiff(before, after, equalFn, callback) {
if (!equalFn) equalFn = strictEqual;
// Find all items in both the before and after array, and represent them
// as moves. Many of these "moves" may end up being discarded in the last
// pass if they are from an index to the same index, but we don't know this
// up front, since we haven't yet offset the indices.
//
// Also keep a map of all the indices accounted for in the before and after
// arrays. These maps are used next to create insert and remove diffs.
var beforeLength = before.length;
var afterLength = after.length;
var moves = [];
var beforeMarked = {};
var afterMarked = {};
function findMatching(beforeIndex, afterIndex, howMany, callback) {
beforeMarked[beforeIndex++] = afterMarked[afterIndex++] = true;
howMany++;
if (beforeIndex < beforeLength &&
afterIndex < afterLength &&
!afterMarked[afterIndex]) {
equalFn(before[beforeIndex], after[afterIndex], beforeIndex, afterIndex, function (areEqual) {
if (areEqual) {
setTimeout(function () {
findMatching(beforeIndex, afterIndex, howMany, callback);
}, 0);
} else {
callback(beforeIndex, afterIndex, howMany);
}
});
} else {
callback(beforeIndex, afterIndex, howMany);
}
}
function compare(beforeIndex, afterIndex, stackDepthRemaining, callback) {
if (afterIndex >= afterLength) {
beforeIndex++;
afterIndex = 0;
}
if (beforeIndex >= beforeLength) {
callback();
return;
}
if (!afterMarked[afterIndex]) {
equalFn(before[beforeIndex], after[afterIndex], beforeIndex, afterIndex, function (areEqual) {
if (areEqual) {
var from = beforeIndex;
var to = afterIndex;
findMatching(beforeIndex, afterIndex, 0, function (newBeforeIndex, newAfterIndex, howMany) {
moves.push(new MoveDiff(from, to, howMany));
if (stackDepthRemaining) {
compare(newBeforeIndex, 0, stackDepthRemaining - 1, callback);
} else {
setTimeout(function () {
compare(newBeforeIndex, 0, MAX_STACK_DEPTH, callback);
}, 0);
}
});
} else {
if (stackDepthRemaining) {
compare(beforeIndex, afterIndex + 1, stackDepthRemaining - 1, callback);
} else {
setTimeout(function () {
compare(beforeIndex, afterIndex + 1, MAX_STACK_DEPTH, callback);
}, 0);
}
}
});
} else {
if (stackDepthRemaining) {
compare(beforeIndex, afterIndex + 1, stackDepthRemaining - 1, callback);
} else {
setTimeout(function () {
compare(beforeIndex, afterIndex + 1, MAX_STACK_DEPTH, callback);
}, 0);
}
}
}
compare(0, 0, MAX_STACK_DEPTH, function () {
// Create a remove for all of the items in the before array that were
// not marked as being matched in the after array as well
var removes = [];
for (var beforeIndex = 0; beforeIndex < beforeLength;) {
if (beforeMarked[beforeIndex]) {
beforeIndex++;
continue;
}
var index = beforeIndex;
var howMany = 0;
while (beforeIndex < beforeLength && !beforeMarked[beforeIndex++]) {
howMany++;
}
removes.push(new RemoveDiff(index, howMany));
}
// Create an insert for all of the items in the after array that were
// not marked as being matched in the before array as well
var inserts = [];
for (var afterIndex = 0; afterIndex < afterLength;) {
if (afterMarked[afterIndex]) {
afterIndex++;
continue;
}
var index = afterIndex;
var howMany = 0;
while (afterIndex < afterLength && !afterMarked[afterIndex++]) {
howMany++;
}
var values = after.slice(index, index + howMany);
inserts.push(new InsertDiff(index, values));
}
var insertsLength = inserts.length;
var removesLength = removes.length;
var movesLength = moves.length;
var i, j;
// Offset subsequent removes and moves by removes
var count = 0;
for (i = 0; i < removesLength; i++) {
var remove = removes[i];
remove.index -= count;
count += remove.howMany;
for (j = 0; j < movesLength; j++) {
var move = moves[j];
if (move.from >= remove.index) move.from -= remove.howMany;
}
}
// Offset moves by inserts
for (i = insertsLength; i--;) {
var insert = inserts[i];
var howMany = insert.values.length;
for (j = movesLength; j--;) {
var move = moves[j];
if (move.to >= insert.index) move.to -= howMany;
}
}
// Offset the to of moves by later moves
for (i = movesLength; i-- > 1;) {
var move = moves[i];
if (move.to === move.from) continue;
for (j = i; j--;) {
var earlier = moves[j];
if (earlier.to >= move.to) earlier.to -= move.howMany;
if (earlier.to >= move.from) earlier.to += move.howMany;
}
}
// Only output moves that end up having an effect after offsetting
var outputMoves = [];
// Offset the from of moves by earlier moves
for (i = 0; i < movesLength; i++) {
var move = moves[i];
if (move.to === move.from) continue;
outputMoves.push(move);
for (j = i + 1; j < movesLength; j++) {
var later = moves[j];
if (later.from >= move.from) later.from -= move.howMany;
if (later.from >= move.to) later.from += move.howMany;
}
}
callback(removes.concat(outputMoves, inserts));
});
}
},{}],26:[function(require,module,exports){
module.exports = arrayDiff;
// Based on some rough benchmarking, this algorithm is about O(2n) worst case,
// and it can compute diffs on random arrays of length 1024 in about 34ms,
// though just a few changes on an array of length 1024 takes about 0.5ms
arrayDiff.InsertDiff = InsertDiff;
arrayDiff.RemoveDiff = RemoveDiff;
arrayDiff.MoveDiff = MoveDiff;
function InsertDiff(index, values) {
this.index = index;
this.values = values;
}
InsertDiff.prototype.type = 'insert';
InsertDiff.prototype.toJSON = function() {
return {
type: this.type
, index: this.index
, values: this.values
};
};
function RemoveDiff(index, howMany) {
this.index = index;
this.howMany = howMany;
}
RemoveDiff.prototype.type = 'remove';
RemoveDiff.prototype.toJSON = function() {
return {
type: this.type
, index: this.index
, howMany: this.howMany
};
};
function MoveDiff(from, to, howMany) {
this.from = from;
this.to = to;
this.howMany = howMany;
}
MoveDiff.prototype.type = 'move';
MoveDiff.prototype.toJSON = function() {
return {
type: this.type
, from: this.from
, to: this.to
, howMany: this.howMany
};
};
function strictEqual(a, b) {
return a === b;
}
function arrayDiff(before, after, equalFn) {
if (!equalFn) equalFn = strictEqual;
// Find all items in both the before and after array, and represent them
// as moves. Many of these "moves" may end up being discarded in the last
// pass if they are from an index to the same index, but we don't know this
// up front, since we haven't yet offset the indices.
//
// Also keep a map of all the indices accounted for in the before and after
// arrays. These maps are used next to create insert and remove diffs.
var beforeLength = before.length;
var afterLength = after.length;
var moves = [];
var beforeMarked = {};
var afterMarked = {};
for (var beforeIndex = 0; beforeIndex < beforeLength; beforeIndex++) {
var beforeItem = before[beforeIndex];
for (var afterIndex = 0; afterIndex < afterLength; afterIndex++) {
if (afterMarked[afterIndex]) continue;
if (!equalFn(beforeItem, after[afterIndex], beforeIndex, afterIndex)) continue;
var from = beforeIndex;
var to = afterIndex;
var howMany = 0;
do {
beforeMarked[beforeIndex++] = afterMarked[afterIndex++] = true;
howMany++;
} while (
beforeIndex < beforeLength &&
afterIndex < afterLength &&
equalFn(before[beforeIndex], after[afterIndex], beforeIndex, afterIndex) &&
!afterMarked[afterIndex]
);
moves.push(new MoveDiff(from, to, howMany));
beforeIndex--;
break;
}
}
// Create a remove for all of the items in the before array that were
// not marked as being matched in the after array as well
var removes = [];
for (beforeIndex = 0; beforeIndex < beforeLength;) {
if (beforeMarked[beforeIndex]) {
beforeIndex++;
continue;
}
var index = beforeIndex;
var howMany = 0;
while (beforeIndex < beforeLength && !beforeMarked[beforeIndex++]) {
howMany++;
}
removes.push(new RemoveDiff(index, howMany));
}
// Create an insert for all of the items in the after array that were
// not marked as being matched in the before array as well
var inserts = [];
for (afterIndex = 0; afterIndex < afterLength;) {
if (afterMarked[afterIndex]) {
afterIndex++;
continue;
}
var index = afterIndex;
var howMany = 0;
while (afterIndex < afterLength && !afterMarked[afterIndex++]) {
howMany++;
}
var values = after.slice(index, index + howMany);
inserts.push(new InsertDiff(index, values));
}
var insertsLength = inserts.length;
var removesLength = removes.length;
var movesLength = moves.length;
var i, j;
// Offset subsequent removes and moves by removes
var count = 0;
for (i = 0; i < removesLength; i++) {
var remove = removes[i];
remove.index -= count;
count += remove.howMany;
for (j = 0; j < movesLength; j++) {
var move = moves[j];
if (move.from >= remove.index) move.from -= remove.howMany;
}
}
// Offset moves by inserts
for (i = insertsLength; i--;) {
var insert = inserts[i];
var howMany = insert.values.length;
for (j = movesLength; j--;) {
var move = moves[j];
if (move.to >= insert.index) move.to -= howMany;
}
}
// Offset the to of moves by later moves
for (i = movesLength; i-- > 1;) {
var move = moves[i];
if (move.to === move.from) continue;
for (j = i; j--;) {
var earlier = moves[j];
if (earlier.to >= move.to) earlier.to -= move.howMany;
if (earlier.to >= move.from) earlier.to += move.howMany;
}
}
// Only output moves that end up having an effect after offsetting
var outputMoves = [];
// Offset the from of moves by earlier moves
for (i = 0; i < movesLength; i++) {
var move = moves[i];
if (move.to === move.from) continue;
outputMoves.push(move);
for (j = i + 1; j < movesLength; j++) {
var later = moves[j];
if (later.from >= move.from) later.from -= move.howMany;
if (later.from >= move.to) later.from += move.howMany;
}
}
return removes.concat(outputMoves, inserts);
}
},{}],27:[function(require,module,exports){
'use strict'
exports.byteLength = byteLength
exports.toByteArray = toByteArray
exports.fromByteArray = fromByteArray
var lookup = []
var revLookup = []
var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
for (var i = 0, len = code.length; i < len; ++i) {
lookup[i] = code[i]
revLookup[code.charCodeAt(i)] = i
}
revLookup['-'.charCodeAt(0)] = 62
revLookup['_'.charCodeAt(0)] = 63
function placeHoldersCount (b64) {
var len = b64.length
if (len % 4 > 0) {
throw new Error('Invalid string. Length must be a multiple of 4')
}
// the number of equal signs (place holders)
// if there are two placeholders, than the two characters before it
// represent one byte
// if there is only one, then the three characters before it represent 2 bytes
// this is just a cheap hack to not do indexOf twice
return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0
}
function byteLength (b64) {
// base64 is 4/3 + up to two characters of the original data
return b64.length * 3 / 4 - placeHoldersCount(b64)
}
function toByteArray (b64) {
var i, j, l, tmp, placeHolders, arr
var len = b64.length
placeHolders = placeHoldersCount(b64)
arr = new Arr(len * 3 / 4 - placeHolders)
// if there are placeholders, only get up to the last complete 4 chars
l = placeHolders > 0 ? len - 4 : len
var L = 0
for (i = 0, j = 0; i < l; i += 4, j += 3) {
tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]
arr[L++] = (tmp >> 16) & 0xFF
arr[L++] = (tmp >> 8) & 0xFF
arr[L++] = tmp & 0xFF
}
if (placeHolders === 2) {
tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4)
arr[L++] = tmp & 0xFF
} else if (placeHolders === 1) {
tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2)
arr[L++] = (tmp >> 8) & 0xFF
arr[L++] = tmp & 0xFF
}
return arr
}
function tripletToBase64 (num) {
return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
}
function encodeChunk (uint8, start, end) {
var tmp
var output = []
for (var i = start; i < end; i += 3) {
tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
output.push(tripletToBase64(tmp))
}
return output.join('')
}
function fromByteArray (uint8) {
var tmp
var len = uint8.length
var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
var output = ''
var parts = []
var maxChunkLength = 16383 // must be multiple of 3
// go through the array every three bytes, we'll deal with trailing stuff later
for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
}
// pad the end with zeros, but make sure to not forget the extra bytes
if (extraBytes === 1) {
tmp = uint8[len - 1]
output += lookup[tmp >> 2]
output += lookup[(tmp << 4) & 0x3F]
output += '=='
} else if (extraBytes === 2) {
tmp = (uint8[len - 2] << 8) + (uint8[len - 1])
output += lookup[tmp >> 10]
output += lookup[(tmp >> 4) & 0x3F]
output += lookup[(tmp << 2) & 0x3F]
output += '='
}
parts.push(output)
return parts.join('')
}
},{}],28:[function(require,module,exports){
/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <[email protected]> <http://feross.org>
* @license MIT
*/
/* eslint-disable no-proto */
'use strict'
var base64 = require(27)
var ieee754 = require(38)
exports.Buffer = Buffer
exports.SlowBuffer = SlowBuffer
exports.INSPECT_MAX_BYTES = 50
var K_MAX_LENGTH = 0x7fffffff
exports.kMaxLength = K_MAX_LENGTH
/**
* If `Buffer.TYPED_ARRAY_SUPPORT`:
* === true Use Uint8Array implementation (fastest)
* === false Print warning and recommend using `buffer` v4.x which has an Object
* implementation (most compatible, even IE6)
*
* Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
* Opera 11.6+, iOS 4.2+.
*
* We report that the browser does not support typed arrays if the are not subclassable
* using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
* (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
* for __proto__ and has a buggy typed array implementation.
*/
Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
typeof console.error === 'function') {
console.error(
'This browser lacks typed array (Uint8Array) support which is required by ' +
'`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
)
}
function typedArraySupport () {
// Can typed array instances can be augmented?
try {
var arr = new Uint8Array(1)
arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}
return arr.foo() === 42
} catch (e) {
return false
}
}
function createBuffer (length) {
if (length > K_MAX_LENGTH) {
throw new RangeError('Invalid typed array length')
}
// Return an augmented `Uint8Array` instance
var buf = new Uint8Array(length)
buf.__proto__ = Buffer.prototype
return buf
}
/**
* The Buffer constructor returns instances of `Uint8Array` that have their
* prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
* `Uint8Array`, so the returned instances will have all the node `Buffer` methods
* and the `Uint8Array` methods. Square bracket notation works as expected -- it
* returns a single octet.
*
* The `Uint8Array` prototype remains unmodified.
*/
function Buffer (arg, encodingOrOffset, length) {
// Common case.
if (typeof arg === 'number') {
if (typeof encodingOrOffset === 'string') {
throw new Error(
'If encoding is specified then the first argument must be a string'
)
}
return allocUnsafe(arg)
}
return from(arg, encodingOrOffset, length)
}
// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
if (typeof Symbol !== 'undefined' && Symbol.species &&
Buffer[Symbol.species] === Buffer) {
Object.defineProperty(Buffer, Symbol.species, {
value: null,
configurable: true,
enumerable: false,
writable: false
})
}
Buffer.poolSize = 8192 // not used by this implementation
function from (value, encodingOrOffset, length) {
if (typeof value === 'number') {
throw new TypeError('"value" argument must not be a number')
}
if (value instanceof ArrayBuffer) {
return fromArrayBuffer(value, encodingOrOffset, length)
}
if (typeof value === 'string') {
return fromString(value, encodingOrOffset)
}
return fromObject(value)
}
/**
* Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
* if value is a number.
* Buffer.from(str[, encoding])
* Buffer.from(array)
* Buffer.from(buffer)
* Buffer.from(arrayBuffer[, byteOffset[, length]])
**/
Buffer.from = function (value, encodingOrOffset, length) {
return from(value, encodingOrOffset, length)
}
// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
// https://github.com/feross/buffer/pull/148
Buffer.prototype.__proto__ = Uint8Array.prototype
Buffer.__proto__ = Uint8Array
function assertSize (size) {
if (typeof size !== 'number') {
throw new TypeError('"size" argument must be a number')
} else if (size < 0) {
throw new RangeError('"size" argument must not be negative')
}
}
function alloc (size, fill, encoding) {
assertSize(size)
if (size <= 0) {
return createBuffer(size)
}
if (fill !== undefined) {
// Only pay attention to encoding if it's a string. This
// prevents accidentally sending in a number that would
// be interpretted as a start offset.
return typeof encoding === 'string'
? createBuffer(size).fill(fill, encoding)
: createBuffer(size).fill(fill)
}
return createBuffer(size)
}
/**
* Creates a new filled Buffer instance.
* alloc(size[, fill[, encoding]])
**/
Buffer.alloc = function (size, fill, encoding) {
return alloc(size, fill, encoding)
}
function allocUnsafe (size) {
assertSize(size)
return createBuffer(size < 0 ? 0 : checked(size) | 0)
}
/**
* Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
* */
Buffer.allocUnsafe = function (size) {
return allocUnsafe(size)
}
/**
* Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
*/
Buffer.allocUnsafeSlow = function (size) {
return allocUnsafe(size)
}
function fromString (string, encoding) {
if (typeof encoding !== 'string' || encoding === '') {
encoding = 'utf8'
}
if (!Buffer.isEncoding(encoding)) {
throw new TypeError('"encoding" must be a valid string encoding')
}
var length = byteLength(string, encoding) | 0
var buf = createBuffer(length)
var actual = buf.write(string, encoding)
if (actual !== length) {
// Writing a hex string, for example, that contains invalid characters will
// cause everything after the first invalid character to be ignored. (e.g.
// 'abxxcd' will be treated as 'ab')
buf = buf.slice(0, actual)
}
return buf
}
function fromArrayLike (array) {
var length = array.length < 0 ? 0 : checked(array.length) | 0
var buf = createBuffer(length)
for (var i = 0; i < length; i += 1) {
buf[i] = array[i] & 255
}
return buf
}
function fromArrayBuffer (array, byteOffset, length) {
if (byteOffset < 0 || array.byteLength < byteOffset) {
throw new RangeError('\'offset\' is out of bounds')
}
if (array.byteLength < byteOffset + (length || 0)) {
throw new RangeError('\'length\' is out of bounds')
}
var buf
if (byteOffset === undefined && length === undefined) {
buf = new Uint8Array(array)
} else if (length === undefined) {
buf = new Uint8Array(array, byteOffset)
} else {
buf = new Uint8Array(array, byteOffset, length)
}
// Return an augmented `Uint8Array` instance
buf.__proto__ = Buffer.prototype
return buf
}
function fromObject (obj) {
if (Buffer.isBuffer(obj)) {
var len = checked(obj.length) | 0
var buf = createBuffer(len)
if (buf.length === 0) {
return buf
}
obj.copy(buf, 0, 0, len)
return buf
}
if (obj) {
if (isArrayBufferView(obj) || 'length' in obj) {
if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
return createBuffer(0)
}
return fromArrayLike(obj)
}
if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
return fromArrayLike(obj.data)
}
}
throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
}
function checked (length) {
// Note: cannot use `length < K_MAX_LENGTH` here because that fails when
// length is NaN (which is otherwise coerced to zero.)
if (length >= K_MAX_LENGTH) {
throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
}
return length | 0
}
function SlowBuffer (length) {
if (+length != length) { // eslint-disable-line eqeqeq
length = 0
}
return Buffer.alloc(+length)
}
Buffer.isBuffer = function isBuffer (b) {
return b != null && b._isBuffer === true
}
Buffer.compare = function compare (a, b) {
if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
throw new TypeError('Arguments must be Buffers')
}
if (a === b) return 0
var x = a.length
var y = b.length
for (var i = 0, len = Math.min(x, y); i < len; ++i) {
if (a[i] !== b[i]) {
x = a[i]
y = b[i]
break
}
}
if (x < y) return -1
if (y < x) return 1
return 0
}
Buffer.isEncoding = function isEncoding (encoding) {
switch (String(encoding).toLowerCase()) {
case 'hex':
case 'utf8':
case 'utf-8':
case 'ascii':
case 'latin1':
case 'binary':
case 'base64':
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return true
default:
return false
}
}
Buffer.concat = function concat (list, length) {
if (!Array.isArray(list)) {
throw new TypeError('"list" argument must be an Array of Buffers')
}
if (list.length === 0) {
return Buffer.alloc(0)
}
var i
if (length === undefined) {
length = 0
for (i = 0; i < list.length; ++i) {
length += list[i].length
}
}
var buffer = Buffer.allocUnsafe(length)
var pos = 0
for (i = 0; i < list.length; ++i) {
var buf = list[i]
if (!Buffer.isBuffer(buf)) {
throw new TypeError('"list" argument must be an Array of Buffers')
}
buf.copy(buffer, pos)
pos += buf.length
}
return buffer
}
function byteLength (string, encoding) {
if (Buffer.isBuffer(string)) {
return string.length
}
if (isArrayBufferView(string) || string instanceof ArrayBuffer) {
return string.byteLength
}
if (typeof string !== 'string') {
string = '' + string
}
var len = string.length
if (len === 0) return 0
// Use a for loop to avoid recursion
var loweredCase = false
for (;;) {
switch (encoding) {
case 'ascii':
case 'latin1':
case 'binary':
return len
case 'utf8':
case 'utf-8':
case undefined:
return utf8ToBytes(string).length
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return len * 2
case 'hex':
return len >>> 1
case 'base64':
return base64ToBytes(string).length
default:
if (loweredCase) return utf8ToBytes(string).length // assume utf8
encoding = ('' + encoding).toLowerCase()
loweredCase = true
}
}
}
Buffer.byteLength = byteLength
function slowToString (encoding, start, end) {
var loweredCase = false
// No need to verify that "this.length <= MAX_UINT32" since it's a read-only
// property of a typed array.
// This behaves neither like String nor Uint8Array in that we set start/end
// to their upper/lower bounds if the value passed is out of range.
// undefined is handled specially as per ECMA-262 6th Edition,
// Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
if (start === undefined || start < 0) {
start = 0
}
// Return early if start > this.length. Done here to prevent potential uint32
// coercion fail below.
if (start > this.length) {
return ''
}
if (end === undefined || end > this.length) {
end = this.length
}
if (end <= 0) {
return ''
}
// Force coersion to uint32. This will also coerce falsey/NaN values to 0.
end >>>= 0
start >>>= 0
if (end <= start) {
return ''
}
if (!encoding) encoding = 'utf8'
while (true) {
switch (encoding) {
case 'hex':
return hexSlice(this, start, end)
case 'utf8':
case 'utf-8':
return utf8Slice(this, start, end)
case 'ascii':
return asciiSlice(this, start, end)
case 'latin1':
case 'binary':
return latin1Slice(this, start, end)
case 'base64':
return base64Slice(this, start, end)
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return utf16leSlice(this, start, end)
default:
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
encoding = (encoding + '').toLowerCase()
loweredCase = true
}
}
}
// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
// to detect a Buffer instance. It's not possible to use `instanceof Buffer`
// reliably in a browserify context because there could be multiple different
// copies of the 'buffer' package in use. This method works even for Buffer
// instances that were created from another copy of the `buffer` package.
// See: https://github.com/feross/buffer/issues/154
Buffer.prototype._isBuffer = true
function swap (b, n, m) {
var i = b[n]
b[n] = b[m]
b[m] = i
}
Buffer.prototype.swap16 = function swap16 () {
var len = this.length
if (len % 2 !== 0) {
throw new RangeError('Buffer size must be a multiple of 16-bits')
}
for (var i = 0; i < len; i += 2) {
swap(this, i, i + 1)
}
return this
}
Buffer.prototype.swap32 = function swap32 () {
var len = this.length
if (len % 4 !== 0) {
throw new RangeError('Buffer size must be a multiple of 32-bits')
}
for (var i = 0; i < len; i += 4) {
swap(this, i, i + 3)
swap(this, i + 1, i + 2)
}
return this
}
Buffer.prototype.swap64 = function swap64 () {
var len = this.length
if (len % 8 !== 0) {
throw new RangeError('Buffer size must be a multiple of 64-bits')
}
for (var i = 0; i < len; i += 8) {
swap(this, i, i + 7)
swap(this, i + 1, i + 6)
swap(this, i + 2, i + 5)
swap(this, i + 3, i + 4)
}
return this
}
Buffer.prototype.toString = function toString () {
var length = this.length
if (length === 0) return ''
if (arguments.length === 0) return utf8Slice(this, 0, length)
return slowToString.apply(this, arguments)
}
Buffer.prototype.equals = function equals (b) {
if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
if (this === b) return true
return Buffer.compare(this, b) === 0
}
Buffer.prototype.inspect = function inspect () {
var str = ''
var max = exports.INSPECT_MAX_BYTES
if (this.length > 0) {
str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
if (this.length > max) str += ' ... '
}
return '<Buffer ' + str + '>'
}
Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
if (!Buffer.isBuffer(target)) {
throw new TypeError('Argument must be a Buffer')
}
if (start === undefined) {
start = 0
}
if (end === undefined) {
end = target ? target.length : 0
}
if (thisStart === undefined) {
thisStart = 0
}
if (thisEnd === undefined) {
thisEnd = this.length
}
if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
throw new RangeError('out of range index')
}
if (thisStart >= thisEnd && start >= end) {
return 0
}
if (thisStart >= thisEnd) {
return -1
}
if (start >= end) {
return 1
}
start >>>= 0
end >>>= 0
thisStart >>>= 0
thisEnd >>>= 0
if (this === target) return 0
var x = thisEnd - thisStart
var y = end - start
var len = Math.min(x, y)
var thisCopy = this.slice(thisStart, thisEnd)
var targetCopy = target.slice(start, end)
for (var i = 0; i < len; ++i) {
if (thisCopy[i] !== targetCopy[i]) {
x = thisCopy[i]
y = targetCopy[i]
break
}
}
if (x < y) return -1
if (y < x) return 1
return 0
}
// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
//
// Arguments:
// - buffer - a Buffer to search
// - val - a string, Buffer, or number
// - byteOffset - an index into `buffer`; will be clamped to an int32
// - encoding - an optional encoding, relevant is val is a string
// - dir - true for indexOf, false for lastIndexOf
function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
// Empty buffer means no match
if (buffer.length === 0) return -1
// Normalize byteOffset
if (typeof byteOffset === 'string') {
encoding = byteOffset
byteOffset = 0
} else if (byteOffset > 0x7fffffff) {
byteOffset = 0x7fffffff
} else if (byteOffset < -0x80000000) {
byteOffset = -0x80000000
}
byteOffset = +byteOffset // Coerce to Number.
if (numberIsNaN(byteOffset)) {
// byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
byteOffset = dir ? 0 : (buffer.length - 1)
}
// Normalize byteOffset: negative offsets start from the end of the buffer
if (byteOffset < 0) byteOffset = buffer.length + byteOffset
if (byteOffset >= buffer.length) {
if (dir) return -1
else byteOffset = buffer.length - 1
} else if (byteOffset < 0) {
if (dir) byteOffset = 0
else return -1
}
// Normalize val
if (typeof val === 'string') {
val = Buffer.from(val, encoding)
}
// Finally, search either indexOf (if dir is true) or lastIndexOf
if (Buffer.isBuffer(val)) {
// Special case: looking for empty string/buffer always fails
if (val.length === 0) {
return -1
}
return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
} else if (typeof val === 'number') {
val = val & 0xFF // Search for a byte value [0-255]
if (typeof Uint8Array.prototype.indexOf === 'function') {
if (dir) {
return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
} else {
return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
}
}
return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
}
throw new TypeError('val must be string, number or Buffer')
}
function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
var indexSize = 1
var arrLength = arr.length
var valLength = val.length
if (encoding !== undefined) {
encoding = String(encoding).toLowerCase()
if (encoding === 'ucs2' || encoding === 'ucs-2' ||
encoding === 'utf16le' || encoding === 'utf-16le') {
if (arr.length < 2 || val.length < 2) {
return -1
}
indexSize = 2
arrLength /= 2
valLength /= 2
byteOffset /= 2
}
}
function read (buf, i) {
if (indexSize === 1) {
return buf[i]
} else {
return buf.readUInt16BE(i * indexSize)
}
}
var i
if (dir) {
var foundIndex = -1
for (i = byteOffset; i < arrLength; i++) {
if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
if (foundIndex === -1) foundIndex = i
if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
} else {
if (foundIndex !== -1) i -= i - foundIndex
foundIndex = -1
}
}
} else {
if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
for (i = byteOffset; i >= 0; i--) {
var found = true
for (var j = 0; j < valLength; j++) {
if (read(arr, i + j) !== read(val, j)) {
found = false
break
}
}
if (found) return i
}
}
return -1
}
Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
return this.indexOf(val, byteOffset, encoding) !== -1
}
Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
}
Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
}
function hexWrite (buf, string, offset, length) {
offset = Number(offset) || 0
var remaining = buf.length - offset
if (!length) {
length = remaining
} else {
length = Number(length)
if (length > remaining) {
length = remaining
}
}
// must be an even number of digits
var strLen = string.length
if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
if (length > strLen / 2) {
length = strLen / 2
}
for (var i = 0; i < length; ++i) {
var parsed = parseInt(string.substr(i * 2, 2), 16)
if (numberIsNaN(parsed)) return i
buf[offset + i] = parsed
}
return i
}
function utf8Write (buf, string, offset, length) {
return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
}
function asciiWrite (buf, string, offset, length) {
return blitBuffer(asciiToBytes(string), buf, offset, length)
}
function latin1Write (buf, string, offset, length) {
return asciiWrite(buf, string, offset, length)
}
function base64Write (buf, string, offset, length) {
return blitBuffer(base64ToBytes(string), buf, offset, length)
}
function ucs2Write (buf, string, offset, length) {
return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
}
Buffer.prototype.write = function write (string, offset, length, encoding) {
// Buffer#write(string)
if (offset === undefined) {
encoding = 'utf8'
length = this.length
offset = 0
// Buffer#write(string, encoding)
} else if (length === undefined && typeof offset === 'string') {
encoding = offset
length = this.length
offset = 0
// Buffer#write(string, offset[, length][, encoding])
} else if (isFinite(offset)) {
offset = offset >>> 0
if (isFinite(length)) {
length = length >>> 0
if (encoding === undefined) encoding = 'utf8'
} else {
encoding = length
length = undefined
}
} else {
throw new Error(
'Buffer.write(string, encoding, offset[, length]) is no longer supported'
)
}
var remaining = this.length - offset
if (length === undefined || length > remaining) length = remaining
if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
throw new RangeError('Attempt to write outside buffer bounds')
}
if (!encoding) encoding = 'utf8'
var loweredCase = false
for (;;) {
switch (encoding) {
case 'hex':
return hexWrite(this, string, offset, length)
case 'utf8':
case 'utf-8':
return utf8Write(this, string, offset, length)
case 'ascii':
return asciiWrite(this, string, offset, length)
case 'latin1':
case 'binary':
return latin1Write(this, string, offset, length)
case 'base64':
// Warning: maxLength not taken into account in base64Write
return base64Write(this, string, offset, length)
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return ucs2Write(this, string, offset, length)
default:
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
encoding = ('' + encoding).toLowerCase()
loweredCase = true
}
}
}
Buffer.prototype.toJSON = function toJSON () {
return {
type: 'Buffer',
data: Array.prototype.slice.call(this._arr || this, 0)
}
}
function base64Slice (buf, start, end) {
if (start === 0 && end === buf.length) {
return base64.fromByteArray(buf)
} else {
return base64.fromByteArray(buf.slice(start, end))
}
}
function utf8Slice (buf, start, end) {
end = Math.min(buf.length, end)
var res = []
var i = start
while (i < end) {
var firstByte = buf[i]
var codePoint = null
var bytesPerSequence = (firstByte > 0xEF) ? 4
: (firstByte > 0xDF) ? 3
: (firstByte > 0xBF) ? 2
: 1
if (i + bytesPerSequence <= end) {
var secondByte, thirdByte, fourthByte, tempCodePoint
switch (bytesPerSequence) {
case 1:
if (firstByte < 0x80) {
codePoint = firstByte
}
break
case 2:
secondByte = buf[i + 1]
if ((secondByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
if (tempCodePoint > 0x7F) {
codePoint = tempCodePoint
}
}
break
case 3:
secondByte = buf[i + 1]
thirdByte = buf[i + 2]
if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
codePoint = tempCodePoint
}
}
break
case 4:
secondByte = buf[i + 1]
thirdByte = buf[i + 2]
fourthByte = buf[i + 3]
if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
codePoint = tempCodePoint
}
}
}
}
if (codePoint === null) {
// we did not generate a valid codePoint so insert a
// replacement char (U+FFFD) and advance only 1 byte
codePoint = 0xFFFD
bytesPerSequence = 1
} else if (codePoint > 0xFFFF) {
// encode to utf16 (surrogate pair dance)
codePoint -= 0x10000
res.push(codePoint >>> 10 & 0x3FF | 0xD800)
codePoint = 0xDC00 | codePoint & 0x3FF
}
res.push(codePoint)
i += bytesPerSequence
}
return decodeCodePointsArray(res)
}
// Based on http://stackoverflow.com/a/22747272/680742, the browser with
// the lowest limit is Chrome, with 0x10000 args.
// We go 1 magnitude less, for safety
var MAX_ARGUMENTS_LENGTH = 0x1000
function decodeCodePointsArray (codePoints) {
var len = codePoints.length
if (len <= MAX_ARGUMENTS_LENGTH) {
return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
}
// Decode in chunks to avoid "call stack size exceeded".
var res = ''
var i = 0
while (i < len) {
res += String.fromCharCode.apply(
String,
codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
)
}
return res
}
function asciiSlice (buf, start, end) {
var ret = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; ++i) {
ret += String.fromCharCode(buf[i] & 0x7F)
}
return ret
}
function latin1Slice (buf, start, end) {
var ret = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; ++i) {
ret += String.fromCharCode(buf[i])
}
return ret
}
function hexSlice (buf, start, end) {
var len = buf.length
if (!start || start < 0) start = 0
if (!end || end < 0 || end > len) end = len
var out = ''
for (var i = start; i < end; ++i) {
out += toHex(buf[i])
}
return out
}
function utf16leSlice (buf, start, end) {
var bytes = buf.slice(start, end)
var res = ''
for (var i = 0; i < bytes.length; i += 2) {
res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
}
return res
}
Buffer.prototype.slice = function slice (start, end) {
var len = this.length
start = ~~start
end = end === undefined ? len : ~~end
if (start < 0) {
start += len
if (start < 0) start = 0
} else if (start > len) {
start = len
}
if (end < 0) {
end += len
if (end < 0) end = 0
} else if (end > len) {
end = len
}
if (end < start) end = start
var newBuf = this.subarray(start, end)
// Return an augmented `Uint8Array` instance
newBuf.__proto__ = Buffer.prototype
return newBuf
}
/*
* Need to make sure that buffer isn't trying to write out of bounds.
*/
function checkOffset (offset, ext, length) {
if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
}
Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var val = this[offset]
var mul = 1
var i = 0
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul
}
return val
}
Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) {
checkOffset(offset, byteLength, this.length)
}
var val = this[offset + --byteLength]
var mul = 1
while (byteLength > 0 && (mul *= 0x100)) {
val += this[offset + --byteLength] * mul
}
return val
}
Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 1, this.length)
return this[offset]
}
Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 2, this.length)
return this[offset] | (this[offset + 1] << 8)
}
Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 2, this.length)
return (this[offset] << 8) | this[offset + 1]
}
Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return ((this[offset]) |
(this[offset + 1] << 8) |
(this[offset + 2] << 16)) +
(this[offset + 3] * 0x1000000)
}
Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset] * 0x1000000) +
((this[offset + 1] << 16) |
(this[offset + 2] << 8) |
this[offset + 3])
}
Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var val = this[offset]
var mul = 1
var i = 0
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul
}
mul *= 0x80
if (val >= mul) val -= Math.pow(2, 8 * byteLength)
return val
}
Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var i = byteLength
var mul = 1
var val = this[offset + --i]
while (i > 0 && (mul *= 0x100)) {
val += this[offset + --i] * mul
}
mul *= 0x80
if (val >= mul) val -= Math.pow(2, 8 * byteLength)
return val
}
Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 1, this.length)
if (!(this[offset] & 0x80)) return (this[offset])
return ((0xff - this[offset] + 1) * -1)
}
Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 2, this.length)
var val = this[offset] | (this[offset + 1] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
}
Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 2, this.length)
var val = this[offset + 1] | (this[offset] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
}
Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset]) |
(this[offset + 1] << 8) |
(this[offset + 2] << 16) |
(this[offset + 3] << 24)
}
Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset] << 24) |
(this[offset + 1] << 16) |
(this[offset + 2] << 8) |
(this[offset + 3])
}
Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, true, 23, 4)
}
Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, false, 23, 4)
}
Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, true, 52, 8)
}
Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
offset = offset >>> 0
if (!noAssert) checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, false, 52, 8)
}
function checkInt (buf, value, offset, ext, max, min) {
if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
if (offset + ext > buf.length) throw new RangeError('Index out of range')
}
Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) {
var maxBytes = Math.pow(2, 8 * byteLength) - 1
checkInt(this, value, offset, byteLength, maxBytes, 0)
}
var mul = 1
var i = 0
this[offset] = value & 0xFF
while (++i < byteLength && (mul *= 0x100)) {
this[offset + i] = (value / mul) & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
byteLength = byteLength >>> 0
if (!noAssert) {
var maxBytes = Math.pow(2, 8 * byteLength) - 1
checkInt(this, value, offset, byteLength, maxBytes, 0)
}
var i = byteLength - 1
var mul = 1
this[offset + i] = value & 0xFF
while (--i >= 0 && (mul *= 0x100)) {
this[offset + i] = (value / mul) & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
this[offset] = (value & 0xff)
return offset + 1
}
Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
return offset + 2
}
Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
this[offset] = (value >>> 8)
this[offset + 1] = (value & 0xff)
return offset + 2
}
Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
this[offset + 3] = (value >>> 24)
this[offset + 2] = (value >>> 16)
this[offset + 1] = (value >>> 8)
this[offset] = (value & 0xff)
return offset + 4
}
Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = (value & 0xff)
return offset + 4
}
Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) {
var limit = Math.pow(2, (8 * byteLength) - 1)
checkInt(this, value, offset, byteLength, limit - 1, -limit)
}
var i = 0
var mul = 1
var sub = 0
this[offset] = value & 0xFF
while (++i < byteLength && (mul *= 0x100)) {
if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
sub = 1
}
this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) {
var limit = Math.pow(2, (8 * byteLength) - 1)
checkInt(this, value, offset, byteLength, limit - 1, -limit)
}
var i = byteLength - 1
var mul = 1
var sub = 0
this[offset + i] = value & 0xFF
while (--i >= 0 && (mul *= 0x100)) {
if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
sub = 1
}
this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
if (value < 0) value = 0xff + value + 1
this[offset] = (value & 0xff)
return offset + 1
}
Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
return offset + 2
}
Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
this[offset] = (value >>> 8)
this[offset + 1] = (value & 0xff)
return offset + 2
}
Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
this[offset + 2] = (value >>> 16)
this[offset + 3] = (value >>> 24)
return offset + 4
}
Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
if (value < 0) value = 0xffffffff + value + 1
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = (value & 0xff)
return offset + 4
}
function checkIEEE754 (buf, value, offset, ext, max, min) {
if (offset + ext > buf.length) throw new RangeError('Index out of range')
if (offset < 0) throw new RangeError('Index out of range')
}
function writeFloat (buf, value, offset, littleEndian, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) {
checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
}
ieee754.write(buf, value, offset, littleEndian, 23, 4)
return offset + 4
}
Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
return writeFloat(this, value, offset, true, noAssert)
}
Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
return writeFloat(this, value, offset, false, noAssert)
}
function writeDouble (buf, value, offset, littleEndian, noAssert) {
value = +value
offset = offset >>> 0
if (!noAssert) {
checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
}
ieee754.write(buf, value, offset, littleEndian, 52, 8)
return offset + 8
}
Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
return writeDouble(this, value, offset, true, noAssert)
}
Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
return writeDouble(this, value, offset, false, noAssert)
}
// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
Buffer.prototype.copy = function copy (target, targetStart, start, end) {
if (!start) start = 0
if (!end && end !== 0) end = this.length
if (targetStart >= target.length) targetStart = target.length
if (!targetStart) targetStart = 0
if (end > 0 && end < start) end = start
// Copy 0 bytes; we're done
if (end === start) return 0
if (target.length === 0 || this.length === 0) return 0
// Fatal error conditions
if (targetStart < 0) {
throw new RangeError('targetStart out of bounds')
}
if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
if (end < 0) throw new RangeError('sourceEnd out of bounds')
// Are we oob?
if (end > this.length) end = this.length
if (target.length - targetStart < end - start) {
end = target.length - targetStart + start
}
var len = end - start
var i
if (this === target && start < targetStart && targetStart < end) {
// descending copy from end
for (i = len - 1; i >= 0; --i) {
target[i + targetStart] = this[i + start]
}
} else if (len < 1000) {
// ascending copy from start
for (i = 0; i < len; ++i) {
target[i + targetStart] = this[i + start]
}
} else {
Uint8Array.prototype.set.call(
target,
this.subarray(start, start + len),
targetStart
)
}
return len
}
// Usage:
// buffer.fill(number[, offset[, end]])
// buffer.fill(buffer[, offset[, end]])
// buffer.fill(string[, offset[, end]][, encoding])
Buffer.prototype.fill = function fill (val, start, end, encoding) {
// Handle string cases:
if (typeof val === 'string') {
if (typeof start === 'string') {
encoding = start
start = 0
end = this.length
} else if (typeof end === 'string') {
encoding = end
end = this.length
}
if (val.length === 1) {
var code = val.charCodeAt(0)
if (code < 256) {
val = code
}
}
if (encoding !== undefined && typeof encoding !== 'string') {
throw new TypeError('encoding must be a string')
}
if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
throw new TypeError('Unknown encoding: ' + encoding)
}
} else if (typeof val === 'number') {
val = val & 255
}
// Invalid ranges are not set to a default, so can range check early.
if (start < 0 || this.length < start || this.length < end) {
throw new RangeError('Out of range index')
}
if (end <= start) {
return this
}
start = start >>> 0
end = end === undefined ? this.length : end >>> 0
if (!val) val = 0
var i
if (typeof val === 'number') {
for (i = start; i < end; ++i) {
this[i] = val
}
} else {
var bytes = Buffer.isBuffer(val)
? val
: new Buffer(val, encoding)
var len = bytes.length
for (i = 0; i < end - start; ++i) {
this[i + start] = bytes[i % len]
}
}
return this
}
// HELPER FUNCTIONS
// ================
var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
function base64clean (str) {
// Node strips out invalid characters like \n and \t from the string, base64-js does not
str = str.trim().replace(INVALID_BASE64_RE, '')
// Node converts strings with length < 2 to ''
if (str.length < 2) return ''
// Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
while (str.length % 4 !== 0) {
str = str + '='
}
return str
}
function toHex (n) {
if (n < 16) return '0' + n.toString(16)
return n.toString(16)
}
function utf8ToBytes (string, units) {
units = units || Infinity
var codePoint
var length = string.length
var leadSurrogate = null
var bytes = []
for (var i = 0; i < length; ++i) {
codePoint = string.charCodeAt(i)
// is surrogate component
if (codePoint > 0xD7FF && codePoint < 0xE000) {
// last char was a lead
if (!leadSurrogate) {
// no lead yet
if (codePoint > 0xDBFF) {
// unexpected trail
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
continue
} else if (i + 1 === length) {
// unpaired lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
continue
}
// valid lead
leadSurrogate = codePoint
continue
}
// 2 leads in a row
if (codePoint < 0xDC00) {
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
leadSurrogate = codePoint
continue
}
// valid surrogate pair
codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
} else if (leadSurrogate) {
// valid bmp char, but last char was a lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
}
leadSurrogate = null
// encode utf8
if (codePoint < 0x80) {
if ((units -= 1) < 0) break
bytes.push(codePoint)
} else if (codePoint < 0x800) {
if ((units -= 2) < 0) break
bytes.push(
codePoint >> 0x6 | 0xC0,
codePoint & 0x3F | 0x80
)
} else if (codePoint < 0x10000) {
if ((units -= 3) < 0) break
bytes.push(
codePoint >> 0xC | 0xE0,
codePoint >> 0x6 & 0x3F | 0x80,
codePoint & 0x3F | 0x80
)
} else if (codePoint < 0x110000) {
if ((units -= 4) < 0) break
bytes.push(
codePoint >> 0x12 | 0xF0,
codePoint >> 0xC & 0x3F | 0x80,
codePoint >> 0x6 & 0x3F | 0x80,
codePoint & 0x3F | 0x80
)
} else {
throw new Error('Invalid code point')
}
}
return bytes
}
function asciiToBytes (str) {
var byteArray = []
for (var i = 0; i < str.length; ++i) {
// Node's code seems to be doing this and not & 0x7F..
byteArray.push(str.charCodeAt(i) & 0xFF)
}
return byteArray
}
function utf16leToBytes (str, units) {
var c, hi, lo
var byteArray = []
for (var i = 0; i < str.length; ++i) {
if ((units -= 2) < 0) break
c = str.charCodeAt(i)
hi = c >> 8
lo = c % 256
byteArray.push(lo)
byteArray.push(hi)
}
return byteArray
}
function base64ToBytes (str) {
return base64.toByteArray(base64clean(str))
}
function blitBuffer (src, dst, offset, length) {
for (var i = 0; i < length; ++i) {
if ((i + offset >= dst.length) || (i >= src.length)) break
dst[i + offset] = src[i]
}
return i
}
// Node 0.10 supports `ArrayBuffer` but lacks `ArrayBuffer.isView`
function isArrayBufferView (obj) {
return (typeof ArrayBuffer.isView === 'function') && ArrayBuffer.isView(obj)
}
function numberIsNaN (obj) {
return obj !== obj // eslint-disable-line no-self-compare
}
},{"27":27,"38":38}],29:[function(require,module,exports){
/**
* @author Markus Ekholm
* @copyright 2012-2015 (c) Markus Ekholm <markus at botten dot org >
* @license Copyright (c) 2012-2015, Markus Ekholm
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the <organization> nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL MARKUS EKHOLM BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* EXPORTS
*/
exports.rgb_to_lab = rgb_to_lab;
/**
* IMPORTS
*/
var pow = Math.pow;
var sqrt = Math.sqrt;
/**
* API FUNCTIONS
*/
/**
* Returns c converted to labcolor.
* @param {rgbcolor} c should have fields R,G,B
* @return {labcolor} c converted to labcolor
*/
function rgb_to_lab(c)
{
return xyz_to_lab(rgb_to_xyz(c))
}
/**
* Returns c converted to xyzcolor.
* @param {rgbcolor} c should have fields R,G,B
* @return {xyzcolor} c converted to xyzcolor
*/
function rgb_to_xyz(c)
{
// Based on http://www.easyrgb.com/index.php?X=MATH&H=02
var R = ( c.R / 255 );
var G = ( c.G / 255 );
var B = ( c.B / 255 );
if ( R > 0.04045 ) R = pow(( ( R + 0.055 ) / 1.055 ),2.4);
else R = R / 12.92;
if ( G > 0.04045 ) G = pow(( ( G + 0.055 ) / 1.055 ),2.4);
else G = G / 12.92;
if ( B > 0.04045 ) B = pow(( ( B + 0.055 ) / 1.055 ), 2.4);
else B = B / 12.92;
R *= 100;
G *= 100;
B *= 100;
// Observer. = 2°, Illuminant = D65
var X = R * 0.4124 + G * 0.3576 + B * 0.1805;
var Y = R * 0.2126 + G * 0.7152 + B * 0.0722;
var Z = R * 0.0193 + G * 0.1192 + B * 0.9505;
return {'X' : X, 'Y' : Y, 'Z' : Z};
}
/**
* Returns c converted to labcolor.
* @param {xyzcolor} c should have fields X,Y,Z
* @return {labcolor} c converted to labcolor
*/
function xyz_to_lab(c)
{
// Based on http://www.easyrgb.com/index.php?X=MATH&H=07
var ref_Y = 100.000;
var ref_Z = 108.883;
var ref_X = 95.047; // Observer= 2°, Illuminant= D65
var Y = c.Y / ref_Y;
var Z = c.Z / ref_Z;
var X = c.X / ref_X;
if ( X > 0.008856 ) X = pow(X, 1/3);
else X = ( 7.787 * X ) + ( 16 / 116 );
if ( Y > 0.008856 ) Y = pow(Y, 1/3);
else Y = ( 7.787 * Y ) + ( 16 / 116 );
if ( Z > 0.008856 ) Z = pow(Z, 1/3);
else Z = ( 7.787 * Z ) + ( 16 / 116 );
var L = ( 116 * Y ) - 16;
var a = 500 * ( X - Y );
var b = 200 * ( Y - Z );
return {'L' : L , 'a' : a, 'b' : b};
}
// Local Variables:
// allout-layout: t
// js-indent-level: 2
// End:
},{}],30:[function(require,module,exports){
/**
* @author Markus Ekholm
* @copyright 2012-2015 (c) Markus Ekholm <markus at botten dot org >
* @license Copyright (c) 2012-2015, Markus Ekholm
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the <organization> nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL MARKUS EKHOLM BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* EXPORTS
*/
exports.ciede2000 = ciede2000;
/**
* IMPORTS
*/
var sqrt = Math.sqrt;
var pow = Math.pow;
var cos = Math.cos;
var atan2 = Math.atan2;
var sin = Math.sin;
var abs = Math.abs;
var exp = Math.exp;
var PI = Math.PI;
/**
* API FUNCTIONS
*/
/**
* Returns diff between c1 and c2 using the CIEDE2000 algorithm
* @param {labcolor} c1 Should have fields L,a,b
* @param {labcolor} c2 Should have fields L,a,b
* @return {float} Difference between c1 and c2
*/
function ciede2000(c1,c2)
{
/**
* Implemented as in "The CIEDE2000 Color-Difference Formula:
* Implementation Notes, Supplementary Test Data, and Mathematical Observations"
* by Gaurav Sharma, Wencheng Wu and Edul N. Dalal.
*/
// Get L,a,b values for color 1
var L1 = c1.L;
var a1 = c1.a;
var b1 = c1.b;
// Get L,a,b values for color 2
var L2 = c2.L;
var a2 = c2.a;
var b2 = c2.b;
// Weight factors
var kL = 1;
var kC = 1;
var kH = 1;
/**
* Step 1: Calculate C1p, C2p, h1p, h2p
*/
var C1 = sqrt(pow(a1, 2) + pow(b1, 2)) //(2)
var C2 = sqrt(pow(a2, 2) + pow(b2, 2)) //(2)
var a_C1_C2 = (C1+C2)/2.0; //(3)
var G = 0.5 * (1 - sqrt(pow(a_C1_C2 , 7.0) /
(pow(a_C1_C2, 7.0) + pow(25.0, 7.0)))); //(4)
var a1p = (1.0 + G) * a1; //(5)
var a2p = (1.0 + G) * a2; //(5)
var C1p = sqrt(pow(a1p, 2) + pow(b1, 2)); //(6)
var C2p = sqrt(pow(a2p, 2) + pow(b2, 2)); //(6)
var hp_f = function(x,y) //(7)
{
if(x== 0 && y == 0) return 0;
else{
var tmphp = degrees(atan2(x,y));
if(tmphp >= 0) return tmphp
else return tmphp + 360;
}
}
var h1p = hp_f(b1, a1p); //(7)
var h2p = hp_f(b2, a2p); //(7)
/**
* Step 2: Calculate dLp, dCp, dHp
*/
var dLp = L2 - L1; //(8)
var dCp = C2p - C1p; //(9)
var dhp_f = function(C1, C2, h1p, h2p) //(10)
{
if(C1*C2 == 0) return 0;
else if(abs(h2p-h1p) <= 180) return h2p-h1p;
else if((h2p-h1p) > 180) return (h2p-h1p)-360;
else if((h2p-h1p) < -180) return (h2p-h1p)+360;
else throw(new Error());
}
var dhp = dhp_f(C1,C2, h1p, h2p); //(10)
var dHp = 2*sqrt(C1p*C2p)*sin(radians(dhp)/2.0); //(11)
/**
* Step 3: Calculate CIEDE2000 Color-Difference
*/
var a_L = (L1 + L2) / 2.0; //(12)
var a_Cp = (C1p + C2p) / 2.0; //(13)
var a_hp_f = function(C1, C2, h1p, h2p) { //(14)
if(C1*C2 == 0) return h1p+h2p
else if(abs(h1p-h2p)<= 180) return (h1p+h2p)/2.0;
else if((abs(h1p-h2p) > 180) && ((h1p+h2p) < 360)) return (h1p+h2p+360)/2.0;
else if((abs(h1p-h2p) > 180) && ((h1p+h2p) >= 360)) return (h1p+h2p-360)/2.0;
else throw(new Error());
}
var a_hp = a_hp_f(C1,C2,h1p,h2p); //(14)
var T = 1-0.17*cos(radians(a_hp-30))+0.24*cos(radians(2*a_hp))+
0.32*cos(radians(3*a_hp+6))-0.20*cos(radians(4*a_hp-63)); //(15)
var d_ro = 30 * exp(-(pow((a_hp-275)/25,2))); //(16)
var RC = sqrt((pow(a_Cp, 7.0)) / (pow(a_Cp, 7.0) + pow(25.0, 7.0)));//(17)
var SL = 1 + ((0.015 * pow(a_L - 50, 2)) /
sqrt(20 + pow(a_L - 50, 2.0)));//(18)
var SC = 1 + 0.045 * a_Cp;//(19)
var SH = 1 + 0.015 * a_Cp * T;//(20)
var RT = -2 * RC * sin(radians(2 * d_ro));//(21)
var dE = sqrt(pow(dLp /(SL * kL), 2) + pow(dCp /(SC * kC), 2) +
pow(dHp /(SH * kH), 2) + RT * (dCp /(SC * kC)) *
(dHp / (SH * kH))); //(22)
return dE;
}
/**
* INTERNAL FUNCTIONS
*/
function degrees(n) { return n*(180/PI); }
function radians(n) { return n*(PI/180); }
// Local Variables:
// allout-layout: t
// js-indent-level: 2
// End:
},{}],31:[function(require,module,exports){
'use strict';
var diff = require(30);
var convert = require(29);
var palette = require(32);
var color = module.exports = {};
color.diff = diff.ciede2000;
color.rgb_to_lab = convert.rgb_to_lab;
color.map_palette = palette.map_palette;
color.palette_map_key = palette.palette_map_key;
color.closest = function(target, relative) {
var key = color.palette_map_key(target);
var result = color.map_palette([target], relative, 'closest');
return result[key];
};
color.furthest = function(target, relative) {
var key = color.palette_map_key(target);
var result = color.map_palette([target], relative, 'furthest');
return result[key];
};
},{"29":29,"30":30,"32":32}],32:[function(require,module,exports){
/**
* @author Markus Ekholm
* @copyright 2012-2015 (c) Markus Ekholm <markus at botten dot org >
* @license Copyright (c) 2012-2015, Markus Ekholm
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the <organization> nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL MARKUS EKHOLM BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* EXPORTS
*/
exports.map_palette = map_palette;
exports.palette_map_key = palette_map_key;
/**
* IMPORTS
*/
var color_diff = require(30);
var color_convert = require(29);
/**
* API FUNCTIONS
*/
/**
* Returns the hash key used for a {rgbcolor} in a {palettemap}
* @param {rgbcolor} c should have fields R,G,B
* @return {string}
*/
function palette_map_key(c)
{
return "R" + c.R + "B" + c.B + "G" + c.G;
}
/**
* Returns a mapping from each color in a to the closest color in b
* @param [{rgbcolor}] a each element should have fields R,G,B
* @param [{rgbcolor}] b each element should have fields R,G,B
* @param 'type' should be the string 'closest' or 'furthest'
* @return {palettemap}
*/
function map_palette(a, b, type)
{
var c = {};
type = type || 'closest';
for (var idx1 = 0; idx1 < a.length; idx1 += 1){
var color1 = a[idx1];
var best_color = undefined;
var best_color_diff = undefined;
for (var idx2 = 0; idx2 < b.length; idx2 += 1)
{
var color2 = b[idx2];
var current_color_diff = diff(color1,color2);
if((best_color == undefined) || ((type === 'closest') && (current_color_diff < best_color_diff)))
{
best_color = color2;
best_color_diff = current_color_diff;
continue;
}
if((type === 'furthest') && (current_color_diff > best_color_diff))
{
best_color = color2;
best_color_diff = current_color_diff;
continue;
}
}
c[palette_map_key(color1)] = best_color;
}
return c;
}
/**
* INTERNAL FUNCTIONS
*/
function diff(c1,c2)
{
c1 = color_convert.rgb_to_lab(c1);
c2 = color_convert.rgb_to_lab(c2);
return color_diff.ciede2000(c1,c2);
}
// Local Variables:
// allout-layout: t
// js-indent-level: 2
// End:
},{"29":29,"30":30}],33:[function(require,module,exports){
'use strict';
var repeating = require(54);
// detect either spaces or tabs but not both to properly handle tabs
// for indentation and spaces for alignment
var INDENT_RE = /^(?:( )+|\t+)/;
function getMostUsed(indents) {
var result = 0;
var maxUsed = 0;
var maxWeight = 0;
for (var n in indents) {
var indent = indents[n];
var u = indent[0];
var w = indent[1];
if (u > maxUsed || u === maxUsed && w > maxWeight) {
maxUsed = u;
maxWeight = w;
result = +n;
}
}
return result;
}
module.exports = function (str) {
if (typeof str !== 'string') {
throw new TypeError('Expected a string');
}
// used to see if tabs or spaces are the most used
var tabs = 0;
var spaces = 0;
// remember the size of previous line's indentation
var prev = 0;
// remember how many indents/unindents as occurred for a given size
// and how much lines follow a given indentation
//
// indents = {
// 3: [1, 0],
// 4: [1, 5],
// 5: [1, 0],
// 12: [1, 0],
// }
var indents = {};
// pointer to the array of last used indent
var current;
// whether the last action was an indent (opposed to an unindent)
var isIndent;
str.split(/\n/g).forEach(function (line) {
if (!line) {
// ignore empty lines
return;
}
var indent;
var matches = line.match(INDENT_RE);
if (!matches) {
indent = 0;
} else {
indent = matches[0].length;
if (matches[1]) {
spaces++;
} else {
tabs++;
}
}
var diff = indent - prev;
prev = indent;
if (diff) {
// an indent or unindent has been detected
isIndent = diff > 0;
current = indents[isIndent ? diff : -diff];
if (current) {
current[0]++;
} else {
current = indents[diff] = [1, 0];
}
} else if (current) {
// if the last action was an indent, increment the weight
current[1] += +isIndent;
}
});
var amount = getMostUsed(indents);
var type;
var actual;
if (!amount) {
type = null;
actual = '';
} else if (spaces >= tabs) {
type = 'space';
actual = repeating(' ', amount);
} else {
type = 'tab';
actual = repeating('\t', amount);
}
return {
amount: amount,
type: type,
indent: actual
};
};
},{"54":54}],34:[function(require,module,exports){
/* See LICENSE file for terms of use */
/*
* Text diff implementation.
*
* This library supports the following APIS:
* JsDiff.diffChars: Character by character diff
* JsDiff.diffWords: Word (as defined by \b regex) diff which ignores whitespace
* JsDiff.diffLines: Line based diff
*
* JsDiff.diffCss: Diff targeted at CSS content
*
* These methods are based on the implementation proposed in
* "An O(ND) Difference Algorithm and its Variations" (Myers, 1986).
* http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.6927
*/
(function(global, undefined) {
var JsDiff = (function() {
/*jshint maxparams: 5*/
function map(arr, mapper, that) {
if (Array.prototype.map) {
return Array.prototype.map.call(arr, mapper, that);
}
var other = new Array(arr.length);
for (var i = 0, n = arr.length; i < n; i++) {
other[i] = mapper.call(that, arr[i], i, arr);
}
return other;
}
function clonePath(path) {
return { newPos: path.newPos, components: path.components.slice(0) };
}
function removeEmpty(array) {
var ret = [];
for (var i = 0; i < array.length; i++) {
if (array[i]) {
ret.push(array[i]);
}
}
return ret;
}
function escapeHTML(s) {
var n = s;
n = n.replace(/&/g, '&');
n = n.replace(/</g, '<');
n = n.replace(/>/g, '>');
n = n.replace(/"/g, '"');
return n;
}
var Diff = function(ignoreWhitespace) {
this.ignoreWhitespace = ignoreWhitespace;
};
Diff.prototype = {
diff: function(oldString, newString) {
// Handle the identity case (this is due to unrolling editLength == 0
if (newString === oldString) {
return [{ value: newString }];
}
if (!newString) {
return [{ value: oldString, removed: true }];
}
if (!oldString) {
return [{ value: newString, added: true }];
}
newString = this.tokenize(newString);
oldString = this.tokenize(oldString);
var newLen = newString.length, oldLen = oldString.length;
var maxEditLength = newLen + oldLen;
var bestPath = [{ newPos: -1, components: [] }];
// Seed editLength = 0
var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0);
if (bestPath[0].newPos+1 >= newLen && oldPos+1 >= oldLen) {
return bestPath[0].components;
}
for (var editLength = 1; editLength <= maxEditLength; editLength++) {
for (var diagonalPath = -1*editLength; diagonalPath <= editLength; diagonalPath+=2) {
var basePath;
var addPath = bestPath[diagonalPath-1],
removePath = bestPath[diagonalPath+1];
oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
if (addPath) {
// No one else is going to attempt to use this value, clear it
bestPath[diagonalPath-1] = undefined;
}
var canAdd = addPath && addPath.newPos+1 < newLen;
var canRemove = removePath && 0 <= oldPos && oldPos < oldLen;
if (!canAdd && !canRemove) {
bestPath[diagonalPath] = undefined;
continue;
}
// Select the diagonal that we want to branch from. We select the prior
// path whose position in the new string is the farthest from the origin
// and does not pass the bounds of the diff graph
if (!canAdd || (canRemove && addPath.newPos < removePath.newPos)) {
basePath = clonePath(removePath);
this.pushComponent(basePath.components, oldString[oldPos], undefined, true);
} else {
basePath = clonePath(addPath);
basePath.newPos++;
this.pushComponent(basePath.components, newString[basePath.newPos], true, undefined);
}
var oldPos = this.extractCommon(basePath, newString, oldString, diagonalPath);
if (basePath.newPos+1 >= newLen && oldPos+1 >= oldLen) {
return basePath.components;
} else {
bestPath[diagonalPath] = basePath;
}
}
}
},
pushComponent: function(components, value, added, removed) {
var last = components[components.length-1];
if (last && last.added === added && last.removed === removed) {
// We need to clone here as the component clone operation is just
// as shallow array clone
components[components.length-1] =
{value: this.join(last.value, value), added: added, removed: removed };
} else {
components.push({value: value, added: added, removed: removed });
}
},
extractCommon: function(basePath, newString, oldString, diagonalPath) {
var newLen = newString.length,
oldLen = oldString.length,
newPos = basePath.newPos,
oldPos = newPos - diagonalPath;
while (newPos+1 < newLen && oldPos+1 < oldLen && this.equals(newString[newPos+1], oldString[oldPos+1])) {
newPos++;
oldPos++;
this.pushComponent(basePath.components, newString[newPos], undefined, undefined);
}
basePath.newPos = newPos;
return oldPos;
},
equals: function(left, right) {
var reWhitespace = /\S/;
if (this.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right)) {
return true;
} else {
return left === right;
}
},
join: function(left, right) {
return left + right;
},
tokenize: function(value) {
return value;
}
};
var CharDiff = new Diff();
var WordDiff = new Diff(true);
var WordWithSpaceDiff = new Diff();
WordDiff.tokenize = WordWithSpaceDiff.tokenize = function(value) {
return removeEmpty(value.split(/(\s+|\b)/));
};
var CssDiff = new Diff(true);
CssDiff.tokenize = function(value) {
return removeEmpty(value.split(/([{}:;,]|\s+)/));
};
var LineDiff = new Diff();
LineDiff.tokenize = function(value) {
var retLines = [],
lines = value.split(/^/m);
for(var i = 0; i < lines.length; i++) {
var line = lines[i],
lastLine = lines[i - 1];
// Merge lines that may contain windows new lines
if (line == '\n' && lastLine && lastLine[lastLine.length - 1] === '\r') {
retLines[retLines.length - 1] += '\n';
} else if (line) {
retLines.push(line);
}
}
return retLines;
};
return {
Diff: Diff,
diffChars: function(oldStr, newStr) { return CharDiff.diff(oldStr, newStr); },
diffWords: function(oldStr, newStr) { return WordDiff.diff(oldStr, newStr); },
diffWordsWithSpace: function(oldStr, newStr) { return WordWithSpaceDiff.diff(oldStr, newStr); },
diffLines: function(oldStr, newStr) { return LineDiff.diff(oldStr, newStr); },
diffCss: function(oldStr, newStr) { return CssDiff.diff(oldStr, newStr); },
createPatch: function(fileName, oldStr, newStr, oldHeader, newHeader) {
var ret = [];
ret.push('Index: ' + fileName);
ret.push('===================================================================');
ret.push('--- ' + fileName + (typeof oldHeader === 'undefined' ? '' : '\t' + oldHeader));
ret.push('+++ ' + fileName + (typeof newHeader === 'undefined' ? '' : '\t' + newHeader));
var diff = LineDiff.diff(oldStr, newStr);
if (!diff[diff.length-1].value) {
diff.pop(); // Remove trailing newline add
}
diff.push({value: '', lines: []}); // Append an empty value to make cleanup easier
function contextLines(lines) {
return map(lines, function(entry) { return ' ' + entry; });
}
function eofNL(curRange, i, current) {
var last = diff[diff.length-2],
isLast = i === diff.length-2,
isLastOfType = i === diff.length-3 && (current.added !== last.added || current.removed !== last.removed);
// Figure out if this is the last line for the given file and missing NL
if (!/\n$/.test(current.value) && (isLast || isLastOfType)) {
curRange.push('\\ No newline at end of file');
}
}
var oldRangeStart = 0, newRangeStart = 0, curRange = [],
oldLine = 1, newLine = 1;
for (var i = 0; i < diff.length; i++) {
var current = diff[i],
lines = current.lines || current.value.replace(/\n$/, '').split('\n');
current.lines = lines;
if (current.added || current.removed) {
if (!oldRangeStart) {
var prev = diff[i-1];
oldRangeStart = oldLine;
newRangeStart = newLine;
if (prev) {
curRange = contextLines(prev.lines.slice(-4));
oldRangeStart -= curRange.length;
newRangeStart -= curRange.length;
}
}
curRange.push.apply(curRange, map(lines, function(entry) { return (current.added?'+':'-') + entry; }));
eofNL(curRange, i, current);
if (current.added) {
newLine += lines.length;
} else {
oldLine += lines.length;
}
} else {
if (oldRangeStart) {
// Close out any changes that have been output (or join overlapping)
if (lines.length <= 8 && i < diff.length-2) {
// Overlapping
curRange.push.apply(curRange, contextLines(lines));
} else {
// end the range and output
var contextSize = Math.min(lines.length, 4);
ret.push(
'@@ -' + oldRangeStart + ',' + (oldLine-oldRangeStart+contextSize)
+ ' +' + newRangeStart + ',' + (newLine-newRangeStart+contextSize)
+ ' @@');
ret.push.apply(ret, curRange);
ret.push.apply(ret, contextLines(lines.slice(0, contextSize)));
if (lines.length <= 4) {
eofNL(ret, i, current);
}
oldRangeStart = 0; newRangeStart = 0; curRange = [];
}
}
oldLine += lines.length;
newLine += lines.length;
}
}
return ret.join('\n') + '\n';
},
applyPatch: function(oldStr, uniDiff) {
var diffstr = uniDiff.split('\n');
var diff = [];
var remEOFNL = false,
addEOFNL = false;
for (var i = (diffstr[0][0]==='I'?4:0); i < diffstr.length; i++) {
if(diffstr[i][0] === '@') {
var meh = diffstr[i].split(/@@ -(\d+),(\d+) \+(\d+),(\d+) @@/);
diff.unshift({
start:meh[3],
oldlength:meh[2],
oldlines:[],
newlength:meh[4],
newlines:[]
});
} else if(diffstr[i][0] === '+') {
diff[0].newlines.push(diffstr[i].substr(1));
} else if(diffstr[i][0] === '-') {
diff[0].oldlines.push(diffstr[i].substr(1));
} else if(diffstr[i][0] === ' ') {
diff[0].newlines.push(diffstr[i].substr(1));
diff[0].oldlines.push(diffstr[i].substr(1));
} else if(diffstr[i][0] === '\\') {
if (diffstr[i-1][0] === '+') {
remEOFNL = true;
} else if(diffstr[i-1][0] === '-') {
addEOFNL = true;
}
}
}
var str = oldStr.split('\n');
for (var i = diff.length - 1; i >= 0; i--) {
var d = diff[i];
for (var j = 0; j < d.oldlength; j++) {
if(str[d.start-1+j] !== d.oldlines[j]) {
return false;
}
}
Array.prototype.splice.apply(str,[d.start-1,+d.oldlength].concat(d.newlines));
}
if (remEOFNL) {
while (!str[str.length-1]) {
str.pop();
}
} else if (addEOFNL) {
str.push('');
}
return str.join('\n');
},
convertChangesToXML: function(changes){
var ret = [];
for ( var i = 0; i < changes.length; i++) {
var change = changes[i];
if (change.added) {
ret.push('<ins>');
} else if (change.removed) {
ret.push('<del>');
}
ret.push(escapeHTML(change.value));
if (change.added) {
ret.push('</ins>');
} else if (change.removed) {
ret.push('</del>');
}
}
return ret.join('');
},
// See: http://code.google.com/p/google-diff-match-patch/wiki/API
convertChangesToDMP: function(changes){
var ret = [], change;
for ( var i = 0; i < changes.length; i++) {
change = changes[i];
ret.push([(change.added ? 1 : change.removed ? -1 : 0), change.value]);
}
return ret;
}
};
})();
if (typeof module !== 'undefined') {
module.exports = JsDiff;
}
else if (typeof define === 'function') {
define([], function() { return JsDiff; });
}
else if (typeof global.JsDiff === 'undefined') {
global.JsDiff = JsDiff;
}
})(this);
},{}],35:[function(require,module,exports){
module.exports = function (a, b) {
var c = b.start - a.start;
if (c !== 0) { return c; }
return (a.end - a.start) - (b.end - b.start);
};
},{}],36:[function(require,module,exports){
var intersectsWithSome = require(37).intersectsWithSome;
var byDescStartAndLength = require(35);
module.exports = function greedyIntervalPacker(intervals, options) {
options = options || {};
if (!Array.isArray(intervals)) {
throw new Error('The interval packer requires an array of objects with start and end properties.');
}
if (intervals.length === 0) {
return [];
}
intervals.forEach(function (interval) {
if (
typeof interval !== 'object' ||
typeof interval.start !== 'number' ||
typeof interval.end !== 'number' ||
interval.end <= interval.start
) {
throw new Error('Intervals must be objects with integer properties start and end where start < end.');
}
});
intervals = [].concat(intervals).sort(byDescStartAndLength);
var currentPartition;
var partitions = [];
var currentPartitionEnd = -Infinity;
while (intervals.length > 0) {
var interval = intervals.pop();
if (currentPartitionEnd <= interval.start) {
currentPartition = [[]];
partitions.push(currentPartition);
}
var i = 0;
while (
i < currentPartition.length &&
intersectsWithSome(currentPartition[i], interval)
) {
i += 1;
}
(currentPartition[i] = currentPartition[i] || []).push(interval);
currentPartitionEnd = Math.max(currentPartitionEnd, interval.end);
}
if (!options.groupPartitions) {
return partitions.reduce(function (result, partition) {
partition.forEach(function (partitionGroup, i) {
result[i] = result[i] || [];
Array.prototype.push.apply(result[i], partitionGroup);
return result;
});
return result;
}, []);
} else {
return partitions;
}
};
},{"35":35,"37":37}],37:[function(require,module,exports){
var intersection = {
intersects: function intersects(x, y) {
return (x.start < y.end && y.start < x.end) || x.start === y.start;
},
intersectsWithSome: function intersectsWithSome(intervals, interval) {
function intersectWithInterval(other) {
return intersection.intersects(interval, other);
}
return intervals.some(intersectWithInterval);
}
};
module.exports = intersection;
},{}],38:[function(require,module,exports){
exports.read = function (buffer, offset, isLE, mLen, nBytes) {
var e, m
var eLen = nBytes * 8 - mLen - 1
var eMax = (1 << eLen) - 1
var eBias = eMax >> 1
var nBits = -7
var i = isLE ? (nBytes - 1) : 0
var d = isLE ? -1 : 1
var s = buffer[offset + i]
i += d
e = s & ((1 << (-nBits)) - 1)
s >>= (-nBits)
nBits += eLen
for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
m = e & ((1 << (-nBits)) - 1)
e >>= (-nBits)
nBits += mLen
for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
if (e === 0) {
e = 1 - eBias
} else if (e === eMax) {
return m ? NaN : ((s ? -1 : 1) * Infinity)
} else {
m = m + Math.pow(2, mLen)
e = e - eBias
}
return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
}
exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
var e, m, c
var eLen = nBytes * 8 - mLen - 1
var eMax = (1 << eLen) - 1
var eBias = eMax >> 1
var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
var i = isLE ? 0 : (nBytes - 1)
var d = isLE ? 1 : -1
var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
value = Math.abs(value)
if (isNaN(value) || value === Infinity) {
m = isNaN(value) ? 1 : 0
e = eMax
} else {
e = Math.floor(Math.log(value) / Math.LN2)
if (value * (c = Math.pow(2, -e)) < 1) {
e--
c *= 2
}
if (e + eBias >= 1) {
value += rt / c
} else {
value += rt * Math.pow(2, 1 - eBias)
}
if (value * c >= 2) {
e++
c /= 2
}
if (e + eBias >= eMax) {
m = 0
e = eMax
} else if (e + eBias >= 1) {
m = (value * c - 1) * Math.pow(2, mLen)
e = e + eBias
} else {
m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
e = 0
}
}
for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
e = (e << mLen) | m
eLen += mLen
for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
buffer[offset + i - d] |= s * 128
}
},{}],39:[function(require,module,exports){
'use strict';
var numberIsNan = require(52);
module.exports = Number.isFinite || function (val) {
return !(typeof val !== 'number' || numberIsNan(val) || val === Infinity || val === -Infinity);
};
},{"52":52}],40:[function(require,module,exports){
/* eslint-disable no-nested-ternary */
'use strict';
var arr = [];
var charCodeCache = [];
module.exports = function (a, b) {
if (a === b) {
return 0;
}
var aLen = a.length;
var bLen = b.length;
if (aLen === 0) {
return bLen;
}
if (bLen === 0) {
return aLen;
}
var bCharCode;
var ret;
var tmp;
var tmp2;
var i = 0;
var j = 0;
while (i < aLen) {
charCodeCache[i] = a.charCodeAt(i);
arr[i] = ++i;
}
while (j < bLen) {
bCharCode = b.charCodeAt(j);
tmp = j++;
ret = j;
for (i = 0; i < aLen; i++) {
tmp2 = bCharCode === charCodeCache[i] ? tmp : tmp + 1;
tmp = arr[i];
ret = arr[i] = tmp > ret ? tmp2 > ret ? ret + 1 : tmp2 : tmp2 > tmp ? tmp + 1 : tmp2;
}
}
return ret;
};
},{}],41:[function(require,module,exports){
var utils = require(51);
var TextSerializer = require(45);
var colorDiff = require(31);
var rgbRegexp = require(49);
var themeMapper = require(50);
var cacheSize = 0;
var maxColorCacheSize = 1024;
var ansiStyles = utils.extend({}, require(22));
Object.keys(ansiStyles).forEach(function (styleName) {
ansiStyles[styleName.toLowerCase()] = ansiStyles[styleName];
});
function AnsiSerializer(theme) {
this.theme = theme;
}
AnsiSerializer.prototype = new TextSerializer();
AnsiSerializer.prototype.format = 'ansi';
var colorPalettes = {
16: {
'#000000': 'black',
'#ff0000': 'red',
'#00ff00': 'green',
'#ffff00': 'yellow',
'#0000ff': 'blue',
'#ff00ff': 'magenta',
'#00ffff': 'cyan',
'#ffffff': 'white',
'#808080': 'gray'
},
256: {}
};
var diffPalettes = {};
function convertColorToObject(color) {
if (color.length < 6) {
// Allow CSS shorthand
color = color.replace(/^#?([0-9a-f])([0-9a-f])([0-9a-f])$/i, '$1$1$2$2$3$3');
}
// Split color into red, green, and blue components
var hexMatch = color.match(/^#?([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])$/i);
if (hexMatch) {
return {
R: parseInt(hexMatch[1], 16),
G: parseInt(hexMatch[2], 16),
B: parseInt(hexMatch[3], 16)
};
}
}
function toHexColor(colorObject) {
var hexString = (Math.round(colorObject.R) * 0x10000 + Math.round(colorObject.G) * 0x100 + Math.round(colorObject.B)).toString(16);
return '#' + ('00000'.substr(0, 6 - hexString.length)) + hexString;
}
function firstUp(text) {
return text.substring(0, 1).toUpperCase() + text.substring(1);
}
diffPalettes[16] = Object.keys(colorPalettes[16]).map(convertColorToObject);
diffPalettes['bg16'] = Object.keys(colorPalettes[16]).filter(function (color) {
return color !== "#808080";
}).map(convertColorToObject);
diffPalettes[256] = [].concat(diffPalettes[16]);
var nextAnsiColorNumber = 16;
function registerNext256PaletteEntry(obj) {
diffPalettes[256].push(obj);
colorPalettes[256][toHexColor(obj)] = nextAnsiColorNumber;
nextAnsiColorNumber += 1;
}
for (var r = 0 ; r < 6 ; r += 1) {
for (var g = 0 ; g < 6 ; g += 1) {
for (var b = 0 ; b < 6 ; b += 1) {
registerNext256PaletteEntry({
R: Math.round(r * 256 / 6),
G: Math.round(g * 256 / 6),
B: Math.round(b * 256 / 6)
});
}
}
}
[
0x08, 0x12, 0x1c, 0x26, 0x30, 0x3a, 0x44, 0x4e, 0x58, 0x60, 0x66, 0x76,
0x80, 0x8a, 0x94, 0x9e, 0xa8, 0xb2, 0xbc, 0xc6, 0xd0, 0xda, 0xe4, 0xee
].forEach(function (value) {
registerNext256PaletteEntry({R: value, G: value, B: value});
});
AnsiSerializer.prototype.text = function (options) {
var content = String(options.content);
if (content === '') {
return '';
}
var styles = themeMapper(this.theme, options.styles);
if (styles.length > 0) {
for (var i = styles.length -1; i >= 0; i -= 1) {
var styleName = styles[i];
if (ansiStyles[styleName]) {
content = ansiStyles[styleName].open + content + ansiStyles[styleName].close;
} else if (rgbRegexp.test(styleName)) {
var originalStyleName = styleName;
var isBackgroundColor = styleName.substring(0, 2) === 'bg';
var colorName = isBackgroundColor ? styleName.substring(2) : styleName;
var color16Hex = toHexColor(colorDiff.closest(convertColorToObject(colorName),
diffPalettes[isBackgroundColor ? 'bg16' : 16]));
var closestColor16 = colorPalettes[16][color16Hex];
var color256Hex = toHexColor(colorDiff.closest(convertColorToObject(colorName), diffPalettes[256]));
var closest256ColorIndex = colorPalettes[256][color256Hex];
if (isBackgroundColor) {
styleName = 'bg' + firstUp(closestColor16);
} else {
styleName = closestColor16;
}
var open = ansiStyles[styleName].open;
var close = ansiStyles[styleName].close;
if (color16Hex !== color256Hex) {
open += '\x1b[' + (isBackgroundColor ? 48 : 38) + ';5;' + closest256ColorIndex + 'm';
}
if (cacheSize < maxColorCacheSize) {
ansiStyles[originalStyleName] = {open: open, close: close};
cacheSize += 1;
}
content = open + content + close;
}
}
}
return content;
};
module.exports = AnsiSerializer;
},{"22":22,"31":31,"45":45,"49":49,"50":50,"51":51}],42:[function(require,module,exports){
var cssStyles = require(46);
var flattenBlocksInLines = require(48);
var rgbRegexp = require(49);
var themeMapper = require(50);
function ColoredConsoleSerializer(theme) {
this.theme = theme;
}
ColoredConsoleSerializer.prototype.format = 'coloredConsole';
ColoredConsoleSerializer.prototype.serialize = function (lines) {
var formatString = '';
var styleStrings = [];
this.serializeLines(flattenBlocksInLines(lines)).forEach(function (entry) {
if (entry) {
formatString += entry[0];
if (entry.length > 1) {
styleStrings.push(entry[1]);
}
}
});
return [formatString].concat(styleStrings);
};
ColoredConsoleSerializer.prototype.serializeLines = function (lines) {
var result = [];
lines.forEach(function (line, i) {
if (i > 0) {
result.push(['%c\n ', '']);
}
Array.prototype.push.apply(result, this.serializeLine(line));
}, this);
return result;
};
ColoredConsoleSerializer.prototype.serializeLine = function (line) {
var result = [];
line.forEach(function (outputEntry) {
if (this[outputEntry.style]) {
result.push(this[outputEntry.style](outputEntry.args));
}
}, this);
return result;
};
ColoredConsoleSerializer.prototype.block = function (content) {
return this.serializeLines(content);
};
ColoredConsoleSerializer.prototype.text = function (options) {
var content = String(options.content);
if (content === '') {
return '';
}
var styles = themeMapper(this.theme, options.styles);
var result = ['%c' + content.replace(/%/g, '%%')];
var styleProperties = [];
if (styles.length > 0) {
for (var i = 0; i < styles.length; i += 1) {
var styleName = styles[i];
if (rgbRegexp.test(styleName)) {
if (styleName.substring(0, 2) === 'bg') {
styleProperties.push('background-color: ' + styleName.substring(2));
} else {
styleProperties.push('color: ' + styleName);
}
} else if (cssStyles[styleName]) {
styleProperties.push(cssStyles[styleName]);
}
}
}
result.push(styleProperties.join('; '));
return result;
};
ColoredConsoleSerializer.prototype.raw = function (options) {
return String(options.content(this));
};
module.exports = ColoredConsoleSerializer;
},{"46":46,"48":48,"49":49,"50":50}],43:[function(require,module,exports){
var cssStyles = require(46);
var rgbRegexp = require(49);
var themeMapper = require(50);
function HtmlSerializer(theme) {
this.theme = theme;
}
HtmlSerializer.prototype.format = 'html';
HtmlSerializer.prototype.serialize = function (lines) {
return '<div style="font-family: monospace; white-space: nowrap">' + this.serializeLines(lines) + '</div>';
};
HtmlSerializer.prototype.serializeLines = function (lines) {
return lines.map(function (line) {
return '<div>' + (this.serializeLine(line).join('') || ' ') + '</div>';
}, this).join('');
};
HtmlSerializer.prototype.serializeLine = function (line) {
return line.map(function (outputEntry) {
return this[outputEntry.style] ?
this[outputEntry.style](outputEntry.args) :
'';
}, this);
};
HtmlSerializer.prototype.block = function (content) {
return '<div style="display: inline-block; vertical-align: top">' +
this.serializeLines(content) +
'</div>';
};
HtmlSerializer.prototype.text = function (options) {
var content = String(options.content);
if (content === '') {
return '';
}
content = content
.replace(/&/g, '&')
.replace(/ /g, ' ')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"');
var styles = themeMapper(this.theme, options.styles);
if (styles.length > 0) {
var styleProperties = [];
for (var j = 0; j < styles.length; j += 1) {
var styleName = styles[j];
if (rgbRegexp.test(styleName)) {
if (styleName.substring(0, 2) === 'bg') {
styleProperties.push('background-color: ' + styleName.substring(2));
} else {
styleProperties.push('color: ' + styleName);
}
} else if (cssStyles[styleName]) {
styleProperties.push(cssStyles[styleName]);
}
}
if (styleProperties.length > 0) {
content = '<span style="' + styleProperties.join('; ') + '">' + content + '</span>';
}
}
return content;
};
HtmlSerializer.prototype.raw = function (options) {
return String(options.content(this));
};
module.exports = HtmlSerializer;
},{"46":46,"49":49,"50":50}],44:[function(require,module,exports){
(function (process){
/*global window*/
var utils = require(51);
var extend = utils.extend;
var duplicateText = require(47);
var rgbRegexp = require(49);
var cssStyles = require(46);
var builtInStyleNames = [
'bold', 'dim', 'italic', 'underline', 'inverse', 'hidden',
'strikeThrough', 'black', 'red', 'green', 'yellow', 'blue',
'magenta', 'cyan', 'white', 'gray', 'bgBlack', 'bgRed',
'bgGreen', 'bgYellow', 'bgBlue', 'bgMagenta', 'bgCyan',
'bgWhite'
];
function MagicPen(options) {
if (!(this instanceof MagicPen)) {
return new MagicPen(options);
}
options = options || {};
if (typeof options === "string") {
options = {format: options };
}
var indentationWidth = 'indentationWidth' in options ?
options.indentationWidth : 2;
this.indentationWidth = Math.max(indentationWidth, 0);
this.indentationLevel = 0;
this.output = [[]];
this.styles = Object.create(null);
this.installedPlugins = [];
// Ready to be cloned individually:
this._themes = {};
Object.keys(MagicPen.serializers).forEach(function (serializerName) {
this._themes[serializerName] = { styles: {} };
}, this);
this.preferredWidth = (!process.browser && process.stdout.columns) || 80;
if (options.format) {
this.format = options.format;
}
}
if (typeof exports === 'object' && typeof exports.nodeName !== 'string' && require(55)) {
MagicPen.defaultFormat = 'ansi'; // colored console
} else if (typeof window !== 'undefined' && typeof window.navigator !== 'undefined') {
if (window._phantom || window.mochaPhantomJS || (window.__karma__ && window.__karma__.config.captureConsole)) {
MagicPen.defaultFormat = 'ansi'; // colored console
} else {
MagicPen.defaultFormat = 'html'; // Browser
}
} else {
MagicPen.defaultFormat = 'text'; // Plain text
}
MagicPen.prototype.newline = MagicPen.prototype.nl = function (count) {
if (typeof count === 'undefined') {
count = 1;
}
if (count === 0) {
return this;
}
for (var i = 0; i < count; i += 1) {
this.output.push([]);
}
return this;
};
MagicPen.serializers = {};
[
require(45),
require(43),
require(41),
require(42)
].forEach(function (serializer) {
MagicPen.serializers[serializer.prototype.format] = serializer;
});
function hasSameTextStyling(a, b) {
if (!a || !b || a.style !== 'text' || b.style !== 'text') {
return false;
}
return utils.arrayEquals(a.args.styles, b.args.styles);
}
function normalizeLine(line) {
if (line.length === 0) {
return line;
}
var result = [line[0]];
for (var i = 1; i < line.length; i += 1) {
var lastEntry = result[result.length - 1];
var entry = line[i];
if (entry.style === 'text' && entry.args.content === '') {
continue;
}
if (hasSameTextStyling(lastEntry, entry)) {
result[result.length - 1] = {
style: lastEntry.style,
args: {
content: lastEntry.args.content + entry.args.content,
styles: lastEntry.args.styles
}
};
} else {
result.push(entry);
}
}
return result;
}
MagicPen.prototype.write = function (options) {
if (this.styles[options.style]) {
this.styles[options.style].apply(this, options.args);
return this;
}
var lastLine = this.output[this.output.length - 1];
var lastEntry = lastLine[lastLine.length - 1];
if (hasSameTextStyling(lastEntry, options)) {
lastLine[lastLine.length - 1] = {
style: lastEntry.style,
args: {
content: lastEntry.args.content + options.args.content,
styles: lastEntry.args.styles
}
};
} else {
lastLine.push(options);
}
return this;
};
MagicPen.prototype.indentLines = function () {
this.indentationLevel += 1;
return this;
};
MagicPen.prototype.indent = MagicPen.prototype.i = function () {
for (var i = 0; i < this.indentationLevel; i += 1) {
this.space(this.indentationWidth);
}
return this;
};
MagicPen.prototype.outdentLines = function () {
this.indentationLevel = Math.max(0, this.indentationLevel - 1);
return this;
};
MagicPen.prototype.addStyle = function (style, handler, allowRedefinition) {
if (this[style] === false || ((this.hasOwnProperty(style) || MagicPen.prototype[style]) && !Object.prototype.hasOwnProperty.call(this.styles, style) && builtInStyleNames.indexOf(style) === -1)) {
throw new Error('"' + style + '" style cannot be defined, it clashes with a built-in attribute');
}
// Refuse to redefine a built-in style or a style already defined directly on this pen unless allowRedefinition is true:
if (this.hasOwnProperty(style) || builtInStyleNames.indexOf(style) !== -1) {
var existingType = typeof this[style];
if (existingType === 'function') {
if (!allowRedefinition) {
throw new Error('"' + style + '" style is already defined, set 3rd arg (allowRedefinition) to true to define it anyway');
}
}
}
if (this._stylesHaveNotBeenClonedYet) {
this.styles = Object.create(this.styles);
this._stylesHaveNotBeenClonedYet = false;
}
this.styles[style] = handler;
this[style] = function () {
handler.apply(this, arguments);
return this;
};
return this;
};
MagicPen.prototype.toString = function (format) {
if (format && this.format && format !== this.format) {
throw new Error('A pen with format: ' + this.format + ' cannot be serialized to: ' + format);
}
format = this.format || format || 'text';
if (format === 'auto') {
format = MagicPen.defaultFormat;
}
var theme = this._themes[format] || {};
var serializer = new MagicPen.serializers[format](theme);
return serializer.serialize(this.output);
};
MagicPen.prototype.text = function () {
var content = arguments[0];
if (content === '') {
return this;
}
var styles = new Array(arguments.length - 1);
for (var i = 1; i < arguments.length; i += 1) {
styles[i - 1] = arguments[i];
}
content = String(content);
if (content.indexOf('\n') !== -1) {
var lines = content.split(/\n/);
lines.forEach(function (lineContent, index) {
if (lineContent.length) {
this.write({
style: 'text',
args: { content: lineContent, styles: styles }
});
}
if (index < lines.length - 1) {
this.nl();
}
}, this);
return this;
} else {
return this.write({
style: 'text',
args: { content: content, styles: styles }
});
}
};
MagicPen.prototype.removeFormatting = function () {
var result = this.clone();
this.output.forEach(function (line, index) {
result.output[index] = normalizeLine(line.map(function (outputEntry) {
return outputEntry.style === 'text' ?
{ style: 'text', args: { content: outputEntry.args.content, styles: [] } } :
outputEntry;
}));
});
result.indentationLevel = this.indentationLevel;
return result;
};
MagicPen.prototype.getContentFromArguments = function (args) {
var clone;
if (args[0].isMagicPen) {
this.ensureCompatibleFormat(args[0].format);
return args[0];
} else if (typeof args[0] === 'function') {
clone = this.clone();
args[0].call(clone, clone);
return clone;
} else if (typeof args[0] === 'string' && args.length === 1) {
clone = this.clone();
clone.text(args[0]);
return clone;
} else if (typeof args[0] === 'string') {
clone = this.clone();
clone[args[0]].apply(clone, Array.prototype.slice.call(args, 1));
return clone;
} else {
throw new Error('Requires the arguments to be:\n' +
'a pen or\n' +
'a callback appending content to a pen or\n' +
'a style and arguments for that style or\n' +
'just a string.');
}
};
MagicPen.prototype.isMultiline = function () {
return this.output.length > 1 || this.size().height > 1;
};
MagicPen.prototype.isAtStartOfLine = function () {
return this.output.length === 0 || this.output[this.output.length - 1].length === 0;
};
MagicPen.prototype.isBlock = function () {
return this.output.length === 1 &&
this.output[0].length === 1 &&
this.output[0][0].style === 'block';
};
MagicPen.prototype.ensureCompatibleFormat = function (format) {
if (format && this.format && format !== this.format) {
throw new Error('This pen is only compatible with the format: ' + this.format);
}
};
MagicPen.prototype.block = function () {
var pen = this.getContentFromArguments(arguments);
var blockOutput = pen.output.map(function (line) {
return [].concat(line);
});
return this.write({ style: 'block', args: blockOutput });
};
function isRawOutput(options) {
return options &&
typeof options === 'object' &&
typeof options.width === 'number' &&
typeof options.height === 'number' && (
typeof options.content === 'function' ||
typeof options.content === 'string'
);
}
MagicPen.prototype.alt = function (options) {
var format = this.format;
if (!format) {
throw new Error('The alt method is only supported on pen where the format has already been set');
}
var outputProperty = options[format];
if (typeof outputProperty === 'undefined') {
if (options.fallback) {
return this.append(options.fallback);
} else {
// Nothing to do for this format, just NOOP:
return this;
}
}
if (typeof outputProperty === 'string' || isRawOutput(outputProperty)) {
return this.raw(outputProperty);
} else {
return this.append(outputProperty);
}
};
MagicPen.prototype.raw = function (options) {
var format = this.format;
if (!format) {
throw new Error('The alt method is only supported on pen where the format has already been set');
}
if (typeof options === 'string') {
return this.write({ style: 'raw', args: {
height: 0,
width: 0,
content: function () {
return options;
}
}});
}
if (isRawOutput(options)) {
if (typeof options.content === 'string') {
options = extend({}, options);
var content = options.content;
options.content = function () {
return content;
};
}
return this.write({ style: 'raw', args: options });
}
throw new Error('Raw ' + this.format + ' content needs to adhere to one of the following forms:\n' +
'a string of raw content\n' +
'a function returning a string of raw content or\n' +
'an object with the following form { width: <number>, height: <number>, content: <string function() {}|string> }');
};
function amend(output, pen) {
var lastLine = output[output.length - 1].slice();
var newOutput = output.slice(0, -1);
var lastEntry = lastLine[lastLine.length - 1];
if (lastEntry && lastEntry.style === 'block') {
lastLine[lastLine.length - 1] = {
style: 'block',
args: amend(lastEntry.args, pen)
};
newOutput[output.length - 1] = lastLine;
} else {
Array.prototype.push.apply(lastLine, pen.output[0]);
newOutput[output.length - 1] = normalizeLine(lastLine);
newOutput.push.apply(newOutput, pen.output.slice(1));
}
return newOutput;
}
MagicPen.prototype.amend = function () {
var pen = this.getContentFromArguments(arguments);
if (pen.isEmpty()) {
return this;
}
this.output = amend(this.output, pen);
return this;
};
MagicPen.prototype.append = function () {
var pen = this.getContentFromArguments(arguments);
if (pen.isEmpty()) {
return this;
}
var lastLine = this.output[this.output.length - 1];
Array.prototype.push.apply(lastLine, pen.output[0]);
this.output[this.output.length - 1] = normalizeLine(lastLine);
this.output.push.apply(this.output, pen.output.slice(1));
return this;
};
MagicPen.prototype.prependLinesWith = function () {
var pen = this.getContentFromArguments(arguments);
if (pen.isEmpty()) {
return this;
}
if (pen.output.length > 1) {
throw new Error('PrependLinesWith only supports a pen with single line content');
}
var height = this.size().height;
var output = this.clone();
output.block(function () {
for (var i = 0; i < height; i += 1) {
if (0 < i) {
this.nl();
}
this.append(pen);
}
});
output.block(this);
this.output = output.output;
return this;
};
MagicPen.prototype.space = MagicPen.prototype.sp = function (count) {
if (count === 0) {
return this;
}
if (typeof count === 'undefined') {
count = 1;
}
return this.text(duplicateText(' ', count));
};
builtInStyleNames.forEach(function (textStyle) {
MagicPen.prototype[textStyle] = MagicPen.prototype[textStyle.toLowerCase()] = function (content) {
return this.text(content, textStyle);
};
});
MagicPen.prototype.clone = function (format) {
if (!this.isEmpty()) {
this.ensureCompatibleFormat(format);
}
function MagicPenClone() {}
MagicPenClone.prototype = this;
var clonedPen = new MagicPenClone();
clonedPen.styles = this.styles;
clonedPen._stylesHaveNotBeenClonedYet = true;
clonedPen.indentationLevel = 0;
clonedPen.output = [[]];
clonedPen.installedPlugins = [];
clonedPen._themes = this._themes;
clonedPen._themesHaveNotBeenClonedYet = true;
clonedPen.format = format || this.format;
clonedPen.parent = this;
return clonedPen;
};
MagicPen.prototype.isMagicPen = true;
MagicPen.prototype.size = function () {
return utils.calculateSize(this.output);
};
MagicPen.prototype.use = function (plugin) {
var existingPlugin = utils.findFirst(this.installedPlugins, function (installedPlugin) {
if (installedPlugin === plugin) {
return true;
} else if (typeof plugin === 'function' && typeof installedPlugin === 'function') {
var pluginName = utils.getFunctionName(plugin);
return pluginName !== '' && pluginName === utils.getFunctionName(installedPlugin);
} else {
return installedPlugin.name === plugin.name;
}
});
if (existingPlugin) {
if (existingPlugin === plugin || (typeof plugin.version !== 'undefined' && plugin.version === existingPlugin.version)) {
// No-op
return this;
} else {
throw new Error("Another instance of the plugin '" + plugin.name + "' " +
"is already installed" +
(typeof existingPlugin.version !== 'undefined' ?
' (version ' + existingPlugin.version +
(typeof plugin.version !== 'undefined' ?
', trying to install ' + plugin.version : '') +
')' : '') +
". Please check your node_modules folder for unmet peerDependencies.");
}
}
if ((typeof plugin !== 'function' && (typeof plugin !== 'object' || typeof plugin.installInto !== 'function')) ||
(typeof plugin.name !== 'undefined' && typeof plugin.name !== 'string') ||
(typeof plugin.dependencies !== 'undefined' && !Array.isArray(plugin.dependencies))) {
throw new Error('Plugins must be functions or adhere to the following interface\n' +
'{\n' +
' name: <an optional plugin name>,\n' +
' version: <an optional semver version string>,\n' +
' dependencies: <an optional list of dependencies>,\n' +
' installInto: <a function that will update the given magicpen instance>\n' +
'}');
}
if (plugin.dependencies) {
var instance = this;
var thisAndParents = [];
do {
thisAndParents.push(instance);
instance = instance.parent;
} while (instance);
var unfulfilledDependencies = plugin.dependencies.filter(function (dependency) {
return !thisAndParents.some(function (instance) {
return instance.installedPlugins.some(function (plugin) {
return plugin.name === dependency;
});
});
});
if (unfulfilledDependencies.length === 1) {
throw new Error(plugin.name + ' requires plugin ' + unfulfilledDependencies[0]);
} else if (unfulfilledDependencies.length > 1) {
throw new Error(plugin.name + ' requires plugins ' +
unfulfilledDependencies.slice(0, -1).join(', ') +
' and ' + unfulfilledDependencies[unfulfilledDependencies.length - 1]);
}
}
this.installedPlugins.push(plugin);
if (typeof plugin === 'function') {
plugin(this);
} else {
plugin.installInto(this);
}
return this; // for chaining
};
MagicPen.prototype.installPlugin = MagicPen.prototype.use; // Legacy alias
function replaceText(output, outputArray, regexp, cb) {
var replacedOutput = output;
outputArray.forEach(function (line, i) {
if (0 < i) {
replacedOutput.nl();
}
line.forEach(function (outputEntry, j) {
if (outputEntry.style === 'block') {
return replacedOutput.output[replacedOutput.output.length - 1].push({
style: 'block',
args: replaceText(output.clone(), outputEntry.args, regexp, cb)
});
} else if (outputEntry.style !== 'text') {
return replacedOutput.output[replacedOutput.output.length - 1].push(outputEntry);
}
if (regexp.global) {
regexp.lastIndex = 0;
}
var m;
var first = true;
var lastIndex = 0;
var text = outputEntry.args.content;
var styles = outputEntry.args.styles;
while ((m = regexp.exec(text)) !== null && (regexp.global || first)) {
if (lastIndex < m.index) {
replacedOutput.text.apply(replacedOutput, [text.substring(lastIndex, m.index)].concat(styles));
}
cb.apply(replacedOutput, [styles].concat(m));
first = false;
lastIndex = m.index + m[0].length;
}
if (lastIndex === 0) {
var lastLine;
if (replacedOutput.output.length === 0) {
lastLine = replacedOutput.output[0] = [];
} else {
lastLine = replacedOutput.output[replacedOutput.output.length - 1];
}
lastLine.push(outputEntry);
} else if (lastIndex < text.length) {
replacedOutput.text.apply(replacedOutput, [text.substring(lastIndex, text.length)].concat(styles));
}
}, this);
}, this);
return replacedOutput.output.map(normalizeLine);
}
MagicPen.prototype.isEmpty = function () {
return this.output.length === 1 && this.output[0].length === 0;
};
MagicPen.prototype.replaceText = function (regexp, cb) {
if (this.isEmpty()) {
return this;
}
if (typeof regexp === 'string') {
regexp = new RegExp(utils.escapeRegExp(regexp), 'g');
}
if (typeof cb === 'string') {
var text = cb;
cb = function (styles, _) {
var args = [text].concat(styles);
this.text.apply(this, args);
};
}
if (arguments.length === 1) {
cb = regexp;
regexp = /.*/;
}
this.output = replaceText(this.clone(), this.output, regexp, cb);
return this;
};
MagicPen.prototype.theme = function (format) {
format = format || this.format;
if (!format) {
throw new Error("Could not detect which format you want to retrieve " +
"theme information for. Set the format of the pen or " +
"provide it as an argument to the theme method.");
}
return this._themes[format];
};
MagicPen.prototype.installTheme = function (formats, theme) {
var that = this;
if (arguments.length === 1) {
theme = formats;
formats = Object.keys(MagicPen.serializers);
}
if (typeof formats === 'string') {
formats = [formats];
}
if (
typeof theme !== 'object' ||
!Array.isArray(formats) ||
formats.some(function (format) {
return typeof format !== 'string';
})
) {
throw new Error("Themes must be installed the following way:\n" +
"Install theme for all formats: pen.installTheme({ comment: 'gray' })\n" +
"Install theme for a specific format: pen.installTheme('ansi', { comment: 'gray' }) or\n" +
"Install theme for a list of formats: pen.installTheme(['ansi', 'html'], { comment: 'gray' })");
}
if (!theme.styles || typeof theme.styles !== 'object') {
theme = {
styles: theme
};
}
if (that._themesHaveNotBeenClonedYet) {
var clonedThemes = {};
Object.keys(that._themes).forEach(function (format) {
clonedThemes[format] = Object.create(that._themes[format]);
});
that._themes = clonedThemes;
that._themesHaveNotBeenClonedYet = false;
}
Object.keys(theme.styles).forEach(function (themeKey) {
if (rgbRegexp.test(themeKey) || cssStyles[themeKey]) {
throw new Error("Invalid theme key: '" + themeKey + "' you can't map build styles.");
}
if (!that[themeKey]) {
that.addStyle(themeKey, function (content) {
this.text(content, themeKey);
});
}
});
formats.forEach(function (format) {
var baseTheme = that._themes[format] || { styles: {} };
var extendedTheme = extend({}, baseTheme, theme);
extendedTheme.styles = extend({}, baseTheme.styles, theme.styles);
that._themes[format] = extendedTheme;
});
return this;
};
module.exports = MagicPen;
}).call(this,require(53))
},{"41":41,"42":42,"43":43,"45":45,"46":46,"47":47,"49":49,"51":51,"53":53,"55":55}],45:[function(require,module,exports){
var flattenBlocksInLines = require(48);
function TextSerializer() {}
TextSerializer.prototype.format = 'text';
TextSerializer.prototype.serialize = function (lines) {
lines = flattenBlocksInLines(lines);
return lines.map(this.serializeLine, this).join('\n');
};
TextSerializer.prototype.serializeLine = function (line) {
return line.map(function (outputEntry) {
return this[outputEntry.style] ?
String(this[outputEntry.style](outputEntry.args)) :
'';
}, this).join('');
};
TextSerializer.prototype.text = function (options) {
return String(options.content);
};
TextSerializer.prototype.block = function (content) {
return this.serialize(content);
};
TextSerializer.prototype.raw = function (options) {
return String(options.content(this));
};
module.exports = TextSerializer;
},{"48":48}],46:[function(require,module,exports){
var cssStyles = {
bold: 'font-weight: bold',
dim: 'opacity: 0.7',
italic: 'font-style: italic',
underline: 'text-decoration: underline',
inverse: '-webkit-filter: invert(%100); filter: invert(100%)',
hidden: 'visibility: hidden',
strikeThrough: 'text-decoration: line-through',
black: 'color: black',
red: 'color: red',
green: 'color: green',
yellow: 'color: yellow',
blue: 'color: blue',
magenta: 'color: magenta',
cyan: 'color: cyan',
white: 'color: white',
gray: 'color: gray',
bgBlack: 'background-color: black',
bgRed: 'background-color: red',
bgGreen: 'background-color: green',
bgYellow: 'background-color: yellow',
bgBlue: 'background-color: blue',
bgMagenta: 'background-color: magenta',
bgCyan: 'background-color: cyan',
bgWhite: 'background-color: white'
};
Object.keys(cssStyles).forEach(function (styleName) {
cssStyles[styleName.toLowerCase()] = cssStyles[styleName];
});
module.exports = cssStyles;
},{}],47:[function(require,module,exports){
var whitespaceCacheLength = 256;
var whitespaceCache = [''];
for (var i = 1; i <= whitespaceCacheLength; i += 1) {
whitespaceCache[i] = whitespaceCache[i - 1] + ' ';
}
function duplicateText(content, times) {
if (times < 0) {
return '';
}
var result = '';
if (content === ' ') {
if (times <= whitespaceCacheLength) {
return whitespaceCache[times];
}
var segment = whitespaceCache[whitespaceCacheLength];
var numberOfSegments = Math.floor(times / whitespaceCacheLength);
for (var i = 0; i < numberOfSegments; i += 1) {
result += segment;
}
result += whitespaceCache[times % whitespaceCacheLength];
} else {
for (var j = 0; j < times; j += 1) {
result += content;
}
}
return result;
}
module.exports = duplicateText;
},{}],48:[function(require,module,exports){
var utils = require(51);
var duplicateText = require(47);
function createPadding(length) {
return { style: 'text', args: { content: duplicateText(' ', length), styles: [] } };
}
function lineContainsBlocks(line) {
return line.some(function (outputEntry) {
return outputEntry.style === 'block' ||
(outputEntry.style === 'text' && String(outputEntry.args.content).indexOf('\n') !== -1);
});
}
function flattenBlocksInOutputEntry(outputEntry) {
switch (outputEntry.style) {
case 'text': return String(outputEntry.args.content).split('\n').map(function (line) {
if (line === '') {
return [];
}
var args = { content: line, styles: outputEntry.args.styles };
return [{ style: 'text', args: args }];
});
case 'block': return flattenBlocksInLines(outputEntry.args);
default: return [];
}
}
function flattenBlocksInLine(line) {
if (line.length === 0) {
return [[]];
}
if (!lineContainsBlocks(line)) {
return [line];
}
var result = [];
var linesLengths = [];
var startIndex = 0;
line.forEach(function (outputEntry, blockIndex) {
var blockLines = flattenBlocksInOutputEntry(outputEntry);
var blockLinesLengths = blockLines.map(function (line) {
return utils.calculateLineSize(line).width;
});
var longestLineLength = Math.max.apply(null, blockLinesLengths);
blockLines.forEach(function (blockLine, index) {
var resultLine = result[index];
if (!resultLine) {
result[index] = resultLine = [];
linesLengths[index] = 0;
}
if (blockLine.length) {
var paddingLength = startIndex - linesLengths[index];
resultLine.push(createPadding(paddingLength));
Array.prototype.push.apply(resultLine, blockLine);
linesLengths[index] = startIndex + blockLinesLengths[index];
}
});
startIndex += longestLineLength;
}, this);
return result;
}
function flattenBlocksInLines(lines) {
var result = [];
lines.forEach(function (line) {
flattenBlocksInLine(line).forEach(function (line) {
result.push(line);
});
});
return result;
}
module.exports = flattenBlocksInLines;
},{"47":47,"51":51}],49:[function(require,module,exports){
module.exports = /^(?:bg)?#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i;
},{}],50:[function(require,module,exports){
module.exports = function (theme, styles) {
if (styles.length === 1) {
var count = 0;
var stack = [];
var themeMapping = styles[0];
var themeStyles = theme.styles || {};
while(typeof themeMapping === 'string' && themeStyles[themeMapping]) {
themeMapping = themeStyles[themeMapping];
count += 1;
if (100 < count) {
var index = stack.indexOf(themeMapping);
stack.push(themeMapping);
if (index !== -1) {
throw new Error('Your theme contains a loop: ' + stack.slice(index).join(' -> '));
}
}
}
return Array.isArray(themeMapping) ? themeMapping : [themeMapping];
}
return styles;
};
},{}],51:[function(require,module,exports){
var utils = {
extend: function (target) {
for (var i = 1; i < arguments.length; i += 1) {
var source = arguments[i];
Object.keys(source).forEach(function (key) {
target[key] = source[key];
});
}
return target;
},
calculateOutputEntrySize: function (outputEntry) {
if (outputEntry.size) {
return outputEntry.size;
}
var size;
switch (outputEntry.style) {
case 'text':
size = { width: String(outputEntry.args.content).length, height: 1 };
break;
case 'block':
size = utils.calculateSize(outputEntry.args);
break;
case 'raw':
var arg = outputEntry.args;
size = { width: arg.width, height: arg.height };
break;
default: size = { width: 0, height: 0 };
}
outputEntry.size = size;
return size;
},
calculateLineSize: function (line) {
var size = { height: 1, width: 0 };
line.forEach(function (outputEntry) {
var outputEntrySize = utils.calculateOutputEntrySize(outputEntry);
size.width += outputEntrySize.width;
size.height = Math.max(outputEntrySize.height, size.height);
});
return size;
},
calculateSize: function (lines) {
var size = { height: 0, width: 0 };
lines.forEach(function (line) {
var lineSize = utils.calculateLineSize(line);
size.height += lineSize.height;
size.width = Math.max(size.width, lineSize.width);
});
return size;
},
arrayEquals: function (a, b) {
if (a === b) {
return true;
}
if (!a || a.length !== b.length) {
return false;
}
for (var i = 0; i < a.length; i += 1) {
if (a[i] !== b[i]) {
return false;
}
}
return true;
},
escapeRegExp: function (text){
return text.replace(/([.*+?^${}()|\[\]\/\\])/g, "\\$1");
},
findFirst: function (arr, predicate, thisObj) {
var scope = thisObj || null;
for (var i = 0 ; i < arr.length ; i += 1) {
if (predicate.call(scope, arr[i], i, arr)) {
return arr[i];
}
}
return null;
},
getFunctionName: function (f) {
if (typeof f.name === 'string') {
return f.name;
}
var matchFunctionName = Function.prototype.toString.call(f).match(/function ([^\(]+)/);
if (matchFunctionName) {
return matchFunctionName[1];
}
if (f === Object) {
return 'Object';
}
if (f === Function) {
return 'Function';
}
}
};
module.exports = utils;
},{}],52:[function(require,module,exports){
'use strict';
module.exports = Number.isNaN || function (x) {
return x !== x;
};
},{}],53:[function(require,module,exports){
// shim for using process in browser
var process = module.exports = {};
// cached from whatever global is present so that test runners that stub it
// don't break things. But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals. It's inside a
// function because try/catches deoptimize in certain engines.
var cachedSetTimeout;
var cachedClearTimeout;
function defaultSetTimout() {
throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout () {
throw new Error('clearTimeout has not been defined');
}
(function () {
try {
if (typeof setTimeout === 'function') {
cachedSetTimeout = setTimeout;
} else {
cachedSetTimeout = defaultSetTimout;
}
} catch (e) {
cachedSetTimeout = defaultSetTimout;
}
try {
if (typeof clearTimeout === 'function') {
cachedClearTimeout = clearTimeout;
} else {
cachedClearTimeout = defaultClearTimeout;
}
} catch (e) {
cachedClearTimeout = defaultClearTimeout;
}
} ())
function runTimeout(fun) {
if (cachedSetTimeout === setTimeout) {
//normal enviroments in sane situations
return setTimeout(fun, 0);
}
// if setTimeout wasn't available but was latter defined
if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
cachedSetTimeout = setTimeout;
return setTimeout(fun, 0);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedSetTimeout(fun, 0);
} catch(e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedSetTimeout.call(null, fun, 0);
} catch(e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
return cachedSetTimeout.call(this, fun, 0);
}
}
}
function runClearTimeout(marker) {
if (cachedClearTimeout === clearTimeout) {
//normal enviroments in sane situations
return clearTimeout(marker);
}
// if clearTimeout wasn't available but was latter defined
if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
cachedClearTimeout = clearTimeout;
return clearTimeout(marker);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedClearTimeout(marker);
} catch (e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedClearTimeout.call(null, marker);
} catch (e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
// Some versions of I.E. have different rules for clearTimeout vs setTimeout
return cachedClearTimeout.call(this, marker);
}
}
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
if (!draining || !currentQueue) {
return;
}
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = runTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
runClearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
runTimeout(drainQueue);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.prependListener = noop;
process.prependOnceListener = noop;
process.listeners = function (name) { return [] }
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
},{}],54:[function(require,module,exports){
'use strict';
var isFinite = require(39);
module.exports = function (str, n) {
if (typeof str !== 'string') {
throw new TypeError('Expected a string as the first argument');
}
if (n < 0 || !isFinite(n)) {
throw new TypeError('Expected a finite positive number');
}
var ret = '';
do {
if (n & 1) {
ret += str;
}
str += str;
} while (n = n >> 1);
return ret;
};
},{"39":39}],55:[function(require,module,exports){
(function (process){
'use strict';
var argv = process.argv;
module.exports = (function () {
if (argv.indexOf('--no-color') !== -1 ||
argv.indexOf('--no-colors') !== -1 ||
argv.indexOf('--color=false') !== -1) {
return false;
}
if (argv.indexOf('--color') !== -1 ||
argv.indexOf('--colors') !== -1 ||
argv.indexOf('--color=true') !== -1 ||
argv.indexOf('--color=always') !== -1) {
return true;
}
if (process.stdout && !process.stdout.isTTY) {
return false;
}
if (process.platform === 'win32') {
return true;
}
if ('COLORTERM' in process.env) {
return true;
}
if (process.env.TERM === 'dumb') {
return false;
}
if (/^screen|^xterm|^vt100|color|ansi|cygwin|linux/i.test(process.env.TERM)) {
return true;
}
return false;
})();
}).call(this,require(53))
},{"53":53}],56:[function(require,module,exports){
(function (process,global){
/* @preserve
* The MIT License (MIT)
*
* Copyright (c) 2014 Petka Antonov
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
/**
* bluebird build version 2.9.34-longstack2
* Features enabled: core, race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, cancel, using, filter, any, each, timers
*/
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.Promise=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof _dereq_=="function"&&_dereq_;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof _dereq_=="function"&&_dereq_;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise) {
var SomePromiseArray = Promise._SomePromiseArray;
function any(promises) {
var ret = new SomePromiseArray(promises);
var promise = ret.promise();
ret.setHowMany(1);
ret.setUnwrap();
ret.init();
return promise;
}
Promise.any = function (promises) {
return any(promises);
};
Promise.prototype.any = function () {
return any(this);
};
};
},{}],2:[function(_dereq_,module,exports){
"use strict";
var firstLineError;
try {throw new Error(); } catch (e) {firstLineError = e;}
var schedule = _dereq_("./schedule.js");
var Queue = _dereq_("./queue.js");
var util = _dereq_("./util.js");
function Async() {
this._isTickUsed = false;
this._lateQueue = new Queue(16);
this._normalQueue = new Queue(16);
this._trampolineEnabled = true;
var self = this;
this.drainQueues = function () {
self._drainQueues();
};
this._schedule =
schedule.isStatic ? schedule(this.drainQueues) : schedule;
}
Async.prototype.disableTrampolineIfNecessary = function() {
if (util.hasDevTools) {
this._trampolineEnabled = false;
}
};
Async.prototype.enableTrampoline = function() {
if (!this._trampolineEnabled) {
this._trampolineEnabled = true;
this._schedule = function(fn) {
setTimeout(fn, 0);
};
}
};
Async.prototype.haveItemsQueued = function () {
return this._normalQueue.length() > 0;
};
Async.prototype.throwLater = function(fn, arg) {
if (arguments.length === 1) {
arg = fn;
fn = function () { throw arg; };
}
if (typeof setTimeout !== "undefined") {
setTimeout(function() {
fn(arg);
}, 0);
} else try {
this._schedule(function() {
fn(arg);
});
} catch (e) {
throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/m3OTXk\u000a");
}
};
function AsyncInvokeLater(fn, receiver, arg) {
this._lateQueue.push(fn, receiver, arg);
this._queueTick();
}
function AsyncInvoke(fn, receiver, arg) {
this._normalQueue.push(fn, receiver, arg);
this._queueTick();
}
function AsyncSettlePromises(promise) {
this._normalQueue._pushOne(promise);
this._queueTick();
}
if (!util.hasDevTools) {
Async.prototype.invokeLater = AsyncInvokeLater;
Async.prototype.invoke = AsyncInvoke;
Async.prototype.settlePromises = AsyncSettlePromises;
} else {
if (schedule.isStatic) {
schedule = function(fn) { setTimeout(fn, 0); };
}
Async.prototype.invokeLater = function (fn, receiver, arg) {
if (this._trampolineEnabled) {
AsyncInvokeLater.call(this, fn, receiver, arg);
} else {
this._schedule(function() {
setTimeout(function() {
fn.call(receiver, arg);
}, 100);
});
}
};
Async.prototype.invoke = function (fn, receiver, arg) {
if (this._trampolineEnabled) {
AsyncInvoke.call(this, fn, receiver, arg);
} else {
this._schedule(function() {
fn.call(receiver, arg);
});
}
};
Async.prototype.settlePromises = function(promise) {
if (this._trampolineEnabled) {
AsyncSettlePromises.call(this, promise);
} else {
this._schedule(function() {
promise._settlePromises();
});
}
};
}
Async.prototype.invokeFirst = function (fn, receiver, arg) {
this._normalQueue.unshift(fn, receiver, arg);
this._queueTick();
};
Async.prototype._drainQueue = function(queue) {
while (queue.length() > 0) {
var fn = queue.shift();
if (typeof fn !== "function") {
fn._settlePromises();
continue;
}
var receiver = queue.shift();
var arg = queue.shift();
fn.call(receiver, arg);
}
};
Async.prototype._drainQueues = function () {
this._drainQueue(this._normalQueue);
this._reset();
this._drainQueue(this._lateQueue);
};
Async.prototype._queueTick = function () {
if (!this._isTickUsed) {
this._isTickUsed = true;
this._schedule(this.drainQueues);
}
};
Async.prototype._reset = function () {
this._isTickUsed = false;
};
module.exports = new Async();
module.exports.firstLineError = firstLineError;
},{"./queue.js":28,"./schedule.js":31,"./util.js":38}],3:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise, INTERNAL, tryConvertToPromise) {
var rejectThis = function(_, e) {
this._reject(e);
};
var targetRejected = function(e, context) {
context.promiseRejectionQueued = true;
context.bindingPromise._then(rejectThis, rejectThis, null, this, e);
};
var bindingResolved = function(thisArg, context) {
if (this._isPending()) {
this._resolveCallback(context.target);
}
};
var bindingRejected = function(e, context) {
if (!context.promiseRejectionQueued) this._reject(e);
};
Promise.prototype.bind = function (thisArg) {
var maybePromise = tryConvertToPromise(thisArg);
var ret = new Promise(INTERNAL);
ret._propagateFrom(this, 1);
var target = this._target();
ret._setBoundTo(maybePromise);
if (maybePromise instanceof Promise) {
var context = {
promiseRejectionQueued: false,
promise: ret,
target: target,
bindingPromise: maybePromise
};
target._then(INTERNAL, targetRejected, ret._progress, ret, context);
maybePromise._then(
bindingResolved, bindingRejected, ret._progress, ret, context);
} else {
ret._resolveCallback(target);
}
return ret;
};
Promise.prototype._setBoundTo = function (obj) {
if (obj !== undefined) {
this._bitField = this._bitField | 131072;
this._boundTo = obj;
} else {
this._bitField = this._bitField & (~131072);
}
};
Promise.prototype._isBound = function () {
return (this._bitField & 131072) === 131072;
};
Promise.bind = function (thisArg, value) {
var maybePromise = tryConvertToPromise(thisArg);
var ret = new Promise(INTERNAL);
ret._setBoundTo(maybePromise);
if (maybePromise instanceof Promise) {
maybePromise._then(function() {
ret._resolveCallback(value);
}, ret._reject, ret._progress, ret, null);
} else {
ret._resolveCallback(value);
}
return ret;
};
};
},{}],4:[function(_dereq_,module,exports){
"use strict";
var old;
if (typeof Promise !== "undefined") old = Promise;
function noConflict() {
try { if (Promise === bluebird) Promise = old; }
catch (e) {}
return bluebird;
}
var bluebird = _dereq_("./promise.js")();
bluebird.noConflict = noConflict;
module.exports = bluebird;
},{"./promise.js":23}],5:[function(_dereq_,module,exports){
"use strict";
var cr = Object.create;
if (cr) {
var callerCache = cr(null);
var getterCache = cr(null);
callerCache[" size"] = getterCache[" size"] = 0;
}
module.exports = function(Promise) {
var util = _dereq_("./util.js");
var canEvaluate = util.canEvaluate;
var isIdentifier = util.isIdentifier;
var getMethodCaller;
var getGetter;
if (!true) {
var makeMethodCaller = function (methodName) {
return new Function("ensureMethod", " \n\
return function(obj) { \n\
'use strict' \n\
var len = this.length; \n\
ensureMethod(obj, 'methodName'); \n\
switch(len) { \n\
case 1: return obj.methodName(this[0]); \n\
case 2: return obj.methodName(this[0], this[1]); \n\
case 3: return obj.methodName(this[0], this[1], this[2]); \n\
case 0: return obj.methodName(); \n\
default: \n\
return obj.methodName.apply(obj, this); \n\
} \n\
}; \n\
".replace(/methodName/g, methodName))(ensureMethod);
};
var makeGetter = function (propertyName) {
return new Function("obj", " \n\
'use strict'; \n\
return obj.propertyName; \n\
".replace("propertyName", propertyName));
};
var getCompiled = function(name, compiler, cache) {
var ret = cache[name];
if (typeof ret !== "function") {
if (!isIdentifier(name)) {
return null;
}
ret = compiler(name);
cache[name] = ret;
cache[" size"]++;
if (cache[" size"] > 512) {
var keys = Object.keys(cache);
for (var i = 0; i < 256; ++i) delete cache[keys[i]];
cache[" size"] = keys.length - 256;
}
}
return ret;
};
getMethodCaller = function(name) {
return getCompiled(name, makeMethodCaller, callerCache);
};
getGetter = function(name) {
return getCompiled(name, makeGetter, getterCache);
};
}
function ensureMethod(obj, methodName) {
var fn;
if (obj != null) fn = obj[methodName];
if (typeof fn !== "function") {
var message = "Object " + util.classString(obj) + " has no method '" +
util.toString(methodName) + "'";
throw new Promise.TypeError(message);
}
return fn;
}
function caller(obj) {
var methodName = this.pop();
var fn = ensureMethod(obj, methodName);
return fn.apply(obj, this);
}
Promise.prototype.call = function (methodName) {
var $_len = arguments.length;var args = new Array($_len - 1); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];}
if (!true) {
if (canEvaluate) {
var maybeCaller = getMethodCaller(methodName);
if (maybeCaller !== null) {
return this._then(
maybeCaller, undefined, undefined, args, undefined);
}
}
}
args.push(methodName);
return this._then(caller, undefined, undefined, args, undefined);
};
function namedGetter(obj) {
return obj[this];
}
function indexedGetter(obj) {
var index = +this;
if (index < 0) index = Math.max(0, index + obj.length);
return obj[index];
}
Promise.prototype.get = function (propertyName) {
var isIndex = (typeof propertyName === "number");
var getter;
if (!isIndex) {
if (canEvaluate) {
var maybeGetter = getGetter(propertyName);
getter = maybeGetter !== null ? maybeGetter : namedGetter;
} else {
getter = namedGetter;
}
} else {
getter = indexedGetter;
}
return this._then(getter, undefined, undefined, propertyName, undefined);
};
};
},{"./util.js":38}],6:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise) {
var errors = _dereq_("./errors.js");
var async = _dereq_("./async.js");
var CancellationError = errors.CancellationError;
Promise.prototype._cancel = function (reason) {
if (!this.isCancellable()) return this;
var parent;
var promiseToReject = this;
while ((parent = promiseToReject._cancellationParent) !== undefined &&
parent.isCancellable()) {
promiseToReject = parent;
}
this._unsetCancellable();
promiseToReject._target()._rejectCallback(reason, false, true);
};
Promise.prototype.cancel = function (reason) {
if (!this.isCancellable()) return this;
if (reason === undefined) reason = new CancellationError();
async.invokeLater(this._cancel, this, reason);
return this;
};
Promise.prototype.cancellable = function () {
if (this._cancellable()) return this;
async.enableTrampoline();
this._setCancellable();
this._cancellationParent = undefined;
return this;
};
Promise.prototype.uncancellable = function () {
var ret = this.then();
ret._unsetCancellable();
return ret;
};
Promise.prototype.fork = function (didFulfill, didReject, didProgress) {
var ret = this._then(didFulfill, didReject, didProgress,
undefined, undefined);
ret._setCancellable();
ret._cancellationParent = undefined;
return ret;
};
};
},{"./async.js":2,"./errors.js":13}],7:[function(_dereq_,module,exports){
"use strict";
module.exports = function() {
var async = _dereq_("./async.js");
var util = _dereq_("./util.js");
var bluebirdFramePattern =
/[\\\/]bluebird[\\\/]js[\\\/](main|debug|zalgo|instrumented)/;
var stackFramePattern = null;
var formatStack = null;
var indentStackFrames = false;
var warn;
function CapturedTrace(parent) {
this._parent = parent;
var length = this._length = 1 + (parent === undefined ? 0 : parent._length);
captureStackTrace(this, CapturedTrace);
if (length > 32) this.uncycle();
}
util.inherits(CapturedTrace, Error);
CapturedTrace.prototype.uncycle = function() {
var length = this._length;
if (length < 2) return;
var nodes = [];
var stackToIndex = {};
for (var i = 0, node = this; node !== undefined; ++i) {
nodes.push(node);
node = node._parent;
}
length = this._length = i;
for (var i = length - 1; i >= 0; --i) {
var stack = nodes[i].stack;
if (stackToIndex[stack] === undefined) {
stackToIndex[stack] = i;
}
}
for (var i = 0; i < length; ++i) {
var currentStack = nodes[i].stack;
var index = stackToIndex[currentStack];
if (index !== undefined && index !== i) {
if (index > 0) {
nodes[index - 1]._parent = undefined;
nodes[index - 1]._length = 1;
}
nodes[i]._parent = undefined;
nodes[i]._length = 1;
var cycleEdgeNode = i > 0 ? nodes[i - 1] : this;
if (index < length - 1) {
cycleEdgeNode._parent = nodes[index + 1];
cycleEdgeNode._parent.uncycle();
cycleEdgeNode._length =
cycleEdgeNode._parent._length + 1;
} else {
cycleEdgeNode._parent = undefined;
cycleEdgeNode._length = 1;
}
var currentChildLength = cycleEdgeNode._length + 1;
for (var j = i - 2; j >= 0; --j) {
nodes[j]._length = currentChildLength;
currentChildLength++;
}
return;
}
}
};
CapturedTrace.prototype.parent = function() {
return this._parent;
};
CapturedTrace.prototype.hasParent = function() {
return this._parent !== undefined;
};
CapturedTrace.prototype.attachExtraTrace = function(error) {
if (error.__stackCleaned__) return;
this.uncycle();
var parsed = CapturedTrace.parseStackAndMessage(error);
var message = parsed.message;
var stacks = [parsed.stack];
var trace = this;
while (trace !== undefined) {
stacks.push(cleanStack(trace.stack.split("\n")));
trace = trace._parent;
}
removeCommonRoots(stacks);
removeDuplicateOrEmptyJumps(stacks);
util.notEnumerableProp(error, "stack", reconstructStack(message, stacks));
util.notEnumerableProp(error, "__stackCleaned__", true);
};
function reconstructStack(message, stacks) {
for (var i = 0; i < stacks.length - 1; ++i) {
stacks[i].push("From previous event:");
stacks[i] = stacks[i].join("\n");
}
if (i < stacks.length) {
stacks[i] = stacks[i].join("\n");
}
return message + "\n" + stacks.join("\n");
}
function removeDuplicateOrEmptyJumps(stacks) {
for (var i = 0; i < stacks.length; ++i) {
if (stacks[i].length === 0 ||
((i + 1 < stacks.length) && stacks[i][0] === stacks[i+1][0])) {
stacks.splice(i, 1);
i--;
}
}
}
function removeCommonRoots(stacks) {
var current = stacks[0];
for (var i = 1; i < stacks.length; ++i) {
var prev = stacks[i];
var currentLastIndex = current.length - 1;
var currentLastLine = current[currentLastIndex];
var commonRootMeetPoint = -1;
for (var j = prev.length - 1; j >= 0; --j) {
if (prev[j] === currentLastLine) {
commonRootMeetPoint = j;
break;
}
}
for (var j = commonRootMeetPoint; j >= 0; --j) {
var line = prev[j];
if (current[currentLastIndex] === line) {
current.pop();
currentLastIndex--;
} else {
break;
}
}
current = prev;
}
}
function cleanStack(stack) {
var ret = [];
for (var i = 0; i < stack.length; ++i) {
var line = stack[i];
var isTraceLine = stackFramePattern.test(line) ||
" (No stack trace)" === line;
var isInternalFrame = isTraceLine && shouldIgnore(line);
if (isTraceLine && !isInternalFrame) {
if (indentStackFrames && line.charAt(0) !== " ") {
line = " " + line;
}
ret.push(line);
}
}
return ret;
}
function stackFramesAsArray(error) {
var stack = error.stack.replace(/\s+$/g, "").split("\n");
for (var i = 0; i < stack.length; ++i) {
var line = stack[i];
if (" (No stack trace)" === line || stackFramePattern.test(line)) {
break;
}
}
if (i > 0) {
stack = stack.slice(i);
}
return stack;
}
CapturedTrace.parseStackAndMessage = function(error) {
var stack = error.stack;
var message = error.toString();
stack = typeof stack === "string" && stack.length > 0
? stackFramesAsArray(error) : [" (No stack trace)"];
return {
message: message,
stack: cleanStack(stack)
};
};
CapturedTrace.formatAndLogError = function(error, title) {
if (typeof console !== "undefined") {
var message;
if (typeof error === "object" || typeof error === "function") {
var stack = error.stack;
message = title + formatStack(stack, error);
} else {
message = title + String(error);
}
if (typeof warn === "function") {
warn(message);
} else if (typeof console.log === "function" ||
typeof console.log === "object") {
console.log(message);
}
}
};
CapturedTrace.unhandledRejection = function (reason) {
CapturedTrace.formatAndLogError(reason, "^--- With additional stack trace: ");
};
CapturedTrace.isSupported = function () {
return typeof captureStackTrace === "function";
};
CapturedTrace.fireRejectionEvent =
function(name, localHandler, reason, promise) {
var localEventFired = false;
try {
if (typeof localHandler === "function") {
localEventFired = true;
if (name === "rejectionHandled") {
localHandler(promise);
} else {
localHandler(reason, promise);
}
}
} catch (e) {
async.throwLater(e);
}
var globalEventFired = false;
try {
globalEventFired = fireGlobalEvent(name, reason, promise);
} catch (e) {
globalEventFired = true;
async.throwLater(e);
}
var domEventFired = false;
if (fireDomEvent) {
try {
domEventFired = fireDomEvent(name.toLowerCase(), {
reason: reason,
promise: promise
});
} catch (e) {
domEventFired = true;
async.throwLater(e);
}
}
if (!globalEventFired && !localEventFired && !domEventFired &&
name === "unhandledRejection") {
CapturedTrace.formatAndLogError(reason, "Unhandled rejection ");
}
};
function formatNonError(obj) {
var str;
if (typeof obj === "function") {
str = "[function " +
(obj.name || "anonymous") +
"]";
} else {
str = obj.toString();
var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/;
if (ruselessToString.test(str)) {
try {
var newStr = JSON.stringify(obj);
str = newStr;
}
catch(e) {
}
}
if (str.length === 0) {
str = "(empty array)";
}
}
return ("(<" + snip(str) + ">, no stack trace)");
}
function snip(str) {
var maxChars = 41;
if (str.length < maxChars) {
return str;
}
return str.substr(0, maxChars - 3) + "...";
}
var shouldIgnore = function() { return false; };
var parseLineInfoRegex = /[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;
function parseLineInfo(line) {
var matches = line.match(parseLineInfoRegex);
if (matches) {
return {
fileName: matches[1],
line: parseInt(matches[2], 10)
};
}
}
CapturedTrace.setBounds = function(firstLineError, lastLineError) {
if (!CapturedTrace.isSupported()) return;
var firstStackLines = firstLineError.stack.split("\n");
var lastStackLines = lastLineError.stack.split("\n");
var firstIndex = -1;
var lastIndex = -1;
var firstFileName;
var lastFileName;
for (var i = 0; i < firstStackLines.length; ++i) {
var result = parseLineInfo(firstStackLines[i]);
if (result) {
firstFileName = result.fileName;
firstIndex = result.line;
break;
}
}
for (var i = 0; i < lastStackLines.length; ++i) {
var result = parseLineInfo(lastStackLines[i]);
if (result) {
lastFileName = result.fileName;
lastIndex = result.line;
break;
}
}
if (firstIndex < 0 || lastIndex < 0 || !firstFileName || !lastFileName ||
firstFileName !== lastFileName || firstIndex >= lastIndex) {
return;
}
shouldIgnore = function(line) {
if (bluebirdFramePattern.test(line)) return true;
var info = parseLineInfo(line);
if (info) {
if (info.fileName === firstFileName &&
(firstIndex <= info.line && info.line <= lastIndex)) {
return true;
}
}
return false;
};
};
var captureStackTrace = (function stackDetection() {
var v8stackFramePattern = /^\s*at\s*/;
var v8stackFormatter = function(stack, error) {
if (typeof stack === "string") return stack;
if (error.name !== undefined &&
error.message !== undefined) {
return error.toString();
}
return formatNonError(error);
};
if (typeof Error.stackTraceLimit === "number" &&
typeof Error.captureStackTrace === "function") {
Error.stackTraceLimit = Error.stackTraceLimit + 6;
stackFramePattern = v8stackFramePattern;
formatStack = v8stackFormatter;
var captureStackTrace = Error.captureStackTrace;
shouldIgnore = function(line) {
return bluebirdFramePattern.test(line);
};
return function(receiver, ignoreUntil) {
Error.stackTraceLimit = Error.stackTraceLimit + 6;
captureStackTrace(receiver, ignoreUntil);
Error.stackTraceLimit = Error.stackTraceLimit - 6;
};
}
var err = new Error();
if (typeof err.stack === "string" &&
err.stack.split("\n")[0].indexOf("stackDetection@") >= 0) {
stackFramePattern = /@/;
formatStack = v8stackFormatter;
indentStackFrames = true;
return function captureStackTrace(o) {
o.stack = new Error().stack;
};
}
var hasStackAfterThrow;
try { throw new Error(); }
catch(e) {
hasStackAfterThrow = ("stack" in e);
}
if (!("stack" in err) && hasStackAfterThrow &&
typeof Error.stackTraceLimit === "number") {
stackFramePattern = v8stackFramePattern;
formatStack = v8stackFormatter;
return function captureStackTrace(o) {
Error.stackTraceLimit = Error.stackTraceLimit + 6;
try { throw new Error(); }
catch(e) { o.stack = e.stack; }
Error.stackTraceLimit = Error.stackTraceLimit - 6;
};
}
formatStack = function(stack, error) {
if (typeof stack === "string") return stack;
if ((typeof error === "object" ||
typeof error === "function") &&
error.name !== undefined &&
error.message !== undefined) {
return error.toString();
}
return formatNonError(error);
};
return null;
})([]);
var fireDomEvent;
var fireGlobalEvent = (function() {
if (util.isNode) {
return function(name, reason, promise) {
if (name === "rejectionHandled") {
return process.emit(name, promise);
} else {
return process.emit(name, reason, promise);
}
};
} else {
var customEventWorks = false;
var anyEventWorks = true;
try {
var ev = new self.CustomEvent("test");
customEventWorks = ev instanceof CustomEvent;
} catch (e) {}
if (!customEventWorks) {
try {
var event = document.createEvent("CustomEvent");
event.initCustomEvent("testingtheevent", false, true, {});
self.dispatchEvent(event);
} catch (e) {
anyEventWorks = false;
}
}
if (anyEventWorks) {
fireDomEvent = function(type, detail) {
var event;
if (customEventWorks) {
event = new self.CustomEvent(type, {
detail: detail,
bubbles: false,
cancelable: true
});
} else if (self.dispatchEvent) {
event = document.createEvent("CustomEvent");
event.initCustomEvent(type, false, true, detail);
}
return event ? !self.dispatchEvent(event) : false;
};
}
var toWindowMethodNameMap = {};
toWindowMethodNameMap["unhandledRejection"] = ("on" +
"unhandledRejection").toLowerCase();
toWindowMethodNameMap["rejectionHandled"] = ("on" +
"rejectionHandled").toLowerCase();
return function(name, reason, promise) {
var methodName = toWindowMethodNameMap[name];
var method = self[methodName];
if (!method) return false;
if (name === "rejectionHandled") {
method.call(self, promise);
} else {
method.call(self, reason, promise);
}
return true;
};
}
})();
if (typeof console !== "undefined" && typeof console.warn !== "undefined") {
warn = function (message) {
console.warn(message);
};
if (util.isNode && process.stderr.isTTY) {
warn = function(message) {
process.stderr.write("\u001b[31m" + message + "\u001b[39m\n");
};
} else if (!util.isNode && typeof (new Error().stack) === "string") {
warn = function(message) {
console.warn("%c" + message, "color: red");
};
}
}
return CapturedTrace;
};
},{"./async.js":2,"./util.js":38}],8:[function(_dereq_,module,exports){
"use strict";
module.exports = function(NEXT_FILTER) {
var util = _dereq_("./util.js");
var errors = _dereq_("./errors.js");
var tryCatch = util.tryCatch;
var errorObj = util.errorObj;
var keys = _dereq_("./es5.js").keys;
var TypeError = errors.TypeError;
function CatchFilter(instances, callback, promise) {
this._instances = instances;
this._callback = callback;
this._promise = promise;
}
function safePredicate(predicate, e) {
var safeObject = {};
var retfilter = tryCatch(predicate).call(safeObject, e);
if (retfilter === errorObj) return retfilter;
var safeKeys = keys(safeObject);
if (safeKeys.length) {
errorObj.e = new TypeError("Catch filter must inherit from Error or be a simple predicate function\u000a\u000a See http://goo.gl/o84o68\u000a");
return errorObj;
}
return retfilter;
}
CatchFilter.prototype.doFilter = function (e) {
var cb = this._callback;
var promise = this._promise;
var boundTo = promise._boundValue();
for (var i = 0, len = this._instances.length; i < len; ++i) {
var item = this._instances[i];
var itemIsErrorType = item === Error ||
(item != null && item.prototype instanceof Error);
if (itemIsErrorType && e instanceof item) {
var ret = tryCatch(cb).call(boundTo, e);
if (ret === errorObj) {
NEXT_FILTER.e = ret.e;
return NEXT_FILTER;
}
return ret;
} else if (typeof item === "function" && !itemIsErrorType) {
var shouldHandle = safePredicate(item, e);
if (shouldHandle === errorObj) {
e = errorObj.e;
break;
} else if (shouldHandle) {
var ret = tryCatch(cb).call(boundTo, e);
if (ret === errorObj) {
NEXT_FILTER.e = ret.e;
return NEXT_FILTER;
}
return ret;
}
}
}
NEXT_FILTER.e = e;
return NEXT_FILTER;
};
return CatchFilter;
};
},{"./errors.js":13,"./es5.js":14,"./util.js":38}],9:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise, CapturedTrace, isDebugging) {
var contextStack = [];
function Context() {
this._trace = new CapturedTrace(peekContext());
}
Context.prototype._pushContext = function () {
if (!isDebugging()) return;
if (this._trace !== undefined) {
contextStack.push(this._trace);
}
};
Context.prototype._popContext = function () {
if (!isDebugging()) return;
if (this._trace !== undefined) {
contextStack.pop();
}
};
function createContext() {
if (isDebugging()) return new Context();
}
function peekContext() {
var lastIndex = contextStack.length - 1;
if (lastIndex >= 0) {
return contextStack[lastIndex];
}
return undefined;
}
Promise.prototype._peekContext = peekContext;
Promise.prototype._pushContext = Context.prototype._pushContext;
Promise.prototype._popContext = Context.prototype._popContext;
return createContext;
};
},{}],10:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise, CapturedTrace) {
var getDomain = Promise._getDomain;
var async = _dereq_("./async.js");
var Warning = _dereq_("./errors.js").Warning;
var util = _dereq_("./util.js");
var canAttachTrace = util.canAttachTrace;
var unhandledRejectionHandled;
var possiblyUnhandledRejection;
var debugging = false || (util.isNode &&
(!!process.env["BLUEBIRD_DEBUG"] ||
process.env["NODE_ENV"] === "development"));
if (debugging) {
async.disableTrampolineIfNecessary();
}
Promise.prototype._ignoreRejections = function() {
this._unsetRejectionIsUnhandled();
this._bitField = this._bitField | 16777216;
};
Promise.prototype._ensurePossibleRejectionHandled = function () {
if ((this._bitField & 16777216) !== 0) return;
this._setRejectionIsUnhandled();
async.invokeLater(this._notifyUnhandledRejection, this, undefined);
};
Promise.prototype._notifyUnhandledRejectionIsHandled = function () {
CapturedTrace.fireRejectionEvent("rejectionHandled",
unhandledRejectionHandled, undefined, this);
};
Promise.prototype._notifyUnhandledRejection = function () {
if (this._isRejectionUnhandled()) {
var reason = this._getCarriedStackTrace() || this._settledValue;
this._setUnhandledRejectionIsNotified();
CapturedTrace.fireRejectionEvent("unhandledRejection",
possiblyUnhandledRejection, reason, this);
}
};
Promise.prototype._setUnhandledRejectionIsNotified = function () {
this._bitField = this._bitField | 524288;
};
Promise.prototype._unsetUnhandledRejectionIsNotified = function () {
this._bitField = this._bitField & (~524288);
};
Promise.prototype._isUnhandledRejectionNotified = function () {
return (this._bitField & 524288) > 0;
};
Promise.prototype._setRejectionIsUnhandled = function () {
this._bitField = this._bitField | 2097152;
};
Promise.prototype._unsetRejectionIsUnhandled = function () {
this._bitField = this._bitField & (~2097152);
if (this._isUnhandledRejectionNotified()) {
this._unsetUnhandledRejectionIsNotified();
this._notifyUnhandledRejectionIsHandled();
}
};
Promise.prototype._isRejectionUnhandled = function () {
return (this._bitField & 2097152) > 0;
};
Promise.prototype._setCarriedStackTrace = function (capturedTrace) {
this._bitField = this._bitField | 1048576;
this._fulfillmentHandler0 = capturedTrace;
};
Promise.prototype._isCarryingStackTrace = function () {
return (this._bitField & 1048576) > 0;
};
Promise.prototype._getCarriedStackTrace = function () {
return this._isCarryingStackTrace()
? this._fulfillmentHandler0
: undefined;
};
Promise.prototype._captureStackTrace = function (force) {
if (debugging || (force && CapturedTrace.isSupported())) {
this._traceForced = force;
this._trace = new CapturedTrace(this._peekContext());
}
return this;
};
Promise.prototype._attachExtraTrace = function (error, ignoreSelf) {
if ((debugging || this._traceForced) && canAttachTrace(error)) {
var trace = this._trace;
if (trace !== undefined) {
if (ignoreSelf) trace = trace._parent;
}
if (trace !== undefined) {
trace.attachExtraTrace(error);
} else if (!error.__stackCleaned__) {
var parsed = CapturedTrace.parseStackAndMessage(error);
util.notEnumerableProp(error, "stack",
parsed.message + "\n" + parsed.stack.join("\n"));
util.notEnumerableProp(error, "__stackCleaned__", true);
}
}
};
Promise.prototype._warn = function(message) {
var warning = new Warning(message);
var ctx = this._peekContext();
if (ctx) {
ctx.attachExtraTrace(warning);
} else {
var parsed = CapturedTrace.parseStackAndMessage(warning);
warning.stack = parsed.message + "\n" + parsed.stack.join("\n");
}
CapturedTrace.formatAndLogError(warning, "");
};
Promise.onPossiblyUnhandledRejection = function (fn) {
var domain = getDomain();
possiblyUnhandledRejection =
typeof fn === "function" ? (domain === null ? fn : domain.bind(fn))
: undefined;
};
Promise.onUnhandledRejectionHandled = function (fn) {
var domain = getDomain();
unhandledRejectionHandled =
typeof fn === "function" ? (domain === null ? fn : domain.bind(fn))
: undefined;
};
Promise.longStackTraces = function () {
if (async.haveItemsQueued() &&
debugging === false
) {
throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/DT1qyG\u000a");
}
debugging = CapturedTrace.isSupported();
if (debugging) {
async.disableTrampolineIfNecessary();
}
};
Promise.hasLongStackTraces = function () {
return debugging && CapturedTrace.isSupported();
};
if (!CapturedTrace.isSupported()) {
Promise.longStackTraces = function(){};
debugging = false;
}
return function() {
return debugging;
};
};
},{"./async.js":2,"./errors.js":13,"./util.js":38}],11:[function(_dereq_,module,exports){
"use strict";
var util = _dereq_("./util.js");
var isPrimitive = util.isPrimitive;
module.exports = function(Promise) {
var returner = function () {
return this;
};
var thrower = function () {
throw this;
};
var returnUndefined = function() {};
var throwUndefined = function() {
throw undefined;
};
var wrapper = function (value, action) {
if (action === 1) {
return function () {
throw value;
};
} else if (action === 2) {
return function () {
return value;
};
}
};
Promise.prototype["return"] =
Promise.prototype.thenReturn = function (value) {
if (value === undefined) return this.then(returnUndefined);
if (isPrimitive(value)) {
return this._then(
wrapper(value, 2),
undefined,
undefined,
undefined,
undefined
);
}
return this._then(returner, undefined, undefined, value, undefined);
};
Promise.prototype["throw"] =
Promise.prototype.thenThrow = function (reason) {
if (reason === undefined) return this.then(throwUndefined);
if (isPrimitive(reason)) {
return this._then(
wrapper(reason, 1),
undefined,
undefined,
undefined,
undefined
);
}
return this._then(thrower, undefined, undefined, reason, undefined);
};
};
},{"./util.js":38}],12:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise, INTERNAL) {
var PromiseReduce = Promise.reduce;
Promise.prototype.each = function (fn) {
return PromiseReduce(this, fn, null, INTERNAL);
};
Promise.each = function (promises, fn) {
return PromiseReduce(promises, fn, null, INTERNAL);
};
};
},{}],13:[function(_dereq_,module,exports){
"use strict";
var es5 = _dereq_("./es5.js");
var Objectfreeze = es5.freeze;
var util = _dereq_("./util.js");
var inherits = util.inherits;
var notEnumerableProp = util.notEnumerableProp;
function subError(nameProperty, defaultMessage) {
function SubError(message) {
if (!(this instanceof SubError)) return new SubError(message);
notEnumerableProp(this, "message",
typeof message === "string" ? message : defaultMessage);
notEnumerableProp(this, "name", nameProperty);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
} else {
Error.call(this);
}
}
inherits(SubError, Error);
return SubError;
}
var _TypeError, _RangeError;
var Warning = subError("Warning", "warning");
var CancellationError = subError("CancellationError", "cancellation error");
var TimeoutError = subError("TimeoutError", "timeout error");
var AggregateError = subError("AggregateError", "aggregate error");
try {
_TypeError = TypeError;
_RangeError = RangeError;
} catch(e) {
_TypeError = subError("TypeError", "type error");
_RangeError = subError("RangeError", "range error");
}
var methods = ("join pop push shift unshift slice filter forEach some " +
"every map indexOf lastIndexOf reduce reduceRight sort reverse").split(" ");
for (var i = 0; i < methods.length; ++i) {
if (typeof Array.prototype[methods[i]] === "function") {
AggregateError.prototype[methods[i]] = Array.prototype[methods[i]];
}
}
es5.defineProperty(AggregateError.prototype, "length", {
value: 0,
configurable: false,
writable: true,
enumerable: true
});
AggregateError.prototype["isOperational"] = true;
var level = 0;
AggregateError.prototype.toString = function() {
var indent = Array(level * 4 + 1).join(" ");
var ret = "\n" + indent + "AggregateError of:" + "\n";
level++;
indent = Array(level * 4 + 1).join(" ");
for (var i = 0; i < this.length; ++i) {
var str = this[i] === this ? "[Circular AggregateError]" : this[i] + "";
var lines = str.split("\n");
for (var j = 0; j < lines.length; ++j) {
lines[j] = indent + lines[j];
}
str = lines.join("\n");
ret += str + "\n";
}
level--;
return ret;
};
function OperationalError(message) {
if (!(this instanceof OperationalError))
return new OperationalError(message);
notEnumerableProp(this, "name", "OperationalError");
notEnumerableProp(this, "message", message);
this.cause = message;
this["isOperational"] = true;
if (message instanceof Error) {
notEnumerableProp(this, "message", message.message);
notEnumerableProp(this, "stack", message.stack);
} else if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
}
}
inherits(OperationalError, Error);
var errorTypes = Error["__BluebirdErrorTypes__"];
if (!errorTypes) {
errorTypes = Objectfreeze({
CancellationError: CancellationError,
TimeoutError: TimeoutError,
OperationalError: OperationalError,
RejectionError: OperationalError,
AggregateError: AggregateError
});
notEnumerableProp(Error, "__BluebirdErrorTypes__", errorTypes);
}
module.exports = {
Error: Error,
TypeError: _TypeError,
RangeError: _RangeError,
CancellationError: errorTypes.CancellationError,
OperationalError: errorTypes.OperationalError,
TimeoutError: errorTypes.TimeoutError,
AggregateError: errorTypes.AggregateError,
Warning: Warning
};
},{"./es5.js":14,"./util.js":38}],14:[function(_dereq_,module,exports){
var isES5 = (function(){
"use strict";
return this === undefined;
})();
if (isES5) {
module.exports = {
freeze: Object.freeze,
defineProperty: Object.defineProperty,
getDescriptor: Object.getOwnPropertyDescriptor,
keys: Object.keys,
names: Object.getOwnPropertyNames,
getPrototypeOf: Object.getPrototypeOf,
isArray: Array.isArray,
isES5: isES5,
propertyIsWritable: function(obj, prop) {
var descriptor = Object.getOwnPropertyDescriptor(obj, prop);
return !!(!descriptor || descriptor.writable || descriptor.set);
}
};
} else {
var has = {}.hasOwnProperty;
var str = {}.toString;
var proto = {}.constructor.prototype;
var ObjectKeys = function (o) {
var ret = [];
for (var key in o) {
if (has.call(o, key)) {
ret.push(key);
}
}
return ret;
};
var ObjectGetDescriptor = function(o, key) {
return {value: o[key]};
};
var ObjectDefineProperty = function (o, key, desc) {
o[key] = desc.value;
return o;
};
var ObjectFreeze = function (obj) {
return obj;
};
var ObjectGetPrototypeOf = function (obj) {
try {
return Object(obj).constructor.prototype;
}
catch (e) {
return proto;
}
};
var ArrayIsArray = function (obj) {
try {
return str.call(obj) === "[object Array]";
}
catch(e) {
return false;
}
};
module.exports = {
isArray: ArrayIsArray,
keys: ObjectKeys,
names: ObjectKeys,
defineProperty: ObjectDefineProperty,
getDescriptor: ObjectGetDescriptor,
freeze: ObjectFreeze,
getPrototypeOf: ObjectGetPrototypeOf,
isES5: isES5,
propertyIsWritable: function() {
return true;
}
};
}
},{}],15:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise, INTERNAL) {
var PromiseMap = Promise.map;
Promise.prototype.filter = function (fn, options) {
return PromiseMap(this, fn, options, INTERNAL);
};
Promise.filter = function (promises, fn, options) {
return PromiseMap(promises, fn, options, INTERNAL);
};
};
},{}],16:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise, NEXT_FILTER, tryConvertToPromise) {
var util = _dereq_("./util.js");
var isPrimitive = util.isPrimitive;
var thrower = util.thrower;
function returnThis() {
return this;
}
function throwThis() {
throw this;
}
function return$(r) {
return function() {
return r;
};
}
function throw$(r) {
return function() {
throw r;
};
}
function promisedFinally(ret, reasonOrValue, isFulfilled) {
var then;
if (isPrimitive(reasonOrValue)) {
then = isFulfilled ? return$(reasonOrValue) : throw$(reasonOrValue);
} else {
then = isFulfilled ? returnThis : throwThis;
}
return ret._then(then, thrower, undefined, reasonOrValue, undefined);
}
function finallyHandler(reasonOrValue) {
var promise = this.promise;
var handler = this.handler;
var ret = promise._isBound()
? handler.call(promise._boundValue())
: handler();
if (ret !== undefined) {
var maybePromise = tryConvertToPromise(ret, promise);
if (maybePromise instanceof Promise) {
maybePromise = maybePromise._target();
return promisedFinally(maybePromise, reasonOrValue,
promise.isFulfilled());
}
}
if (promise.isRejected()) {
NEXT_FILTER.e = reasonOrValue;
return NEXT_FILTER;
} else {
return reasonOrValue;
}
}
function tapHandler(value) {
var promise = this.promise;
var handler = this.handler;
var ret = promise._isBound()
? handler.call(promise._boundValue(), value)
: handler(value);
if (ret !== undefined) {
var maybePromise = tryConvertToPromise(ret, promise);
if (maybePromise instanceof Promise) {
maybePromise = maybePromise._target();
return promisedFinally(maybePromise, value, true);
}
}
return value;
}
Promise.prototype._passThroughHandler = function (handler, isFinally) {
if (typeof handler !== "function") return this.then();
var promiseAndHandler = {
promise: this,
handler: handler
};
return this._then(
isFinally ? finallyHandler : tapHandler,
isFinally ? finallyHandler : undefined, undefined,
promiseAndHandler, undefined);
};
Promise.prototype.lastly =
Promise.prototype["finally"] = function (handler) {
return this._passThroughHandler(handler, true);
};
Promise.prototype.tap = function (handler) {
return this._passThroughHandler(handler, false);
};
};
},{"./util.js":38}],17:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise,
apiRejection,
INTERNAL,
tryConvertToPromise) {
var errors = _dereq_("./errors.js");
var TypeError = errors.TypeError;
var util = _dereq_("./util.js");
var errorObj = util.errorObj;
var tryCatch = util.tryCatch;
var yieldHandlers = [];
function promiseFromYieldHandler(value, yieldHandlers, traceParent) {
for (var i = 0; i < yieldHandlers.length; ++i) {
traceParent._pushContext();
var result = tryCatch(yieldHandlers[i])(value);
traceParent._popContext();
if (result === errorObj) {
traceParent._pushContext();
var ret = Promise.reject(errorObj.e);
traceParent._popContext();
return ret;
}
var maybePromise = tryConvertToPromise(result, traceParent);
if (maybePromise instanceof Promise) return maybePromise;
}
return null;
}
function PromiseSpawn(generatorFunction, receiver, yieldHandler, stack) {
var promise = this._promise = new Promise(INTERNAL);
promise._captureStackTrace();
this._stack = stack;
this._generatorFunction = generatorFunction;
this._receiver = receiver;
this._generator = undefined;
this._yieldHandlers = typeof yieldHandler === "function"
? [yieldHandler].concat(yieldHandlers)
: yieldHandlers;
}
PromiseSpawn.prototype.promise = function () {
return this._promise;
};
PromiseSpawn.prototype._run = function () {
this._generator = this._generatorFunction.call(this._receiver);
this._receiver =
this._generatorFunction = undefined;
this._next(undefined);
};
PromiseSpawn.prototype._continue = function (result) {
if (result === errorObj) {
return this._promise._rejectCallback(result.e, false, true);
}
var value = result.value;
if (result.done === true) {
this._promise._resolveCallback(value);
} else {
var maybePromise = tryConvertToPromise(value, this._promise);
if (!(maybePromise instanceof Promise)) {
maybePromise =
promiseFromYieldHandler(maybePromise,
this._yieldHandlers,
this._promise);
if (maybePromise === null) {
this._throw(
new TypeError(
"A value %s was yielded that could not be treated as a promise\u000a\u000a See http://goo.gl/4Y4pDk\u000a\u000a".replace("%s", value) +
"From coroutine:\u000a" +
this._stack.split("\n").slice(1, -7).join("\n")
)
);
return;
}
}
maybePromise._then(
this._next,
this._throw,
undefined,
this,
null
);
}
};
PromiseSpawn.prototype._throw = function (reason) {
this._promise._attachExtraTrace(reason);
this._promise._pushContext();
var result = tryCatch(this._generator["throw"])
.call(this._generator, reason);
this._promise._popContext();
this._continue(result);
};
PromiseSpawn.prototype._next = function (value) {
this._promise._pushContext();
var result = tryCatch(this._generator.next).call(this._generator, value);
this._promise._popContext();
this._continue(result);
};
Promise.coroutine = function (generatorFunction, options) {
if (typeof generatorFunction !== "function") {
throw new TypeError("generatorFunction must be a function\u000a\u000a See http://goo.gl/6Vqhm0\u000a");
}
var yieldHandler = Object(options).yieldHandler;
var PromiseSpawn$ = PromiseSpawn;
var stack = new Error().stack;
return function () {
var generator = generatorFunction.apply(this, arguments);
var spawn = new PromiseSpawn$(undefined, undefined, yieldHandler,
stack);
spawn._generator = generator;
spawn._next(undefined);
return spawn.promise();
};
};
Promise.coroutine.addYieldHandler = function(fn) {
if (typeof fn !== "function") throw new TypeError("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a");
yieldHandlers.push(fn);
};
Promise.spawn = function (generatorFunction) {
if (typeof generatorFunction !== "function") {
return apiRejection("generatorFunction must be a function\u000a\u000a See http://goo.gl/6Vqhm0\u000a");
}
var spawn = new PromiseSpawn(generatorFunction, this);
var ret = spawn.promise();
spawn._run(Promise.spawn);
return ret;
};
};
},{"./errors.js":13,"./util.js":38}],18:[function(_dereq_,module,exports){
"use strict";
module.exports =
function(Promise, PromiseArray, tryConvertToPromise, INTERNAL) {
var util = _dereq_("./util.js");
var canEvaluate = util.canEvaluate;
var tryCatch = util.tryCatch;
var errorObj = util.errorObj;
var reject;
if (!true) {
if (canEvaluate) {
var thenCallback = function(i) {
return new Function("value", "holder", " \n\
'use strict'; \n\
holder.pIndex = value; \n\
holder.checkFulfillment(this); \n\
".replace(/Index/g, i));
};
var caller = function(count) {
var values = [];
for (var i = 1; i <= count; ++i) values.push("holder.p" + i);
return new Function("holder", " \n\
'use strict'; \n\
var callback = holder.fn; \n\
return callback(values); \n\
".replace(/values/g, values.join(", ")));
};
var thenCallbacks = [];
var callers = [undefined];
for (var i = 1; i <= 5; ++i) {
thenCallbacks.push(thenCallback(i));
callers.push(caller(i));
}
var Holder = function(total, fn) {
this.p1 = this.p2 = this.p3 = this.p4 = this.p5 = null;
this.fn = fn;
this.total = total;
this.now = 0;
};
Holder.prototype.callers = callers;
Holder.prototype.checkFulfillment = function(promise) {
var now = this.now;
now++;
var total = this.total;
if (now >= total) {
var handler = this.callers[total];
promise._pushContext();
var ret = tryCatch(handler)(this);
promise._popContext();
if (ret === errorObj) {
promise._rejectCallback(ret.e, false, true);
} else {
promise._resolveCallback(ret);
}
} else {
this.now = now;
}
};
var reject = function (reason) {
this._reject(reason);
};
}
}
Promise.join = function () {
var last = arguments.length - 1;
var fn;
if (last > 0 && typeof arguments[last] === "function") {
fn = arguments[last];
if (!true) {
if (last < 6 && canEvaluate) {
var ret = new Promise(INTERNAL);
ret._captureStackTrace();
var holder = new Holder(last, fn);
var callbacks = thenCallbacks;
for (var i = 0; i < last; ++i) {
var maybePromise = tryConvertToPromise(arguments[i], ret);
if (maybePromise instanceof Promise) {
maybePromise = maybePromise._target();
if (maybePromise._isPending()) {
maybePromise._then(callbacks[i], reject,
undefined, ret, holder);
} else if (maybePromise._isFulfilled()) {
callbacks[i].call(ret,
maybePromise._value(), holder);
} else {
ret._reject(maybePromise._reason());
}
} else {
callbacks[i].call(ret, maybePromise, holder);
}
}
return ret;
}
}
}
var $_len = arguments.length;var args = new Array($_len); for(var $_i = 0; $_i < $_len; ++$_i) {args[$_i] = arguments[$_i];}
if (fn) args.pop();
var ret = new PromiseArray(args).promise();
return fn !== undefined ? ret.spread(fn) : ret;
};
};
},{"./util.js":38}],19:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise,
PromiseArray,
apiRejection,
tryConvertToPromise,
INTERNAL) {
var getDomain = Promise._getDomain;
var async = _dereq_("./async.js");
var util = _dereq_("./util.js");
var tryCatch = util.tryCatch;
var errorObj = util.errorObj;
var PENDING = {};
var EMPTY_ARRAY = [];
function MappingPromiseArray(promises, fn, limit, _filter) {
this.constructor$(promises);
this._promise._captureStackTrace();
var domain = getDomain();
this._callback = domain === null ? fn : domain.bind(fn);
this._preservedValues = _filter === INTERNAL
? new Array(this.length())
: null;
this._limit = limit;
this._inFlight = 0;
this._queue = limit >= 1 ? [] : EMPTY_ARRAY;
async.invoke(init, this, undefined);
}
util.inherits(MappingPromiseArray, PromiseArray);
function init() {this._init$(undefined, -2);}
MappingPromiseArray.prototype._init = function () {};
MappingPromiseArray.prototype._promiseFulfilled = function (value, index) {
var values = this._values;
var length = this.length();
var preservedValues = this._preservedValues;
var limit = this._limit;
if (values[index] === PENDING) {
values[index] = value;
if (limit >= 1) {
this._inFlight--;
this._drainQueue();
if (this._isResolved()) return;
}
} else {
if (limit >= 1 && this._inFlight >= limit) {
values[index] = value;
this._queue.push(index);
return;
}
if (preservedValues !== null) preservedValues[index] = value;
var callback = this._callback;
var receiver = this._promise._boundValue();
this._promise._pushContext();
var ret = tryCatch(callback).call(receiver, value, index, length);
this._promise._popContext();
if (ret === errorObj) return this._reject(ret.e);
var maybePromise = tryConvertToPromise(ret, this._promise);
if (maybePromise instanceof Promise) {
maybePromise = maybePromise._target();
if (maybePromise._isPending()) {
if (limit >= 1) this._inFlight++;
values[index] = PENDING;
return maybePromise._proxyPromiseArray(this, index);
} else if (maybePromise._isFulfilled()) {
ret = maybePromise._value();
} else {
return this._reject(maybePromise._reason());
}
}
values[index] = ret;
}
var totalResolved = ++this._totalResolved;
if (totalResolved >= length) {
if (preservedValues !== null) {
this._filter(values, preservedValues);
} else {
this._resolve(values);
}
}
};
MappingPromiseArray.prototype._drainQueue = function () {
var queue = this._queue;
var limit = this._limit;
var values = this._values;
while (queue.length > 0 && this._inFlight < limit) {
if (this._isResolved()) return;
var index = queue.pop();
this._promiseFulfilled(values[index], index);
}
};
MappingPromiseArray.prototype._filter = function (booleans, values) {
var len = values.length;
var ret = new Array(len);
var j = 0;
for (var i = 0; i < len; ++i) {
if (booleans[i]) ret[j++] = values[i];
}
ret.length = j;
this._resolve(ret);
};
MappingPromiseArray.prototype.preservedValues = function () {
return this._preservedValues;
};
function map(promises, fn, options, _filter) {
var limit = typeof options === "object" && options !== null
? options.concurrency
: 0;
limit = typeof limit === "number" &&
isFinite(limit) && limit >= 1 ? limit : 0;
return new MappingPromiseArray(promises, fn, limit, _filter);
}
Promise.prototype.map = function (fn, options) {
if (typeof fn !== "function") return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a");
return map(this, fn, options, null).promise();
};
Promise.map = function (promises, fn, options, _filter) {
if (typeof fn !== "function") return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a");
return map(promises, fn, options, _filter).promise();
};
};
},{"./async.js":2,"./util.js":38}],20:[function(_dereq_,module,exports){
"use strict";
module.exports =
function(Promise, INTERNAL, tryConvertToPromise, apiRejection) {
var util = _dereq_("./util.js");
var tryCatch = util.tryCatch;
Promise.method = function (fn) {
if (typeof fn !== "function") {
throw new Promise.TypeError("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a");
}
return function () {
var ret = new Promise(INTERNAL);
ret._captureStackTrace();
ret._pushContext();
var value = tryCatch(fn).apply(this, arguments);
ret._popContext();
ret._resolveFromSyncValue(value);
return ret;
};
};
Promise.attempt = Promise["try"] = function (fn, args, ctx) {
if (typeof fn !== "function") {
return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a");
}
var ret = new Promise(INTERNAL);
ret._captureStackTrace();
ret._pushContext();
var value = util.isArray(args)
? tryCatch(fn).apply(ctx, args)
: tryCatch(fn).call(ctx, args);
ret._popContext();
ret._resolveFromSyncValue(value);
return ret;
};
Promise.prototype._resolveFromSyncValue = function (value) {
if (value === util.errorObj) {
this._rejectCallback(value.e, false, true);
} else {
this._resolveCallback(value, true);
}
};
};
},{"./util.js":38}],21:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise) {
var util = _dereq_("./util.js");
var async = _dereq_("./async.js");
var tryCatch = util.tryCatch;
var errorObj = util.errorObj;
function spreadAdapter(val, nodeback) {
var promise = this;
if (!util.isArray(val)) return successAdapter.call(promise, val, nodeback);
var ret =
tryCatch(nodeback).apply(promise._boundValue(), [null].concat(val));
if (ret === errorObj) {
async.throwLater(ret.e);
}
}
function successAdapter(val, nodeback) {
var promise = this;
var receiver = promise._boundValue();
var ret = val === undefined
? tryCatch(nodeback).call(receiver, null)
: tryCatch(nodeback).call(receiver, null, val);
if (ret === errorObj) {
async.throwLater(ret.e);
}
}
function errorAdapter(reason, nodeback) {
var promise = this;
if (!reason) {
var target = promise._target();
var newReason = target._getCarriedStackTrace();
newReason.cause = reason;
reason = newReason;
}
var ret = tryCatch(nodeback).call(promise._boundValue(), reason);
if (ret === errorObj) {
async.throwLater(ret.e);
}
}
Promise.prototype.asCallback =
Promise.prototype.nodeify = function (nodeback, options) {
if (typeof nodeback == "function") {
var adapter = successAdapter;
if (options !== undefined && Object(options).spread) {
adapter = spreadAdapter;
}
this._then(
adapter,
errorAdapter,
undefined,
this,
nodeback
);
}
return this;
};
};
},{"./async.js":2,"./util.js":38}],22:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise, PromiseArray) {
var util = _dereq_("./util.js");
var async = _dereq_("./async.js");
var tryCatch = util.tryCatch;
var errorObj = util.errorObj;
Promise.prototype.progressed = function (handler) {
return this._then(undefined, undefined, handler, undefined, undefined);
};
Promise.prototype._progress = function (progressValue) {
if (this._isFollowingOrFulfilledOrRejected()) return;
this._target()._progressUnchecked(progressValue);
};
Promise.prototype._progressHandlerAt = function (index) {
return index === 0
? this._progressHandler0
: this[(index << 2) + index - 5 + 2];
};
Promise.prototype._doProgressWith = function (progression) {
var progressValue = progression.value;
var handler = progression.handler;
var promise = progression.promise;
var receiver = progression.receiver;
var ret = tryCatch(handler).call(receiver, progressValue);
if (ret === errorObj) {
if (ret.e != null &&
ret.e.name !== "StopProgressPropagation") {
var trace = util.canAttachTrace(ret.e)
? ret.e : new Error(util.toString(ret.e));
promise._attachExtraTrace(trace);
promise._progress(ret.e);
}
} else if (ret instanceof Promise) {
ret._then(promise._progress, null, null, promise, undefined);
} else {
promise._progress(ret);
}
};
Promise.prototype._progressUnchecked = function (progressValue) {
var len = this._length();
var progress = this._progress;
for (var i = 0; i < len; i++) {
var handler = this._progressHandlerAt(i);
var promise = this._promiseAt(i);
if (!(promise instanceof Promise)) {
var receiver = this._receiverAt(i);
if (typeof handler === "function") {
handler.call(receiver, progressValue, promise);
} else if (receiver instanceof PromiseArray &&
!receiver._isResolved()) {
receiver._promiseProgressed(progressValue, promise);
}
continue;
}
if (typeof handler === "function") {
async.invoke(this._doProgressWith, this, {
handler: handler,
promise: promise,
receiver: this._receiverAt(i),
value: progressValue
});
} else {
async.invoke(progress, promise, progressValue);
}
}
};
};
},{"./async.js":2,"./util.js":38}],23:[function(_dereq_,module,exports){
"use strict";
module.exports = function() {
var makeSelfResolutionError = function () {
return new TypeError("circular promise resolution chain\u000a\u000a See http://goo.gl/LhFpo0\u000a");
};
var reflect = function() {
return new Promise.PromiseInspection(this._target());
};
var apiRejection = function(msg) {
return Promise.reject(new TypeError(msg));
};
var util = _dereq_("./util.js");
var getDomain;
if (util.isNode) {
getDomain = function() {
var ret = process.domain;
if (ret === undefined) ret = null;
return ret;
};
} else {
getDomain = function() {
return null;
};
}
util.notEnumerableProp(Promise, "_getDomain", getDomain);
var async = _dereq_("./async.js");
var errors = _dereq_("./errors.js");
var TypeError = Promise.TypeError = errors.TypeError;
Promise.RangeError = errors.RangeError;
Promise.CancellationError = errors.CancellationError;
Promise.TimeoutError = errors.TimeoutError;
Promise.OperationalError = errors.OperationalError;
Promise.RejectionError = errors.OperationalError;
Promise.AggregateError = errors.AggregateError;
var INTERNAL = function(){};
var APPLY = {};
var NEXT_FILTER = {e: null};
var tryConvertToPromise = _dereq_("./thenables.js")(Promise, INTERNAL);
var PromiseArray =
_dereq_("./promise_array.js")(Promise, INTERNAL,
tryConvertToPromise, apiRejection);
var CapturedTrace = _dereq_("./captured_trace.js")();
var isDebugging = _dereq_("./debuggability.js")(Promise, CapturedTrace);
/*jshint unused:false*/
var createContext =
_dereq_("./context.js")(Promise, CapturedTrace, isDebugging);
var CatchFilter = _dereq_("./catch_filter.js")(NEXT_FILTER);
var PromiseResolver = _dereq_("./promise_resolver.js");
var nodebackForPromise = PromiseResolver._nodebackForPromise;
var errorObj = util.errorObj;
var tryCatch = util.tryCatch;
function Promise(resolver) {
if (typeof resolver !== "function") {
throw new TypeError("the promise constructor requires a resolver function\u000a\u000a See http://goo.gl/EC22Yn\u000a");
}
if (this.constructor !== Promise) {
throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/KsIlge\u000a");
}
this._bitField = 0;
this._fulfillmentHandler0 = undefined;
this._rejectionHandler0 = undefined;
this._progressHandler0 = undefined;
this._promise0 = undefined;
this._receiver0 = undefined;
this._settledValue = undefined;
if (resolver !== INTERNAL) this._resolveFromResolver(resolver);
}
Promise.prototype.toString = function () {
return "[object Promise]";
};
Promise.prototype.caught = Promise.prototype["catch"] = function (fn) {
var len = arguments.length;
if (len > 1) {
var catchInstances = new Array(len - 1),
j = 0, i;
for (i = 0; i < len - 1; ++i) {
var item = arguments[i];
if (typeof item === "function") {
catchInstances[j++] = item;
} else {
return Promise.reject(
new TypeError("Catch filter must inherit from Error or be a simple predicate function\u000a\u000a See http://goo.gl/o84o68\u000a"));
}
}
catchInstances.length = j;
fn = arguments[i];
var catchFilter = new CatchFilter(catchInstances, fn, this);
return this._then(undefined, catchFilter.doFilter, undefined,
catchFilter, undefined);
}
return this._then(undefined, fn, undefined, undefined, undefined);
};
Promise.prototype.reflect = function () {
return this._then(reflect, reflect, undefined, this, undefined);
};
Promise.prototype.then = function (didFulfill, didReject, didProgress) {
if (isDebugging() && arguments.length > 0 &&
typeof didFulfill !== "function" &&
typeof didReject !== "function") {
var msg = ".then() only accepts functions but was passed: " +
util.classString(didFulfill);
if (arguments.length > 1) {
msg += ", " + util.classString(didReject);
}
this._warn(msg);
}
return this._then(didFulfill, didReject, didProgress,
undefined, undefined);
};
Promise.prototype.done = function (didFulfill, didReject, didProgress) {
var promise = this._then(didFulfill, didReject, didProgress,
undefined, undefined);
promise._setIsFinal();
};
Promise.prototype.spread = function (didFulfill, didReject) {
return this.all()._then(didFulfill, didReject, undefined, APPLY, undefined);
};
Promise.prototype.isCancellable = function () {
return !this.isResolved() &&
this._cancellable();
};
Promise.prototype.toJSON = function () {
var ret = {
isFulfilled: false,
isRejected: false,
fulfillmentValue: undefined,
rejectionReason: undefined
};
if (this.isFulfilled()) {
ret.fulfillmentValue = this.value();
ret.isFulfilled = true;
} else if (this.isRejected()) {
ret.rejectionReason = this.reason();
ret.isRejected = true;
}
return ret;
};
Promise.prototype.all = function () {
return new PromiseArray(this).promise();
};
Promise.prototype.error = function (fn) {
return this.caught(util.originatesFromRejection, fn);
};
Promise.is = function (val) {
return val instanceof Promise;
};
Promise.fromNode = function(fn) {
var ret = new Promise(INTERNAL);
var result = tryCatch(fn)(nodebackForPromise(ret));
if (result === errorObj) {
ret._rejectCallback(result.e, true, true);
}
return ret;
};
Promise.all = function (promises) {
return new PromiseArray(promises).promise();
};
Promise.defer = Promise.pending = function () {
var promise = new Promise(INTERNAL);
return new PromiseResolver(promise);
};
Promise.cast = function (obj) {
var ret = tryConvertToPromise(obj);
if (!(ret instanceof Promise)) {
var val = ret;
ret = new Promise(INTERNAL);
ret._fulfillUnchecked(val);
}
return ret;
};
Promise.resolve = Promise.fulfilled = Promise.cast;
Promise.reject = Promise.rejected = function (reason) {
var ret = new Promise(INTERNAL);
ret._captureStackTrace();
ret._rejectCallback(reason, true);
return ret;
};
Promise.setScheduler = function(fn) {
if (typeof fn !== "function") throw new TypeError("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a");
var prev = async._schedule;
async._schedule = fn;
return prev;
};
Promise.prototype._then = function (
didFulfill,
didReject,
didProgress,
receiver,
internalData
) {
var haveInternalData = internalData !== undefined;
var ret = haveInternalData ? internalData : new Promise(INTERNAL);
if (!haveInternalData) {
ret._propagateFrom(this, 4 | 1);
ret._captureStackTrace();
}
var target = this._target();
if (target !== this) {
if (receiver === undefined) receiver = this._boundTo;
if (!haveInternalData) ret._setIsMigrated();
}
var callbackIndex = target._addCallbacks(didFulfill,
didReject,
didProgress,
ret,
receiver,
getDomain());
if (target._isResolved() && !target._isSettlePromisesQueued()) {
async.invoke(
target._settlePromiseAtPostResolution, target, callbackIndex);
}
return ret;
};
Promise.prototype._settlePromiseAtPostResolution = function (index) {
if (this._isRejectionUnhandled()) this._unsetRejectionIsUnhandled();
this._settlePromiseAt(index);
};
Promise.prototype._length = function () {
return this._bitField & 131071;
};
Promise.prototype._isFollowingOrFulfilledOrRejected = function () {
return (this._bitField & 939524096) > 0;
};
Promise.prototype._isFollowing = function () {
return (this._bitField & 536870912) === 536870912;
};
Promise.prototype._setLength = function (len) {
this._bitField = (this._bitField & -131072) |
(len & 131071);
};
Promise.prototype._setFulfilled = function () {
this._bitField = this._bitField | 268435456;
};
Promise.prototype._setRejected = function () {
this._bitField = this._bitField | 134217728;
};
Promise.prototype._setFollowing = function () {
this._bitField = this._bitField | 536870912;
};
Promise.prototype._setIsFinal = function () {
this._bitField = this._bitField | 33554432;
};
Promise.prototype._isFinal = function () {
return (this._bitField & 33554432) > 0;
};
Promise.prototype._cancellable = function () {
return (this._bitField & 67108864) > 0;
};
Promise.prototype._setCancellable = function () {
this._bitField = this._bitField | 67108864;
};
Promise.prototype._unsetCancellable = function () {
this._bitField = this._bitField & (~67108864);
};
Promise.prototype._setIsMigrated = function () {
this._bitField = this._bitField | 4194304;
};
Promise.prototype._unsetIsMigrated = function () {
this._bitField = this._bitField & (~4194304);
};
Promise.prototype._isMigrated = function () {
return (this._bitField & 4194304) > 0;
};
Promise.prototype._receiverAt = function (index) {
var ret = index === 0
? this._receiver0
: this[
index * 5 - 5 + 4];
if (ret === undefined && this._isBound()) {
return this._boundValue();
}
return ret;
};
Promise.prototype._promiseAt = function (index) {
return index === 0
? this._promise0
: this[index * 5 - 5 + 3];
};
Promise.prototype._fulfillmentHandlerAt = function (index) {
return index === 0
? this._fulfillmentHandler0
: this[index * 5 - 5 + 0];
};
Promise.prototype._rejectionHandlerAt = function (index) {
return index === 0
? this._rejectionHandler0
: this[index * 5 - 5 + 1];
};
Promise.prototype._boundValue = function() {
var ret = this._boundTo;
if (ret !== undefined) {
if (ret instanceof Promise) {
if (ret.isFulfilled()) {
return ret.value();
} else {
return undefined;
}
}
}
return ret;
};
Promise.prototype._migrateCallbacks = function (follower, index) {
var fulfill = follower._fulfillmentHandlerAt(index);
var reject = follower._rejectionHandlerAt(index);
var progress = follower._progressHandlerAt(index);
var promise = follower._promiseAt(index);
var receiver = follower._receiverAt(index);
if (promise instanceof Promise) promise._setIsMigrated();
this._addCallbacks(fulfill, reject, progress, promise, receiver, null);
};
Promise.prototype._addCallbacks = function (
fulfill,
reject,
progress,
promise,
receiver,
domain
) {
var index = this._length();
if (index >= 131071 - 5) {
index = 0;
this._setLength(0);
}
if (index === 0) {
this._promise0 = promise;
if (receiver !== undefined) this._receiver0 = receiver;
if (typeof fulfill === "function" && !this._isCarryingStackTrace()) {
this._fulfillmentHandler0 =
domain === null ? fulfill : domain.bind(fulfill);
}
if (typeof reject === "function") {
this._rejectionHandler0 =
domain === null ? reject : domain.bind(reject);
}
if (typeof progress === "function") {
this._progressHandler0 =
domain === null ? progress : domain.bind(progress);
}
} else {
var base = index * 5 - 5;
this[base + 3] = promise;
this[base + 4] = receiver;
if (typeof fulfill === "function") {
this[base + 0] =
domain === null ? fulfill : domain.bind(fulfill);
}
if (typeof reject === "function") {
this[base + 1] =
domain === null ? reject : domain.bind(reject);
}
if (typeof progress === "function") {
this[base + 2] =
domain === null ? progress : domain.bind(progress);
}
}
this._setLength(index + 1);
return index;
};
Promise.prototype._setProxyHandlers = function (receiver, promiseSlotValue) {
var index = this._length();
if (index >= 131071 - 5) {
index = 0;
this._setLength(0);
}
if (index === 0) {
this._promise0 = promiseSlotValue;
this._receiver0 = receiver;
} else {
var base = index * 5 - 5;
this[base + 3] = promiseSlotValue;
this[base + 4] = receiver;
}
this._setLength(index + 1);
};
Promise.prototype._proxyPromiseArray = function (promiseArray, index) {
this._setProxyHandlers(promiseArray, index);
};
Promise.prototype._resolveCallback = function(value, shouldBind) {
if (this._isFollowingOrFulfilledOrRejected()) return;
if (value === this)
return this._rejectCallback(makeSelfResolutionError(), false, true);
var maybePromise = tryConvertToPromise(value, this);
if (!(maybePromise instanceof Promise)) return this._fulfill(value);
var propagationFlags = 1 | (shouldBind ? 4 : 0);
this._propagateFrom(maybePromise, propagationFlags);
var promise = maybePromise._target();
if (promise._isPending()) {
var len = this._length();
for (var i = 0; i < len; ++i) {
promise._migrateCallbacks(this, i);
}
this._setFollowing();
this._setLength(0);
this._setFollowee(promise);
} else if (promise._isFulfilled()) {
this._fulfillUnchecked(promise._value());
} else {
this._rejectUnchecked(promise._reason(),
promise._getCarriedStackTrace());
}
};
Promise.prototype._rejectCallback =
function(reason, synchronous, shouldNotMarkOriginatingFromRejection) {
if (!shouldNotMarkOriginatingFromRejection) {
util.markAsOriginatingFromRejection(reason);
}
var trace = util.ensureErrorObject(reason);
var hasStack = trace === reason;
this._attachExtraTrace(trace, synchronous ? hasStack : false);
this._reject(reason, hasStack ? undefined : trace);
};
Promise.prototype._resolveFromResolver = function (resolver) {
var promise = this;
this._captureStackTrace();
this._pushContext();
var synchronous = true;
var r = tryCatch(resolver)(function(value) {
if (promise === null) return;
promise._resolveCallback(value);
promise = null;
}, function (reason) {
if (promise === null) return;
promise._rejectCallback(reason, synchronous);
promise = null;
});
synchronous = false;
this._popContext();
if (r !== undefined && r === errorObj && promise !== null) {
promise._rejectCallback(r.e, true, true);
promise = null;
}
};
Promise.prototype._settlePromiseFromHandler = function (
handler, receiver, value, promise
) {
if (promise._isRejected()) return;
promise._pushContext();
var x;
if (receiver === APPLY && !this._isRejected()) {
x = tryCatch(handler).apply(this._boundValue(), value);
} else {
x = tryCatch(handler).call(receiver, value);
}
promise._popContext();
if (x === errorObj || x === promise || x === NEXT_FILTER) {
var err = x === promise ? makeSelfResolutionError() : x.e;
promise._rejectCallback(err, false, true);
} else {
promise._resolveCallback(x);
}
};
Promise.prototype._target = function() {
var ret = this;
while (ret._isFollowing()) ret = ret._followee();
return ret;
};
Promise.prototype._followee = function() {
return this._rejectionHandler0;
};
Promise.prototype._setFollowee = function(promise) {
this._rejectionHandler0 = promise;
};
Promise.prototype._cleanValues = function () {
if (this._cancellable()) {
this._cancellationParent = undefined;
}
};
Promise.prototype._propagateFrom = function (parent, flags) {
if ((flags & 1) > 0 && parent._cancellable()) {
this._setCancellable();
this._cancellationParent = parent;
}
if ((flags & 4) > 0 && parent._isBound()) {
this._setBoundTo(parent._boundTo);
}
};
Promise.prototype._fulfill = function (value) {
if (this._isFollowingOrFulfilledOrRejected()) return;
this._fulfillUnchecked(value);
};
Promise.prototype._reject = function (reason, carriedStackTrace) {
if (this._isFollowingOrFulfilledOrRejected()) return;
this._rejectUnchecked(reason, carriedStackTrace);
};
Promise.prototype._settlePromiseAt = function (index) {
var promise = this._promiseAt(index);
var isPromise = promise instanceof Promise;
if (isPromise && promise._isMigrated()) {
promise._unsetIsMigrated();
return async.invoke(this._settlePromiseAt, this, index);
}
var handler = this._isFulfilled()
? this._fulfillmentHandlerAt(index)
: this._rejectionHandlerAt(index);
var carriedStackTrace =
this._isCarryingStackTrace() ? this._getCarriedStackTrace() : undefined;
var value = this._settledValue;
var receiver = this._receiverAt(index);
this._clearCallbackDataAtIndex(index);
if (typeof handler === "function") {
if (!isPromise) {
handler.call(receiver, value, promise);
} else {
this._settlePromiseFromHandler(handler, receiver, value, promise);
}
} else if (receiver instanceof PromiseArray) {
if (!receiver._isResolved()) {
if (this._isFulfilled()) {
receiver._promiseFulfilled(value, promise);
}
else {
receiver._promiseRejected(value, promise);
}
}
} else if (isPromise) {
if (this._isFulfilled()) {
promise._fulfill(value);
} else {
promise._reject(value, carriedStackTrace);
}
}
if (index >= 4 && (index & 31) === 4)
async.invokeLater(this._setLength, this, 0);
};
Promise.prototype._clearCallbackDataAtIndex = function(index) {
if (index === 0) {
if (!this._isCarryingStackTrace()) {
this._fulfillmentHandler0 = undefined;
}
this._rejectionHandler0 =
this._progressHandler0 =
this._receiver0 =
this._promise0 = undefined;
} else {
var base = index * 5 - 5;
this[base + 3] =
this[base + 4] =
this[base + 0] =
this[base + 1] =
this[base + 2] = undefined;
}
};
Promise.prototype._isSettlePromisesQueued = function () {
return (this._bitField &
-1073741824) === -1073741824;
};
Promise.prototype._setSettlePromisesQueued = function () {
this._bitField = this._bitField | -1073741824;
};
Promise.prototype._unsetSettlePromisesQueued = function () {
this._bitField = this._bitField & (~-1073741824);
};
Promise.prototype._queueSettlePromises = function() {
async.settlePromises(this);
this._setSettlePromisesQueued();
};
Promise.prototype._fulfillUnchecked = function (value) {
if (value === this) {
var err = makeSelfResolutionError();
this._attachExtraTrace(err);
return this._rejectUnchecked(err, undefined);
}
this._setFulfilled();
this._settledValue = value;
this._cleanValues();
if (this._length() > 0) {
this._queueSettlePromises();
}
};
Promise.prototype._rejectUncheckedCheckError = function (reason) {
var trace = util.ensureErrorObject(reason);
this._rejectUnchecked(reason, trace === reason ? undefined : trace);
};
Promise.prototype._rejectUnchecked = function (reason, trace) {
if (reason === this) {
var err = makeSelfResolutionError();
this._attachExtraTrace(err);
return this._rejectUnchecked(err);
}
this._setRejected();
this._settledValue = reason;
this._cleanValues();
if (this._isFinal()) {
async.throwLater(function(e) {
if ("stack" in e) {
async.invokeFirst(
CapturedTrace.unhandledRejection, undefined, e);
}
throw e;
}, trace === undefined ? reason : trace);
return;
}
if (trace !== undefined && trace !== reason) {
this._setCarriedStackTrace(trace);
}
if (this._length() > 0) {
this._queueSettlePromises();
} else {
this._ensurePossibleRejectionHandled();
}
};
Promise.prototype._settlePromises = function () {
this._unsetSettlePromisesQueued();
var len = this._length();
for (var i = 0; i < len; i++) {
this._settlePromiseAt(i);
}
};
util.notEnumerableProp(Promise,
"_makeSelfResolutionError",
makeSelfResolutionError);
_dereq_("./progress.js")(Promise, PromiseArray);
_dereq_("./method.js")(Promise, INTERNAL, tryConvertToPromise, apiRejection);
_dereq_("./bind.js")(Promise, INTERNAL, tryConvertToPromise);
_dereq_("./finally.js")(Promise, NEXT_FILTER, tryConvertToPromise);
_dereq_("./direct_resolve.js")(Promise);
_dereq_("./synchronous_inspection.js")(Promise);
_dereq_("./join.js")(Promise, PromiseArray, tryConvertToPromise, INTERNAL);
Promise.Promise = Promise;
_dereq_('./map.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL);
_dereq_('./cancel.js')(Promise);
_dereq_('./using.js')(Promise, apiRejection, tryConvertToPromise, createContext);
_dereq_('./generators.js')(Promise, apiRejection, INTERNAL, tryConvertToPromise);
_dereq_('./nodeify.js')(Promise);
_dereq_('./call_get.js')(Promise);
_dereq_('./props.js')(Promise, PromiseArray, tryConvertToPromise, apiRejection);
_dereq_('./race.js')(Promise, INTERNAL, tryConvertToPromise, apiRejection);
_dereq_('./reduce.js')(Promise, PromiseArray, apiRejection, tryConvertToPromise, INTERNAL);
_dereq_('./settle.js')(Promise, PromiseArray);
_dereq_('./some.js')(Promise, PromiseArray, apiRejection);
_dereq_('./promisify.js')(Promise, INTERNAL);
_dereq_('./any.js')(Promise);
_dereq_('./each.js')(Promise, INTERNAL);
_dereq_('./timers.js')(Promise, INTERNAL);
_dereq_('./filter.js')(Promise, INTERNAL);
util.toFastProperties(Promise);
util.toFastProperties(Promise.prototype);
function fillTypes(value) {
var p = new Promise(INTERNAL);
p._fulfillmentHandler0 = value;
p._rejectionHandler0 = value;
p._progressHandler0 = value;
p._promise0 = value;
p._receiver0 = value;
p._settledValue = value;
}
// Complete slack tracking, opt out of field-type tracking and
// stabilize map
fillTypes({a: 1});
fillTypes({b: 2});
fillTypes({c: 3});
fillTypes(1);
fillTypes(function(){});
fillTypes(undefined);
fillTypes(false);
fillTypes(new Promise(INTERNAL));
CapturedTrace.setBounds(async.firstLineError, util.lastLineError);
return Promise;
};
},{"./any.js":1,"./async.js":2,"./bind.js":3,"./call_get.js":5,"./cancel.js":6,"./captured_trace.js":7,"./catch_filter.js":8,"./context.js":9,"./debuggability.js":10,"./direct_resolve.js":11,"./each.js":12,"./errors.js":13,"./filter.js":15,"./finally.js":16,"./generators.js":17,"./join.js":18,"./map.js":19,"./method.js":20,"./nodeify.js":21,"./progress.js":22,"./promise_array.js":24,"./promise_resolver.js":25,"./promisify.js":26,"./props.js":27,"./race.js":29,"./reduce.js":30,"./settle.js":32,"./some.js":33,"./synchronous_inspection.js":34,"./thenables.js":35,"./timers.js":36,"./using.js":37,"./util.js":38}],24:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise, INTERNAL, tryConvertToPromise,
apiRejection) {
var util = _dereq_("./util.js");
var isArray = util.isArray;
function toResolutionValue(val) {
switch(val) {
case -2: return [];
case -3: return {};
}
}
function PromiseArray(values) {
var promise = this._promise = new Promise(INTERNAL);
var parent;
if (values instanceof Promise) {
parent = values;
promise._propagateFrom(parent, 1 | 4);
}
this._values = values;
this._length = 0;
this._totalResolved = 0;
this._init(undefined, -2);
}
PromiseArray.prototype.length = function () {
return this._length;
};
PromiseArray.prototype.promise = function () {
return this._promise;
};
PromiseArray.prototype._init = function init(_, resolveValueIfEmpty) {
var values = tryConvertToPromise(this._values, this._promise);
if (values instanceof Promise) {
values = values._target();
this._values = values;
if (values._isFulfilled()) {
values = values._value();
if (!isArray(values)) {
var err = new Promise.TypeError("expecting an array, a promise or a thenable\u000a\u000a See http://goo.gl/s8MMhc\u000a");
this.__hardReject__(err);
return;
}
} else if (values._isPending()) {
values._then(
init,
this._reject,
undefined,
this,
resolveValueIfEmpty
);
return;
} else {
this._reject(values._reason());
return;
}
} else if (!isArray(values)) {
this._promise._reject(apiRejection("expecting an array, a promise or a thenable\u000a\u000a See http://goo.gl/s8MMhc\u000a")._reason());
return;
}
if (values.length === 0) {
if (resolveValueIfEmpty === -5) {
this._resolveEmptyArray();
}
else {
this._resolve(toResolutionValue(resolveValueIfEmpty));
}
return;
}
var len = this.getActualLength(values.length);
this._length = len;
this._values = this.shouldCopyValues() ? new Array(len) : this._values;
var promise = this._promise;
for (var i = 0; i < len; ++i) {
var isResolved = this._isResolved();
var maybePromise = tryConvertToPromise(values[i], promise);
if (maybePromise instanceof Promise) {
maybePromise = maybePromise._target();
if (isResolved) {
maybePromise._ignoreRejections();
} else if (maybePromise._isPending()) {
maybePromise._proxyPromiseArray(this, i);
} else if (maybePromise._isFulfilled()) {
this._promiseFulfilled(maybePromise._value(), i);
} else {
this._promiseRejected(maybePromise._reason(), i);
}
} else if (!isResolved) {
this._promiseFulfilled(maybePromise, i);
}
}
};
PromiseArray.prototype._isResolved = function () {
return this._values === null;
};
PromiseArray.prototype._resolve = function (value) {
this._values = null;
this._promise._fulfill(value);
};
PromiseArray.prototype.__hardReject__ =
PromiseArray.prototype._reject = function (reason) {
this._values = null;
this._promise._rejectCallback(reason, false, true);
};
PromiseArray.prototype._promiseProgressed = function (progressValue, index) {
this._promise._progress({
index: index,
value: progressValue
});
};
PromiseArray.prototype._promiseFulfilled = function (value, index) {
this._values[index] = value;
var totalResolved = ++this._totalResolved;
if (totalResolved >= this._length) {
this._resolve(this._values);
}
};
PromiseArray.prototype._promiseRejected = function (reason, index) {
this._totalResolved++;
this._reject(reason);
};
PromiseArray.prototype.shouldCopyValues = function () {
return true;
};
PromiseArray.prototype.getActualLength = function (len) {
return len;
};
return PromiseArray;
};
},{"./util.js":38}],25:[function(_dereq_,module,exports){
"use strict";
var util = _dereq_("./util.js");
var maybeWrapAsError = util.maybeWrapAsError;
var errors = _dereq_("./errors.js");
var TimeoutError = errors.TimeoutError;
var OperationalError = errors.OperationalError;
var haveGetters = util.haveGetters;
var es5 = _dereq_("./es5.js");
function isUntypedError(obj) {
return obj instanceof Error &&
es5.getPrototypeOf(obj) === Error.prototype;
}
var rErrorKey = /^(?:name|message|stack|cause)$/;
function wrapAsOperationalError(obj) {
var ret;
if (isUntypedError(obj)) {
ret = new OperationalError(obj);
ret.name = obj.name;
ret.message = obj.message;
ret.stack = obj.stack;
var keys = es5.keys(obj);
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
if (!rErrorKey.test(key)) {
ret[key] = obj[key];
}
}
return ret;
}
util.markAsOriginatingFromRejection(obj);
return obj;
}
function nodebackForPromise(promise) {
return function(err, value) {
if (promise === null) return;
if (err) {
var wrapped = wrapAsOperationalError(maybeWrapAsError(err));
promise._attachExtraTrace(wrapped);
promise._reject(wrapped);
} else if (arguments.length > 2) {
var $_len = arguments.length;var args = new Array($_len - 1); for(var $_i = 1; $_i < $_len; ++$_i) {args[$_i - 1] = arguments[$_i];}
promise._fulfill(args);
} else {
promise._fulfill(value);
}
promise = null;
};
}
var PromiseResolver;
if (!haveGetters) {
PromiseResolver = function (promise) {
this.promise = promise;
this.asCallback = nodebackForPromise(promise);
this.callback = this.asCallback;
};
}
else {
PromiseResolver = function (promise) {
this.promise = promise;
};
}
if (haveGetters) {
var prop = {
get: function() {
return nodebackForPromise(this.promise);
}
};
es5.defineProperty(PromiseResolver.prototype, "asCallback", prop);
es5.defineProperty(PromiseResolver.prototype, "callback", prop);
}
PromiseResolver._nodebackForPromise = nodebackForPromise;
PromiseResolver.prototype.toString = function () {
return "[object PromiseResolver]";
};
PromiseResolver.prototype.resolve =
PromiseResolver.prototype.fulfill = function (value) {
if (!(this instanceof PromiseResolver)) {
throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\u000a\u000a See http://goo.gl/sdkXL9\u000a");
}
this.promise._resolveCallback(value);
};
PromiseResolver.prototype.reject = function (reason) {
if (!(this instanceof PromiseResolver)) {
throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\u000a\u000a See http://goo.gl/sdkXL9\u000a");
}
this.promise._rejectCallback(reason);
};
PromiseResolver.prototype.progress = function (value) {
if (!(this instanceof PromiseResolver)) {
throw new TypeError("Illegal invocation, resolver resolve/reject must be called within a resolver context. Consider using the promise constructor instead.\u000a\u000a See http://goo.gl/sdkXL9\u000a");
}
this.promise._progress(value);
};
PromiseResolver.prototype.cancel = function (err) {
this.promise.cancel(err);
};
PromiseResolver.prototype.timeout = function () {
this.reject(new TimeoutError("timeout"));
};
PromiseResolver.prototype.isResolved = function () {
return this.promise.isResolved();
};
PromiseResolver.prototype.toJSON = function () {
return this.promise.toJSON();
};
module.exports = PromiseResolver;
},{"./errors.js":13,"./es5.js":14,"./util.js":38}],26:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise, INTERNAL) {
var THIS = {};
var util = _dereq_("./util.js");
var nodebackForPromise = _dereq_("./promise_resolver.js")
._nodebackForPromise;
var withAppended = util.withAppended;
var maybeWrapAsError = util.maybeWrapAsError;
var canEvaluate = util.canEvaluate;
var TypeError = _dereq_("./errors").TypeError;
var defaultSuffix = "Async";
var defaultPromisified = {__isPromisified__: true};
var noCopyProps = [
"arity", "length",
"name",
"arguments",
"caller",
"callee",
"prototype",
"__isPromisified__"
];
var noCopyPropsPattern = new RegExp("^(?:" + noCopyProps.join("|") + ")$");
var defaultFilter = function(name) {
return util.isIdentifier(name) &&
name.charAt(0) !== "_" &&
name !== "constructor";
};
function propsFilter(key) {
return !noCopyPropsPattern.test(key);
}
function isPromisified(fn) {
try {
return fn.__isPromisified__ === true;
}
catch (e) {
return false;
}
}
function hasPromisified(obj, key, suffix) {
var val = util.getDataPropertyOrDefault(obj, key + suffix,
defaultPromisified);
return val ? isPromisified(val) : false;
}
function checkValid(ret, suffix, suffixRegexp) {
for (var i = 0; i < ret.length; i += 2) {
var key = ret[i];
if (suffixRegexp.test(key)) {
var keyWithoutAsyncSuffix = key.replace(suffixRegexp, "");
for (var j = 0; j < ret.length; j += 2) {
if (ret[j] === keyWithoutAsyncSuffix) {
throw new TypeError("Cannot promisify an API that has normal methods with '%s'-suffix\u000a\u000a See http://goo.gl/iWrZbw\u000a"
.replace("%s", suffix));
}
}
}
}
}
function promisifiableMethods(obj, suffix, suffixRegexp, filter) {
var keys = util.inheritedDataKeys(obj);
var ret = [];
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
var value = obj[key];
var passesDefaultFilter = filter === defaultFilter
? true : defaultFilter(key, value, obj);
if (typeof value === "function" &&
!isPromisified(value) &&
!hasPromisified(obj, key, suffix) &&
filter(key, value, obj, passesDefaultFilter)) {
ret.push(key, value);
}
}
checkValid(ret, suffix, suffixRegexp);
return ret;
}
var escapeIdentRegex = function(str) {
return str.replace(/([$])/, "\\$");
};
var makeNodePromisifiedEval;
if (!true) {
var switchCaseArgumentOrder = function(likelyArgumentCount) {
var ret = [likelyArgumentCount];
var min = Math.max(0, likelyArgumentCount - 1 - 3);
for(var i = likelyArgumentCount - 1; i >= min; --i) {
ret.push(i);
}
for(var i = likelyArgumentCount + 1; i <= 3; ++i) {
ret.push(i);
}
return ret;
};
var argumentSequence = function(argumentCount) {
return util.filledRange(argumentCount, "_arg", "");
};
var parameterDeclaration = function(parameterCount) {
return util.filledRange(
Math.max(parameterCount, 3), "_arg", "");
};
var parameterCount = function(fn) {
if (typeof fn.length === "number") {
return Math.max(Math.min(fn.length, 1023 + 1), 0);
}
return 0;
};
makeNodePromisifiedEval =
function(callback, receiver, originalName, fn) {
var newParameterCount = Math.max(0, parameterCount(fn) - 1);
var argumentOrder = switchCaseArgumentOrder(newParameterCount);
var shouldProxyThis = typeof callback === "string" || receiver === THIS;
function generateCallForArgumentCount(count) {
var args = argumentSequence(count).join(", ");
var comma = count > 0 ? ", " : "";
var ret;
if (shouldProxyThis) {
ret = "ret = callback.call(this, {{args}}, nodeback); break;\n";
} else {
ret = receiver === undefined
? "ret = callback({{args}}, nodeback); break;\n"
: "ret = callback.call(receiver, {{args}}, nodeback); break;\n";
}
return ret.replace("{{args}}", args).replace(", ", comma);
}
function generateArgumentSwitchCase() {
var ret = "";
for (var i = 0; i < argumentOrder.length; ++i) {
ret += "case " + argumentOrder[i] +":" +
generateCallForArgumentCount(argumentOrder[i]);
}
ret += " \n\
default: \n\
var args = new Array(len + 1); \n\
var i = 0; \n\
for (var i = 0; i < len; ++i) { \n\
args[i] = arguments[i]; \n\
} \n\
args[i] = nodeback; \n\
[CodeForCall] \n\
break; \n\
".replace("[CodeForCall]", (shouldProxyThis
? "ret = callback.apply(this, args);\n"
: "ret = callback.apply(receiver, args);\n"));
return ret;
}
var getFunctionCode = typeof callback === "string"
? ("this != null ? this['"+callback+"'] : fn")
: "fn";
return new Function("Promise",
"fn",
"receiver",
"withAppended",
"maybeWrapAsError",
"nodebackForPromise",
"tryCatch",
"errorObj",
"notEnumerableProp",
"INTERNAL","'use strict'; \n\
var ret = function (Parameters) { \n\
'use strict'; \n\
var len = arguments.length; \n\
var promise = new Promise(INTERNAL); \n\
promise._captureStackTrace(); \n\
var nodeback = nodebackForPromise(promise); \n\
var ret; \n\
var callback = tryCatch([GetFunctionCode]); \n\
switch(len) { \n\
[CodeForSwitchCase] \n\
} \n\
if (ret === errorObj) { \n\
promise._rejectCallback(maybeWrapAsError(ret.e), true, true);\n\
} \n\
return promise; \n\
}; \n\
notEnumerableProp(ret, '__isPromisified__', true); \n\
return ret; \n\
"
.replace("Parameters", parameterDeclaration(newParameterCount))
.replace("[CodeForSwitchCase]", generateArgumentSwitchCase())
.replace("[GetFunctionCode]", getFunctionCode))(
Promise,
fn,
receiver,
withAppended,
maybeWrapAsError,
nodebackForPromise,
util.tryCatch,
util.errorObj,
util.notEnumerableProp,
INTERNAL
);
};
}
function makeNodePromisifiedClosure(callback, receiver, _, fn) {
var defaultThis = (function() {return this;})();
var method = callback;
if (typeof method === "string") {
callback = fn;
}
function promisified() {
var _receiver = receiver;
if (receiver === THIS) _receiver = this;
var promise = new Promise(INTERNAL);
promise._captureStackTrace();
var cb = typeof method === "string" && this !== defaultThis
? this[method] : callback;
var fn = nodebackForPromise(promise);
try {
cb.apply(_receiver, withAppended(arguments, fn));
} catch(e) {
promise._rejectCallback(maybeWrapAsError(e), true, true);
}
return promise;
}
util.notEnumerableProp(promisified, "__isPromisified__", true);
return promisified;
}
var makeNodePromisified = canEvaluate
? makeNodePromisifiedEval
: makeNodePromisifiedClosure;
function promisifyAll(obj, suffix, filter, promisifier) {
var suffixRegexp = new RegExp(escapeIdentRegex(suffix) + "$");
var methods =
promisifiableMethods(obj, suffix, suffixRegexp, filter);
for (var i = 0, len = methods.length; i < len; i+= 2) {
var key = methods[i];
var fn = methods[i+1];
var promisifiedKey = key + suffix;
obj[promisifiedKey] = promisifier === makeNodePromisified
? makeNodePromisified(key, THIS, key, fn, suffix)
: promisifier(fn, function() {
return makeNodePromisified(key, THIS, key, fn, suffix);
});
}
util.toFastProperties(obj);
return obj;
}
function promisify(callback, receiver) {
return makeNodePromisified(callback, receiver, undefined, callback);
}
Promise.promisify = function (fn, receiver) {
if (typeof fn !== "function") {
throw new TypeError("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a");
}
if (isPromisified(fn)) {
return fn;
}
var ret = promisify(fn, arguments.length < 2 ? THIS : receiver);
util.copyDescriptors(fn, ret, propsFilter);
return ret;
};
Promise.promisifyAll = function (target, options) {
if (typeof target !== "function" && typeof target !== "object") {
throw new TypeError("the target of promisifyAll must be an object or a function\u000a\u000a See http://goo.gl/9ITlV0\u000a");
}
options = Object(options);
var suffix = options.suffix;
if (typeof suffix !== "string") suffix = defaultSuffix;
var filter = options.filter;
if (typeof filter !== "function") filter = defaultFilter;
var promisifier = options.promisifier;
if (typeof promisifier !== "function") promisifier = makeNodePromisified;
if (!util.isIdentifier(suffix)) {
throw new RangeError("suffix must be a valid identifier\u000a\u000a See http://goo.gl/8FZo5V\u000a");
}
var keys = util.inheritedDataKeys(target);
for (var i = 0; i < keys.length; ++i) {
var value = target[keys[i]];
if (keys[i] !== "constructor" &&
util.isClass(value)) {
promisifyAll(value.prototype, suffix, filter, promisifier);
promisifyAll(value, suffix, filter, promisifier);
}
}
return promisifyAll(target, suffix, filter, promisifier);
};
};
},{"./errors":13,"./promise_resolver.js":25,"./util.js":38}],27:[function(_dereq_,module,exports){
"use strict";
module.exports = function(
Promise, PromiseArray, tryConvertToPromise, apiRejection) {
var util = _dereq_("./util.js");
var isObject = util.isObject;
var es5 = _dereq_("./es5.js");
function PropertiesPromiseArray(obj) {
var keys = es5.keys(obj);
var len = keys.length;
var values = new Array(len * 2);
for (var i = 0; i < len; ++i) {
var key = keys[i];
values[i] = obj[key];
values[i + len] = key;
}
this.constructor$(values);
}
util.inherits(PropertiesPromiseArray, PromiseArray);
PropertiesPromiseArray.prototype._init = function () {
this._init$(undefined, -3) ;
};
PropertiesPromiseArray.prototype._promiseFulfilled = function (value, index) {
this._values[index] = value;
var totalResolved = ++this._totalResolved;
if (totalResolved >= this._length) {
var val = {};
var keyOffset = this.length();
for (var i = 0, len = this.length(); i < len; ++i) {
val[this._values[i + keyOffset]] = this._values[i];
}
this._resolve(val);
}
};
PropertiesPromiseArray.prototype._promiseProgressed = function (value, index) {
this._promise._progress({
key: this._values[index + this.length()],
value: value
});
};
PropertiesPromiseArray.prototype.shouldCopyValues = function () {
return false;
};
PropertiesPromiseArray.prototype.getActualLength = function (len) {
return len >> 1;
};
function props(promises) {
var ret;
var castValue = tryConvertToPromise(promises);
if (!isObject(castValue)) {
return apiRejection("cannot await properties of a non-object\u000a\u000a See http://goo.gl/OsFKC8\u000a");
} else if (castValue instanceof Promise) {
ret = castValue._then(
Promise.props, undefined, undefined, undefined, undefined);
} else {
ret = new PropertiesPromiseArray(castValue).promise();
}
if (castValue instanceof Promise) {
ret._propagateFrom(castValue, 4);
}
return ret;
}
Promise.prototype.props = function () {
return props(this);
};
Promise.props = function (promises) {
return props(promises);
};
};
},{"./es5.js":14,"./util.js":38}],28:[function(_dereq_,module,exports){
"use strict";
function arrayMove(src, srcIndex, dst, dstIndex, len) {
for (var j = 0; j < len; ++j) {
dst[j + dstIndex] = src[j + srcIndex];
src[j + srcIndex] = void 0;
}
}
function Queue(capacity) {
this._capacity = capacity;
this._length = 0;
this._front = 0;
}
Queue.prototype._willBeOverCapacity = function (size) {
return this._capacity < size;
};
Queue.prototype._pushOne = function (arg) {
var length = this.length();
this._checkCapacity(length + 1);
var i = (this._front + length) & (this._capacity - 1);
this[i] = arg;
this._length = length + 1;
};
Queue.prototype._unshiftOne = function(value) {
var capacity = this._capacity;
this._checkCapacity(this.length() + 1);
var front = this._front;
var i = (((( front - 1 ) &
( capacity - 1) ) ^ capacity ) - capacity );
this[i] = value;
this._front = i;
this._length = this.length() + 1;
};
Queue.prototype.unshift = function(fn, receiver, arg) {
this._unshiftOne(arg);
this._unshiftOne(receiver);
this._unshiftOne(fn);
};
Queue.prototype.push = function (fn, receiver, arg) {
var length = this.length() + 3;
if (this._willBeOverCapacity(length)) {
this._pushOne(fn);
this._pushOne(receiver);
this._pushOne(arg);
return;
}
var j = this._front + length - 3;
this._checkCapacity(length);
var wrapMask = this._capacity - 1;
this[(j + 0) & wrapMask] = fn;
this[(j + 1) & wrapMask] = receiver;
this[(j + 2) & wrapMask] = arg;
this._length = length;
};
Queue.prototype.shift = function () {
var front = this._front,
ret = this[front];
this[front] = undefined;
this._front = (front + 1) & (this._capacity - 1);
this._length--;
return ret;
};
Queue.prototype.length = function () {
return this._length;
};
Queue.prototype._checkCapacity = function (size) {
if (this._capacity < size) {
this._resizeTo(this._capacity << 1);
}
};
Queue.prototype._resizeTo = function (capacity) {
var oldCapacity = this._capacity;
this._capacity = capacity;
var front = this._front;
var length = this._length;
var moveItemsCount = (front + length) & (oldCapacity - 1);
arrayMove(this, 0, this, oldCapacity, moveItemsCount);
};
module.exports = Queue;
},{}],29:[function(_dereq_,module,exports){
"use strict";
module.exports = function(
Promise, INTERNAL, tryConvertToPromise, apiRejection) {
var isArray = _dereq_("./util.js").isArray;
var raceLater = function (promise) {
return promise.then(function(array) {
return race(array, promise);
});
};
function race(promises, parent) {
var maybePromise = tryConvertToPromise(promises);
if (maybePromise instanceof Promise) {
return raceLater(maybePromise);
} else if (!isArray(promises)) {
return apiRejection("expecting an array, a promise or a thenable\u000a\u000a See http://goo.gl/s8MMhc\u000a");
}
var ret = new Promise(INTERNAL);
if (parent !== undefined) {
ret._propagateFrom(parent, 4 | 1);
}
var fulfill = ret._fulfill;
var reject = ret._reject;
for (var i = 0, len = promises.length; i < len; ++i) {
var val = promises[i];
if (val === undefined && !(i in promises)) {
continue;
}
Promise.cast(val)._then(fulfill, reject, undefined, ret, null);
}
return ret;
}
Promise.race = function (promises) {
return race(promises, undefined);
};
Promise.prototype.race = function () {
return race(this, undefined);
};
};
},{"./util.js":38}],30:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise,
PromiseArray,
apiRejection,
tryConvertToPromise,
INTERNAL) {
var getDomain = Promise._getDomain;
var async = _dereq_("./async.js");
var util = _dereq_("./util.js");
var tryCatch = util.tryCatch;
var errorObj = util.errorObj;
function ReductionPromiseArray(promises, fn, accum, _each) {
this.constructor$(promises);
this._promise._captureStackTrace();
this._preservedValues = _each === INTERNAL ? [] : null;
this._zerothIsAccum = (accum === undefined);
this._gotAccum = false;
this._reducingIndex = (this._zerothIsAccum ? 1 : 0);
this._valuesPhase = undefined;
var maybePromise = tryConvertToPromise(accum, this._promise);
var rejected = false;
var isPromise = maybePromise instanceof Promise;
if (isPromise) {
maybePromise = maybePromise._target();
if (maybePromise._isPending()) {
maybePromise._proxyPromiseArray(this, -1);
} else if (maybePromise._isFulfilled()) {
accum = maybePromise._value();
this._gotAccum = true;
} else {
this._reject(maybePromise._reason());
rejected = true;
}
}
if (!(isPromise || this._zerothIsAccum)) this._gotAccum = true;
var domain = getDomain();
this._callback = domain === null ? fn : domain.bind(fn);
this._accum = accum;
if (!rejected) async.invoke(init, this, undefined);
}
function init() {
this._init$(undefined, -5);
}
util.inherits(ReductionPromiseArray, PromiseArray);
ReductionPromiseArray.prototype._init = function () {};
ReductionPromiseArray.prototype._resolveEmptyArray = function () {
if (this._gotAccum || this._zerothIsAccum) {
this._resolve(this._preservedValues !== null
? [] : this._accum);
}
};
ReductionPromiseArray.prototype._promiseFulfilled = function (value, index) {
var values = this._values;
values[index] = value;
var length = this.length();
var preservedValues = this._preservedValues;
var isEach = preservedValues !== null;
var gotAccum = this._gotAccum;
var valuesPhase = this._valuesPhase;
var valuesPhaseIndex;
if (!valuesPhase) {
valuesPhase = this._valuesPhase = new Array(length);
for (valuesPhaseIndex=0; valuesPhaseIndex<length; ++valuesPhaseIndex) {
valuesPhase[valuesPhaseIndex] = 0;
}
}
valuesPhaseIndex = valuesPhase[index];
if (index === 0 && this._zerothIsAccum) {
this._accum = value;
this._gotAccum = gotAccum = true;
valuesPhase[index] = ((valuesPhaseIndex === 0)
? 1 : 2);
} else if (index === -1) {
this._accum = value;
this._gotAccum = gotAccum = true;
} else {
if (valuesPhaseIndex === 0) {
valuesPhase[index] = 1;
} else {
valuesPhase[index] = 2;
this._accum = value;
}
}
if (!gotAccum) return;
var callback = this._callback;
var receiver = this._promise._boundValue();
var ret;
for (var i = this._reducingIndex; i < length; ++i) {
valuesPhaseIndex = valuesPhase[i];
if (valuesPhaseIndex === 2) {
this._reducingIndex = i + 1;
continue;
}
if (valuesPhaseIndex !== 1) return;
value = values[i];
this._promise._pushContext();
if (isEach) {
preservedValues.push(value);
ret = tryCatch(callback).call(receiver, value, i, length);
}
else {
ret = tryCatch(callback)
.call(receiver, this._accum, value, i, length);
}
this._promise._popContext();
if (ret === errorObj) return this._reject(ret.e);
var maybePromise = tryConvertToPromise(ret, this._promise);
if (maybePromise instanceof Promise) {
maybePromise = maybePromise._target();
if (maybePromise._isPending()) {
valuesPhase[i] = 4;
return maybePromise._proxyPromiseArray(this, i);
} else if (maybePromise._isFulfilled()) {
ret = maybePromise._value();
} else {
return this._reject(maybePromise._reason());
}
}
this._reducingIndex = i + 1;
this._accum = ret;
}
this._resolve(isEach ? preservedValues : this._accum);
};
function reduce(promises, fn, initialValue, _each) {
if (typeof fn !== "function") return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a");
var array = new ReductionPromiseArray(promises, fn, initialValue, _each);
return array.promise();
}
Promise.prototype.reduce = function (fn, initialValue) {
return reduce(this, fn, initialValue, null);
};
Promise.reduce = function (promises, fn, initialValue, _each) {
return reduce(promises, fn, initialValue, _each);
};
};
},{"./async.js":2,"./util.js":38}],31:[function(_dereq_,module,exports){
"use strict";
var schedule;
var util = _dereq_("./util");
var noAsyncScheduler = function() {
throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/m3OTXk\u000a");
};
if (util.isNode && typeof MutationObserver === "undefined") {
var GlobalSetImmediate = global.setImmediate;
var ProcessNextTick = process.nextTick;
schedule = util.isRecentNode
? function(fn) { GlobalSetImmediate.call(global, fn); }
: function(fn) { ProcessNextTick.call(process, fn); };
} else if ((typeof MutationObserver !== "undefined") &&
!(typeof window !== "undefined" &&
window.navigator &&
window.navigator.standalone)) {
schedule = function(fn) {
var div = document.createElement("div");
var observer = new MutationObserver(fn);
observer.observe(div, {attributes: true});
return function() { div.classList.toggle("foo"); };
};
schedule.isStatic = true;
} else if (typeof setImmediate !== "undefined") {
schedule = function (fn) {
setImmediate(fn);
};
} else if (typeof setTimeout !== "undefined") {
schedule = function (fn) {
setTimeout(fn, 0);
};
} else {
schedule = noAsyncScheduler;
}
module.exports = schedule;
},{"./util":38}],32:[function(_dereq_,module,exports){
"use strict";
module.exports =
function(Promise, PromiseArray) {
var PromiseInspection = Promise.PromiseInspection;
var util = _dereq_("./util.js");
function SettledPromiseArray(values) {
this.constructor$(values);
}
util.inherits(SettledPromiseArray, PromiseArray);
SettledPromiseArray.prototype._promiseResolved = function (index, inspection) {
this._values[index] = inspection;
var totalResolved = ++this._totalResolved;
if (totalResolved >= this._length) {
this._resolve(this._values);
}
};
SettledPromiseArray.prototype._promiseFulfilled = function (value, index) {
var ret = new PromiseInspection();
ret._bitField = 268435456;
ret._settledValue = value;
this._promiseResolved(index, ret);
};
SettledPromiseArray.prototype._promiseRejected = function (reason, index) {
var ret = new PromiseInspection();
ret._bitField = 134217728;
ret._settledValue = reason;
this._promiseResolved(index, ret);
};
Promise.settle = function (promises) {
return new SettledPromiseArray(promises).promise();
};
Promise.prototype.settle = function () {
return new SettledPromiseArray(this).promise();
};
};
},{"./util.js":38}],33:[function(_dereq_,module,exports){
"use strict";
module.exports =
function(Promise, PromiseArray, apiRejection) {
var util = _dereq_("./util.js");
var RangeError = _dereq_("./errors.js").RangeError;
var AggregateError = _dereq_("./errors.js").AggregateError;
var isArray = util.isArray;
function SomePromiseArray(values) {
this.constructor$(values);
this._howMany = 0;
this._unwrap = false;
this._initialized = false;
}
util.inherits(SomePromiseArray, PromiseArray);
SomePromiseArray.prototype._init = function () {
if (!this._initialized) {
return;
}
if (this._howMany === 0) {
this._resolve([]);
return;
}
this._init$(undefined, -5);
var isArrayResolved = isArray(this._values);
if (!this._isResolved() &&
isArrayResolved &&
this._howMany > this._canPossiblyFulfill()) {
this._reject(this._getRangeError(this.length()));
}
};
SomePromiseArray.prototype.init = function () {
this._initialized = true;
this._init();
};
SomePromiseArray.prototype.setUnwrap = function () {
this._unwrap = true;
};
SomePromiseArray.prototype.howMany = function () {
return this._howMany;
};
SomePromiseArray.prototype.setHowMany = function (count) {
this._howMany = count;
};
SomePromiseArray.prototype._promiseFulfilled = function (value) {
this._addFulfilled(value);
if (this._fulfilled() === this.howMany()) {
this._values.length = this.howMany();
if (this.howMany() === 1 && this._unwrap) {
this._resolve(this._values[0]);
} else {
this._resolve(this._values);
}
}
};
SomePromiseArray.prototype._promiseRejected = function (reason) {
this._addRejected(reason);
if (this.howMany() > this._canPossiblyFulfill()) {
var e = new AggregateError();
for (var i = this.length(); i < this._values.length; ++i) {
e.push(this._values[i]);
}
this._reject(e);
}
};
SomePromiseArray.prototype._fulfilled = function () {
return this._totalResolved;
};
SomePromiseArray.prototype._rejected = function () {
return this._values.length - this.length();
};
SomePromiseArray.prototype._addRejected = function (reason) {
this._values.push(reason);
};
SomePromiseArray.prototype._addFulfilled = function (value) {
this._values[this._totalResolved++] = value;
};
SomePromiseArray.prototype._canPossiblyFulfill = function () {
return this.length() - this._rejected();
};
SomePromiseArray.prototype._getRangeError = function (count) {
var message = "Input array must contain at least " +
this._howMany + " items but contains only " + count + " items";
return new RangeError(message);
};
SomePromiseArray.prototype._resolveEmptyArray = function () {
this._reject(this._getRangeError(0));
};
function some(promises, howMany) {
if ((howMany | 0) !== howMany || howMany < 0) {
return apiRejection("expecting a positive integer\u000a\u000a See http://goo.gl/1wAmHx\u000a");
}
var ret = new SomePromiseArray(promises);
var promise = ret.promise();
ret.setHowMany(howMany);
ret.init();
return promise;
}
Promise.some = function (promises, howMany) {
return some(promises, howMany);
};
Promise.prototype.some = function (howMany) {
return some(this, howMany);
};
Promise._SomePromiseArray = SomePromiseArray;
};
},{"./errors.js":13,"./util.js":38}],34:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise) {
function PromiseInspection(promise) {
if (promise !== undefined) {
promise = promise._target();
this._bitField = promise._bitField;
this._settledValue = promise._settledValue;
}
else {
this._bitField = 0;
this._settledValue = undefined;
}
}
PromiseInspection.prototype.value = function () {
if (!this.isFulfilled()) {
throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/hc1DLj\u000a");
}
return this._settledValue;
};
PromiseInspection.prototype.error =
PromiseInspection.prototype.reason = function () {
if (!this.isRejected()) {
throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/hPuiwB\u000a");
}
return this._settledValue;
};
PromiseInspection.prototype.isFulfilled =
Promise.prototype._isFulfilled = function () {
return (this._bitField & 268435456) > 0;
};
PromiseInspection.prototype.isRejected =
Promise.prototype._isRejected = function () {
return (this._bitField & 134217728) > 0;
};
PromiseInspection.prototype.isPending =
Promise.prototype._isPending = function () {
return (this._bitField & 402653184) === 0;
};
PromiseInspection.prototype.isResolved =
Promise.prototype._isResolved = function () {
return (this._bitField & 402653184) > 0;
};
Promise.prototype.isPending = function() {
return this._target()._isPending();
};
Promise.prototype.isRejected = function() {
return this._target()._isRejected();
};
Promise.prototype.isFulfilled = function() {
return this._target()._isFulfilled();
};
Promise.prototype.isResolved = function() {
return this._target()._isResolved();
};
Promise.prototype._value = function() {
return this._settledValue;
};
Promise.prototype._reason = function() {
this._unsetRejectionIsUnhandled();
return this._settledValue;
};
Promise.prototype.value = function() {
var target = this._target();
if (!target.isFulfilled()) {
throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/hc1DLj\u000a");
}
return target._settledValue;
};
Promise.prototype.reason = function() {
var target = this._target();
if (!target.isRejected()) {
throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/hPuiwB\u000a");
}
target._unsetRejectionIsUnhandled();
return target._settledValue;
};
Promise.PromiseInspection = PromiseInspection;
};
},{}],35:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise, INTERNAL) {
var util = _dereq_("./util.js");
var errorObj = util.errorObj;
var isObject = util.isObject;
function tryConvertToPromise(obj, context) {
if (isObject(obj)) {
if (obj instanceof Promise) {
return obj;
}
else if (isAnyBluebirdPromise(obj)) {
var ret = new Promise(INTERNAL);
obj._then(
ret._fulfillUnchecked,
ret._rejectUncheckedCheckError,
ret._progressUnchecked,
ret,
null
);
return ret;
}
var then = util.tryCatch(getThen)(obj);
if (then === errorObj) {
if (context) context._pushContext();
var ret = Promise.reject(then.e);
if (context) context._popContext();
return ret;
} else if (typeof then === "function") {
return doThenable(obj, then, context);
}
}
return obj;
}
function getThen(obj) {
return obj.then;
}
var hasProp = {}.hasOwnProperty;
function isAnyBluebirdPromise(obj) {
return hasProp.call(obj, "_promise0");
}
function doThenable(x, then, context) {
var promise = new Promise(INTERNAL);
var ret = promise;
if (context) context._pushContext();
promise._captureStackTrace();
if (context) context._popContext();
var synchronous = true;
var result = util.tryCatch(then).call(x,
resolveFromThenable,
rejectFromThenable,
progressFromThenable);
synchronous = false;
if (promise && result === errorObj) {
promise._rejectCallback(result.e, true, true);
promise = null;
}
function resolveFromThenable(value) {
if (!promise) return;
promise._resolveCallback(value);
promise = null;
}
function rejectFromThenable(reason) {
if (!promise) return;
promise._rejectCallback(reason, synchronous, true);
promise = null;
}
function progressFromThenable(value) {
if (!promise) return;
if (typeof promise._progress === "function") {
promise._progress(value);
}
}
return ret;
}
return tryConvertToPromise;
};
},{"./util.js":38}],36:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise, INTERNAL) {
var util = _dereq_("./util.js");
var TimeoutError = Promise.TimeoutError;
var afterTimeout = function (promise, message) {
if (!promise.isPending()) return;
if (typeof message !== "string") {
message = "operation timed out";
}
var err = new TimeoutError(message);
util.markAsOriginatingFromRejection(err);
promise._attachExtraTrace(err);
promise._cancel(err);
};
var afterValue = function(value) { return delay(+this).thenReturn(value); };
var delay = Promise.delay = function (value, ms) {
if (ms === undefined) {
ms = value;
value = undefined;
var ret = new Promise(INTERNAL);
setTimeout(function() { ret._fulfill(); }, ms);
return ret;
}
ms = +ms;
return Promise.resolve(value)._then(afterValue, null, null, ms, undefined);
};
Promise.prototype.delay = function (ms) {
return delay(this, ms);
};
function successClear(value) {
var handle = this;
if (handle instanceof Number) handle = +handle;
clearTimeout(handle);
return value;
}
function failureClear(reason) {
var handle = this;
if (handle instanceof Number) handle = +handle;
clearTimeout(handle);
throw reason;
}
Promise.prototype.timeout = function (ms, message) {
ms = +ms;
var ret = this.then().cancellable();
ret._cancellationParent = this;
var handle = setTimeout(function timeoutTimeout() {
afterTimeout(ret, message);
}, ms);
return ret._then(successClear, failureClear, undefined, handle, undefined);
};
};
},{"./util.js":38}],37:[function(_dereq_,module,exports){
"use strict";
module.exports = function (Promise, apiRejection, tryConvertToPromise,
createContext) {
var TypeError = _dereq_("./errors.js").TypeError;
var inherits = _dereq_("./util.js").inherits;
var PromiseInspection = Promise.PromiseInspection;
function inspectionMapper(inspections) {
var len = inspections.length;
for (var i = 0; i < len; ++i) {
var inspection = inspections[i];
if (inspection.isRejected()) {
return Promise.reject(inspection.error());
}
inspections[i] = inspection._settledValue;
}
return inspections;
}
function thrower(e) {
setTimeout(function(){throw e;}, 0);
}
function castPreservingDisposable(thenable) {
var maybePromise = tryConvertToPromise(thenable);
if (maybePromise !== thenable &&
typeof thenable._isDisposable === "function" &&
typeof thenable._getDisposer === "function" &&
thenable._isDisposable()) {
maybePromise._setDisposable(thenable._getDisposer());
}
return maybePromise;
}
function dispose(resources, inspection) {
var i = 0;
var len = resources.length;
var ret = Promise.defer();
function iterator() {
if (i >= len) return ret.resolve();
var maybePromise = castPreservingDisposable(resources[i++]);
if (maybePromise instanceof Promise &&
maybePromise._isDisposable()) {
try {
maybePromise = tryConvertToPromise(
maybePromise._getDisposer().tryDispose(inspection),
resources.promise);
} catch (e) {
return thrower(e);
}
if (maybePromise instanceof Promise) {
return maybePromise._then(iterator, thrower,
null, null, null);
}
}
iterator();
}
iterator();
return ret.promise;
}
function disposerSuccess(value) {
var inspection = new PromiseInspection();
inspection._settledValue = value;
inspection._bitField = 268435456;
return dispose(this, inspection).thenReturn(value);
}
function disposerFail(reason) {
var inspection = new PromiseInspection();
inspection._settledValue = reason;
inspection._bitField = 134217728;
return dispose(this, inspection).thenThrow(reason);
}
function Disposer(data, promise, context) {
this._data = data;
this._promise = promise;
this._context = context;
}
Disposer.prototype.data = function () {
return this._data;
};
Disposer.prototype.promise = function () {
return this._promise;
};
Disposer.prototype.resource = function () {
if (this.promise().isFulfilled()) {
return this.promise().value();
}
return null;
};
Disposer.prototype.tryDispose = function(inspection) {
var resource = this.resource();
var context = this._context;
if (context !== undefined) context._pushContext();
var ret = resource !== null
? this.doDispose(resource, inspection) : null;
if (context !== undefined) context._popContext();
this._promise._unsetDisposable();
this._data = null;
return ret;
};
Disposer.isDisposer = function (d) {
return (d != null &&
typeof d.resource === "function" &&
typeof d.tryDispose === "function");
};
function FunctionDisposer(fn, promise, context) {
this.constructor$(fn, promise, context);
}
inherits(FunctionDisposer, Disposer);
FunctionDisposer.prototype.doDispose = function (resource, inspection) {
var fn = this.data();
return fn.call(resource, resource, inspection);
};
function maybeUnwrapDisposer(value) {
if (Disposer.isDisposer(value)) {
this.resources[this.index]._setDisposable(value);
return value.promise();
}
return value;
}
Promise.using = function () {
var len = arguments.length;
if (len < 2) return apiRejection(
"you must pass at least 2 arguments to Promise.using");
var fn = arguments[len - 1];
if (typeof fn !== "function") return apiRejection("fn must be a function\u000a\u000a See http://goo.gl/916lJJ\u000a");
len--;
var resources = new Array(len);
for (var i = 0; i < len; ++i) {
var resource = arguments[i];
if (Disposer.isDisposer(resource)) {
var disposer = resource;
resource = resource.promise();
resource._setDisposable(disposer);
} else {
var maybePromise = tryConvertToPromise(resource);
if (maybePromise instanceof Promise) {
resource =
maybePromise._then(maybeUnwrapDisposer, null, null, {
resources: resources,
index: i
}, undefined);
}
}
resources[i] = resource;
}
var promise = Promise.settle(resources)
.then(inspectionMapper)
.then(function(vals) {
promise._pushContext();
var ret;
try {
ret = fn.apply(undefined, vals);
} finally {
promise._popContext();
}
return ret;
})
._then(
disposerSuccess, disposerFail, undefined, resources, undefined);
resources.promise = promise;
return promise;
};
Promise.prototype._setDisposable = function (disposer) {
this._bitField = this._bitField | 262144;
this._disposer = disposer;
};
Promise.prototype._isDisposable = function () {
return (this._bitField & 262144) > 0;
};
Promise.prototype._getDisposer = function () {
return this._disposer;
};
Promise.prototype._unsetDisposable = function () {
this._bitField = this._bitField & (~262144);
this._disposer = undefined;
};
Promise.prototype.disposer = function (fn) {
if (typeof fn === "function") {
return new FunctionDisposer(fn, this, createContext());
}
throw new TypeError();
};
};
},{"./errors.js":13,"./util.js":38}],38:[function(_dereq_,module,exports){
"use strict";
var es5 = _dereq_("./es5.js");
var canEvaluate = typeof navigator == "undefined";
var haveGetters = (function(){
try {
var o = {};
es5.defineProperty(o, "f", {
get: function () {
return 3;
}
});
return o.f === 3;
}
catch (e) {
return false;
}
})();
var errorObj = {e: {}};
var tryCatchTarget;
function tryCatcher() {
try {
var target = tryCatchTarget;
tryCatchTarget = null;
return target.apply(this, arguments);
} catch (e) {
errorObj.e = e;
return errorObj;
}
}
function tryCatch(fn) {
tryCatchTarget = fn;
return tryCatcher;
}
var inherits = function(Child, Parent) {
var hasProp = {}.hasOwnProperty;
function T() {
this.constructor = Child;
this.constructor$ = Parent;
for (var propertyName in Parent.prototype) {
if (hasProp.call(Parent.prototype, propertyName) &&
propertyName.charAt(propertyName.length-1) !== "$"
) {
this[propertyName + "$"] = Parent.prototype[propertyName];
}
}
}
T.prototype = Parent.prototype;
Child.prototype = new T();
return Child.prototype;
};
function isPrimitive(val) {
return val == null || val === true || val === false ||
typeof val === "string" || typeof val === "number";
}
function isObject(value) {
return !isPrimitive(value);
}
function maybeWrapAsError(maybeError) {
if (!isPrimitive(maybeError)) return maybeError;
return new Error(safeToString(maybeError));
}
function withAppended(target, appendee) {
var len = target.length;
var ret = new Array(len + 1);
var i;
for (i = 0; i < len; ++i) {
ret[i] = target[i];
}
ret[i] = appendee;
return ret;
}
function getDataPropertyOrDefault(obj, key, defaultValue) {
if (es5.isES5) {
var desc = Object.getOwnPropertyDescriptor(obj, key);
if (desc != null) {
return desc.get == null && desc.set == null
? desc.value
: defaultValue;
}
} else {
return {}.hasOwnProperty.call(obj, key) ? obj[key] : undefined;
}
}
function notEnumerableProp(obj, name, value) {
if (isPrimitive(obj)) return obj;
var descriptor = {
value: value,
configurable: true,
enumerable: false,
writable: true
};
es5.defineProperty(obj, name, descriptor);
return obj;
}
function thrower(r) {
throw r;
}
var inheritedDataKeys = (function() {
var excludedPrototypes = [
Array.prototype,
Object.prototype,
Function.prototype
];
var isExcludedProto = function(val) {
for (var i = 0; i < excludedPrototypes.length; ++i) {
if (excludedPrototypes[i] === val) {
return true;
}
}
return false;
};
if (es5.isES5) {
var getKeys = Object.getOwnPropertyNames;
return function(obj) {
var ret = [];
var visitedKeys = Object.create(null);
while (obj != null && !isExcludedProto(obj)) {
var keys;
try {
keys = getKeys(obj);
} catch (e) {
return ret;
}
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
if (visitedKeys[key]) continue;
visitedKeys[key] = true;
var desc = Object.getOwnPropertyDescriptor(obj, key);
if (desc != null && desc.get == null && desc.set == null) {
ret.push(key);
}
}
obj = es5.getPrototypeOf(obj);
}
return ret;
};
} else {
var hasProp = {}.hasOwnProperty;
return function(obj) {
if (isExcludedProto(obj)) return [];
var ret = [];
/*jshint forin:false */
enumeration: for (var key in obj) {
if (hasProp.call(obj, key)) {
ret.push(key);
} else {
for (var i = 0; i < excludedPrototypes.length; ++i) {
if (hasProp.call(excludedPrototypes[i], key)) {
continue enumeration;
}
}
ret.push(key);
}
}
return ret;
};
}
})();
var thisAssignmentPattern = /this\s*\.\s*\S+\s*=/;
function isClass(fn) {
try {
if (typeof fn === "function") {
var keys = es5.names(fn.prototype);
var hasMethods = es5.isES5 && keys.length > 1;
var hasMethodsOtherThanConstructor = keys.length > 0 &&
!(keys.length === 1 && keys[0] === "constructor");
var hasThisAssignmentAndStaticMethods =
thisAssignmentPattern.test(fn + "") && es5.names(fn).length > 0;
if (hasMethods || hasMethodsOtherThanConstructor ||
hasThisAssignmentAndStaticMethods) {
return true;
}
}
return false;
} catch (e) {
return false;
}
}
function toFastProperties(obj) {
/*jshint -W027,-W055,-W031*/
function f() {}
f.prototype = obj;
var l = 8;
while (l--) new f();
return obj;
eval(obj);
}
var rident = /^[a-z$_][a-z$_0-9]*$/i;
function isIdentifier(str) {
return rident.test(str);
}
function filledRange(count, prefix, suffix) {
var ret = new Array(count);
for(var i = 0; i < count; ++i) {
ret[i] = prefix + i + suffix;
}
return ret;
}
function safeToString(obj) {
try {
return obj + "";
} catch (e) {
return "[no string representation]";
}
}
function markAsOriginatingFromRejection(e) {
try {
notEnumerableProp(e, "isOperational", true);
}
catch(ignore) {}
}
function originatesFromRejection(e) {
if (e == null) return false;
return ((e instanceof Error["__BluebirdErrorTypes__"].OperationalError) ||
e["isOperational"] === true);
}
function canAttachTrace(obj) {
return obj instanceof Error && es5.propertyIsWritable(obj, "stack");
}
var ensureErrorObject = (function() {
if (!("stack" in new Error())) {
return function(value) {
if (canAttachTrace(value)) return value;
try {throw new Error(safeToString(value));}
catch(err) {return err;}
};
} else {
return function(value) {
if (canAttachTrace(value)) return value;
return new Error(safeToString(value));
};
}
})();
function classString(obj) {
return {}.toString.call(obj);
}
function copyDescriptors(from, to, filter) {
var keys = es5.names(from);
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
if (filter(key)) {
try {
es5.defineProperty(to, key, es5.getDescriptor(from, key));
} catch (ignore) {}
}
}
}
var ret = {
isClass: isClass,
isIdentifier: isIdentifier,
inheritedDataKeys: inheritedDataKeys,
getDataPropertyOrDefault: getDataPropertyOrDefault,
thrower: thrower,
isArray: es5.isArray,
haveGetters: haveGetters,
notEnumerableProp: notEnumerableProp,
isPrimitive: isPrimitive,
isObject: isObject,
canEvaluate: canEvaluate,
errorObj: errorObj,
tryCatch: tryCatch,
inherits: inherits,
withAppended: withAppended,
maybeWrapAsError: maybeWrapAsError,
toFastProperties: toFastProperties,
filledRange: filledRange,
toString: safeToString,
canAttachTrace: canAttachTrace,
ensureErrorObject: ensureErrorObject,
originatesFromRejection: originatesFromRejection,
markAsOriginatingFromRejection: markAsOriginatingFromRejection,
classString: classString,
copyDescriptors: copyDescriptors,
hasDevTools: typeof chrome !== "undefined" && chrome &&
typeof chrome.loadTimes === "function",
isNode: typeof process !== "undefined" &&
classString(process).toLowerCase() === "[object process]"
};
ret.isRecentNode = ret.isNode && (function() {
var version = process.versions.node.split(".").map(Number);
return (version[0] === 0 && version[1] > 10) || (version[0] > 0);
})();
if (ret.isNode) ret.toFastProperties(process);
try {throw new Error(); } catch (e) {ret.lastLineError = e;}
module.exports = ret;
},{"./es5.js":14}]},{},[4])(4)
}); ;if (typeof window !== 'undefined' && window !== null) { window.P = window.Promise; } else if (typeof self !== 'undefined' && self !== null) { self.P = self.Promise; }
}).call(this,require(53),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"53":53}]},{},[21])(21)
}); | Build unexpected.js
| unexpected.js | Build unexpected.js | <ide><path>nexpected.js
<ide>
<ide> expect.addAssertion('<object|function> [not] to have own property <string>', function (expect, subject, key) {
<ide> expect(subject.hasOwnProperty(key), '[not] to be truthy');
<add> return subject[key];
<add> });
<add>
<add> expect.addAssertion('<object|function> [not] to have (enumerable|configurable|writable) property <string>', function (expect, subject, key) {
<add> var descriptor = expect.alternations[0];
<add> expect(Object.getOwnPropertyDescriptor(subject, key)[descriptor], '[not] to be truthy');
<ide> return subject[key];
<ide> });
<ide> |
|
JavaScript | apache-2.0 | ca99390b2d987fec6910a22a6d0f808180afb9fb | 0 | emig/data-models,eHealthAfrica/data-models | 'use strict';
module.exports = {
'case': require('./Case.json'),
'dailyDelivery': require('./DailyDelivery.json'),
'deliveryRound': require('./DeliveryRound.json'),
'driver': require('./Driver.json'),
'facilityRound': require('./FacilityRound.json'),
'packingList': require('./PackingList.json'),
'person': require('./Person.json'),
'pickedProduct': require('./PickedProduct.json'),
'product': require('./Product.json'),
'draft-04': require('./draft-04.json')
};
| schemas/index.js | 'use strict';
var fs = require('fs');
var path = require('path');
var cwd = path.join(__dirname, '/');
function isJSON(file) {
return file.match(/.json$/);
}
function toLowerCamelCase(str) {
return str.charAt(0).toLowerCase() + str.slice(1);
}
function appendToExports(file) {
var name = toLowerCamelCase(file).replace('.json', '');
exports[name] = require(cwd + file);
}
fs.readdirSync(cwd)
.filter(isJSON)
.forEach(appendToExports);
| Don't rely on fs.readdirSync to load schemas
Browserify/brfs can't handle this properly as described in https://github.com/substack/brfs/issues/36
and we want to use this module in the lr-sense-followup-app on the
client side (for specs)
| schemas/index.js | Don't rely on fs.readdirSync to load schemas | <ide><path>chemas/index.js
<ide> 'use strict';
<ide>
<del>var fs = require('fs');
<del>var path = require('path');
<del>
<del>var cwd = path.join(__dirname, '/');
<del>
<del>function isJSON(file) {
<del> return file.match(/.json$/);
<del>}
<del>
<del>function toLowerCamelCase(str) {
<del> return str.charAt(0).toLowerCase() + str.slice(1);
<del>}
<del>
<del>function appendToExports(file) {
<del> var name = toLowerCamelCase(file).replace('.json', '');
<del> exports[name] = require(cwd + file);
<del>}
<del>
<del>fs.readdirSync(cwd)
<del> .filter(isJSON)
<del> .forEach(appendToExports);
<add>module.exports = {
<add> 'case': require('./Case.json'),
<add> 'dailyDelivery': require('./DailyDelivery.json'),
<add> 'deliveryRound': require('./DeliveryRound.json'),
<add> 'driver': require('./Driver.json'),
<add> 'facilityRound': require('./FacilityRound.json'),
<add> 'packingList': require('./PackingList.json'),
<add> 'person': require('./Person.json'),
<add> 'pickedProduct': require('./PickedProduct.json'),
<add> 'product': require('./Product.json'),
<add> 'draft-04': require('./draft-04.json')
<add>}; |
|
Java | mit | 87fbb8ec987a68271adc0f43bd65593eeb91d2c1 | 0 | Shredder121/github-api,recena/github-api,stephenc/github-api,jeffnelson/github-api,kohsuke/github-api | package org.kohsuke.github;
import com.infradna.tool.bridge_method_injector.WithBridgeMethods;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.io.IOException;
import java.net.URL;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
/**
* A commit in a repository.
*
* @author Kohsuke Kawaguchi
* @see GHRepository#getCommit(String)
* @see GHCommitComment#getCommit()
*/
@SuppressFBWarnings(value = {"NP_UNWRITTEN_FIELD", "UWF_UNWRITTEN_FIELD"},
justification = "JSON API")
public class GHCommit {
private GHRepository owner;
private ShortInfo commit;
/**
* Short summary of this commit.
*/
@SuppressFBWarnings(value = {"UWF_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD", "UWF_UNWRITTEN_FIELD",
"NP_UNWRITTEN_FIELD", "UWF_UNWRITTEN_FIELD"}, justification = "JSON API")
public static class ShortInfo {
private GHAuthor author;
private GHAuthor committer;
private String message;
private int comment_count;
@WithBridgeMethods(value = GHAuthor.class, castRequired = true)
public GitUser getAuthor() {
return author;
}
public Date getAuthoredDate() {
return GitHub.parseDate(author.date);
}
@WithBridgeMethods(value = GHAuthor.class, castRequired = true)
public GitUser getCommitter() {
return committer;
}
public Date getCommitDate() {
return GitHub.parseDate(committer.date);
}
/**
* Commit message.
*/
public String getMessage() {
return message;
}
public int getCommentCount() {
return comment_count;
}
}
/**
* @deprecated Use {@link GitUser} instead.
*/
public static class GHAuthor extends GitUser {
private String date;
}
public static class Stats {
int total,additions,deletions;
}
/**
* A file that was modified.
*/
@SuppressFBWarnings(value = "UWF_UNWRITTEN_FIELD",
justification = "It's being initilized by JSON deserialization")
public static class File {
String status;
int changes,additions,deletions;
String raw_url, blob_url, sha, patch;
String filename, previous_filename;
/**
* Number of lines added + removed.
*/
public int getLinesChanged() {
return changes;
}
/**
* Number of lines added.
*/
public int getLinesAdded() {
return additions;
}
/**
* Number of lines removed.
*/
public int getLinesDeleted() {
return deletions;
}
/**
* "modified", "added", or "removed"
*/
public String getStatus() {
return status;
}
/**
* Full path in the repository.
*/
@SuppressFBWarnings(value = "NM_CONFUSING",
justification = "It's a part of the library's API and cannot be renamed")
public String getFileName() {
return filename;
}
/**
* Previous path, in case file has moved.
*/
public String getPreviousFilename() {
return previous_filename;
}
/**
* The actual change.
*/
public String getPatch() {
return patch;
}
/**
* URL like 'https://raw.github.com/jenkinsci/jenkins/4eb17c197dfdcf8ef7ff87eb160f24f6a20b7f0e/core/pom.xml'
* that resolves to the actual content of the file.
*/
public URL getRawUrl() {
return GitHub.parseURL(raw_url);
}
/**
* URL like 'https://github.com/jenkinsci/jenkins/blob/1182e2ebb1734d0653142bd422ad33c21437f7cf/core/pom.xml'
* that resolves to the HTML page that describes this file.
*/
public URL getBlobUrl() {
return GitHub.parseURL(blob_url);
}
/**
* [0-9a-f]{40} SHA1 checksum.
*/
public String getSha() {
return sha;
}
}
public static class Parent {
@SuppressFBWarnings(value = "UUF_UNUSED_FIELD", justification = "We don't provide it in API now")
String url;
String sha;
}
static class User {
// TODO: what if someone who doesn't have an account on GitHub makes a commit?
@SuppressFBWarnings(value = "UUF_UNUSED_FIELD", justification = "We don't provide it in API now")
String url,avatar_url,gravatar_id;
@SuppressFBWarnings(value = "UUF_UNUSED_FIELD", justification = "We don't provide it in API now")
int id;
String login;
}
String url,html_url,sha;
List<File> files;
Stats stats;
List<Parent> parents;
User author,committer;
public ShortInfo getCommitShortInfo() throws IOException {
if (commit==null)
populate();
return commit;
}
/**
* The repository that contains the commit.
*/
public GHRepository getOwner() {
return owner;
}
/**
* Number of lines added + removed.
*/
public int getLinesChanged() throws IOException {
populate();
return stats.total;
}
/**
* Number of lines added.
*/
public int getLinesAdded() throws IOException {
populate();
return stats.additions;
}
/**
* Number of lines removed.
*/
public int getLinesDeleted() throws IOException {
populate();
return stats.deletions;
}
/**
* URL of this commit like "https://github.com/kohsuke/sandbox-ant/commit/8ae38db0ea5837313ab5f39d43a6f73de3bd9000"
*/
public URL getHtmlUrl() {
return GitHub.parseURL(html_url);
}
/**
* [0-9a-f]{40} SHA1 checksum.
*/
public String getSHA1() {
return sha;
}
/**
* List of files changed/added/removed in this commit.
*
* @return
* Can be empty but never null.
*/
public List<File> getFiles() throws IOException {
populate();
return files!=null ? Collections.unmodifiableList(files) : Collections.<File>emptyList();
}
/**
* Returns the SHA1 of parent commit objects.
*/
public List<String> getParentSHA1s() {
if (parents==null) return Collections.emptyList();
return new AbstractList<String>() {
@Override
public String get(int index) {
return parents.get(index).sha;
}
@Override
public int size() {
return parents.size();
}
};
}
/**
* Resolves the parent commit objects and return them.
*/
public List<GHCommit> getParents() throws IOException {
List<GHCommit> r = new ArrayList<GHCommit>();
for (String sha1 : getParentSHA1s())
r.add(owner.getCommit(sha1));
return r;
}
public GHUser getAuthor() throws IOException {
return resolveUser(author);
}
/**
* Gets the date the change was authored on.
* @return the date the change was authored on.
* @throws IOException if the information was not already fetched and an attempt at fetching the information failed.
*/
public Date getAuthoredDate() throws IOException {
return getCommitShortInfo().getAuthoredDate();
}
public GHUser getCommitter() throws IOException {
return resolveUser(committer);
}
/**
* Gets the date the change was committed on.
*
* @return the date the change was committed on.
* @throws IOException if the information was not already fetched and an attempt at fetching the information failed.
*/
public Date getCommitDate() throws IOException {
return getCommitShortInfo().getCommitDate();
}
private GHUser resolveUser(User author) throws IOException {
if (author==null || author.login==null) return null;
return owner.root.getUser(author.login);
}
/**
* Lists up all the commit comments in this repository.
*/
public PagedIterable<GHCommitComment> listComments() {
return new PagedIterable<GHCommitComment>() {
public PagedIterator<GHCommitComment> _iterator(int pageSize) {
return new PagedIterator<GHCommitComment>(owner.root.retrieve().asIterator(String.format("/repos/%s/%s/commits/%s/comments", owner.getOwnerName(), owner.getName(), sha), GHCommitComment[].class, pageSize)) {
@Override
protected void wrapUp(GHCommitComment[] page) {
for (GHCommitComment c : page)
c.wrap(owner);
}
};
}
};
}
/**
* Creates a commit comment.
*
* I'm not sure how path/line/position parameters interact with each other.
*/
public GHCommitComment createComment(String body, String path, Integer line, Integer position) throws IOException {
GHCommitComment r = new Requester(owner.root)
.with("body",body)
.with("path",path)
.with("line",line)
.with("position",position)
.to(String.format("/repos/%s/%s/commits/%s/comments",owner.getOwnerName(),owner.getName(),sha),GHCommitComment.class);
return r.wrap(owner);
}
public GHCommitComment createComment(String body) throws IOException {
return createComment(body, null, null, null);
}
/**
* Gets the status of this commit, newer ones first.
*/
public PagedIterable<GHCommitStatus> listStatuses() throws IOException {
return owner.listCommitStatuses(sha);
}
/**
* Gets the last status of this commit, which is what gets shown in the UI.
*/
public GHCommitStatus getLastStatus() throws IOException {
return owner.getLastCommitStatus(sha);
}
/**
* Some of the fields are not always filled in when this object is retrieved as a part of another API call.
*/
void populate() throws IOException {
if (files==null && stats==null)
owner.root.retrieve().to(owner.getApiTailUrl("commits/" + sha), this);
}
GHCommit wrapUp(GHRepository owner) {
this.owner = owner;
return this;
}
}
| src/main/java/org/kohsuke/github/GHCommit.java | package org.kohsuke.github;
import com.infradna.tool.bridge_method_injector.WithBridgeMethods;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.io.IOException;
import java.net.URL;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
/**
* A commit in a repository.
*
* @author Kohsuke Kawaguchi
* @see GHRepository#getCommit(String)
* @see GHCommitComment#getCommit()
*/
@SuppressFBWarnings(value = {"NP_UNWRITTEN_FIELD", "UWF_UNWRITTEN_FIELD"},
justification = "JSON API")
public class GHCommit {
private GHRepository owner;
private ShortInfo commit;
/**
* Short summary of this commit.
*/
@SuppressFBWarnings(value = {"UWF_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD", "UWF_UNWRITTEN_FIELD",
"NP_UNWRITTEN_FIELD", "UWF_UNWRITTEN_FIELD"}, justification = "JSON API")
public static class ShortInfo {
private GHAuthor author;
private GHAuthor committer;
private String message;
private int comment_count;
@WithBridgeMethods(value = GHAuthor.class, castRequired = true)
public GitUser getAuthor() {
return author;
}
public Date getAuthoredDate() {
return GitHub.parseDate(author.date);
}
@WithBridgeMethods(value = GHAuthor.class, castRequired = true)
public GitUser getCommitter() {
return committer;
}
public Date getCommitDate() {
return GitHub.parseDate(author.date);
}
/**
* Commit message.
*/
public String getMessage() {
return message;
}
public int getCommentCount() {
return comment_count;
}
}
/**
* @deprecated Use {@link GitUser} instead.
*/
public static class GHAuthor extends GitUser {
private String date;
}
public static class Stats {
int total,additions,deletions;
}
/**
* A file that was modified.
*/
@SuppressFBWarnings(value = "UWF_UNWRITTEN_FIELD",
justification = "It's being initilized by JSON deserialization")
public static class File {
String status;
int changes,additions,deletions;
String raw_url, blob_url, sha, patch;
String filename, previous_filename;
/**
* Number of lines added + removed.
*/
public int getLinesChanged() {
return changes;
}
/**
* Number of lines added.
*/
public int getLinesAdded() {
return additions;
}
/**
* Number of lines removed.
*/
public int getLinesDeleted() {
return deletions;
}
/**
* "modified", "added", or "removed"
*/
public String getStatus() {
return status;
}
/**
* Full path in the repository.
*/
@SuppressFBWarnings(value = "NM_CONFUSING",
justification = "It's a part of the library's API and cannot be renamed")
public String getFileName() {
return filename;
}
/**
* Previous path, in case file has moved.
*/
public String getPreviousFilename() {
return previous_filename;
}
/**
* The actual change.
*/
public String getPatch() {
return patch;
}
/**
* URL like 'https://raw.github.com/jenkinsci/jenkins/4eb17c197dfdcf8ef7ff87eb160f24f6a20b7f0e/core/pom.xml'
* that resolves to the actual content of the file.
*/
public URL getRawUrl() {
return GitHub.parseURL(raw_url);
}
/**
* URL like 'https://github.com/jenkinsci/jenkins/blob/1182e2ebb1734d0653142bd422ad33c21437f7cf/core/pom.xml'
* that resolves to the HTML page that describes this file.
*/
public URL getBlobUrl() {
return GitHub.parseURL(blob_url);
}
/**
* [0-9a-f]{40} SHA1 checksum.
*/
public String getSha() {
return sha;
}
}
public static class Parent {
@SuppressFBWarnings(value = "UUF_UNUSED_FIELD", justification = "We don't provide it in API now")
String url;
String sha;
}
static class User {
// TODO: what if someone who doesn't have an account on GitHub makes a commit?
@SuppressFBWarnings(value = "UUF_UNUSED_FIELD", justification = "We don't provide it in API now")
String url,avatar_url,gravatar_id;
@SuppressFBWarnings(value = "UUF_UNUSED_FIELD", justification = "We don't provide it in API now")
int id;
String login;
}
String url,html_url,sha;
List<File> files;
Stats stats;
List<Parent> parents;
User author,committer;
public ShortInfo getCommitShortInfo() throws IOException {
if (commit==null)
populate();
return commit;
}
/**
* The repository that contains the commit.
*/
public GHRepository getOwner() {
return owner;
}
/**
* Number of lines added + removed.
*/
public int getLinesChanged() throws IOException {
populate();
return stats.total;
}
/**
* Number of lines added.
*/
public int getLinesAdded() throws IOException {
populate();
return stats.additions;
}
/**
* Number of lines removed.
*/
public int getLinesDeleted() throws IOException {
populate();
return stats.deletions;
}
/**
* URL of this commit like "https://github.com/kohsuke/sandbox-ant/commit/8ae38db0ea5837313ab5f39d43a6f73de3bd9000"
*/
public URL getHtmlUrl() {
return GitHub.parseURL(html_url);
}
/**
* [0-9a-f]{40} SHA1 checksum.
*/
public String getSHA1() {
return sha;
}
/**
* List of files changed/added/removed in this commit.
*
* @return
* Can be empty but never null.
*/
public List<File> getFiles() throws IOException {
populate();
return files!=null ? Collections.unmodifiableList(files) : Collections.<File>emptyList();
}
/**
* Returns the SHA1 of parent commit objects.
*/
public List<String> getParentSHA1s() {
if (parents==null) return Collections.emptyList();
return new AbstractList<String>() {
@Override
public String get(int index) {
return parents.get(index).sha;
}
@Override
public int size() {
return parents.size();
}
};
}
/**
* Resolves the parent commit objects and return them.
*/
public List<GHCommit> getParents() throws IOException {
List<GHCommit> r = new ArrayList<GHCommit>();
for (String sha1 : getParentSHA1s())
r.add(owner.getCommit(sha1));
return r;
}
public GHUser getAuthor() throws IOException {
return resolveUser(author);
}
/**
* Gets the date the change was authored on.
* @return the date the change was authored on.
* @throws IOException if the information was not already fetched and an attempt at fetching the information failed.
*/
public Date getAuthoredDate() throws IOException {
return getCommitShortInfo().getAuthoredDate();
}
public GHUser getCommitter() throws IOException {
return resolveUser(committer);
}
/**
* Gets the date the change was committed on.
*
* @return the date the change was committed on.
* @throws IOException if the information was not already fetched and an attempt at fetching the information failed.
*/
public Date getCommitDate() throws IOException {
return getCommitShortInfo().getCommitDate();
}
private GHUser resolveUser(User author) throws IOException {
if (author==null || author.login==null) return null;
return owner.root.getUser(author.login);
}
/**
* Lists up all the commit comments in this repository.
*/
public PagedIterable<GHCommitComment> listComments() {
return new PagedIterable<GHCommitComment>() {
public PagedIterator<GHCommitComment> _iterator(int pageSize) {
return new PagedIterator<GHCommitComment>(owner.root.retrieve().asIterator(String.format("/repos/%s/%s/commits/%s/comments", owner.getOwnerName(), owner.getName(), sha), GHCommitComment[].class, pageSize)) {
@Override
protected void wrapUp(GHCommitComment[] page) {
for (GHCommitComment c : page)
c.wrap(owner);
}
};
}
};
}
/**
* Creates a commit comment.
*
* I'm not sure how path/line/position parameters interact with each other.
*/
public GHCommitComment createComment(String body, String path, Integer line, Integer position) throws IOException {
GHCommitComment r = new Requester(owner.root)
.with("body",body)
.with("path",path)
.with("line",line)
.with("position",position)
.to(String.format("/repos/%s/%s/commits/%s/comments",owner.getOwnerName(),owner.getName(),sha),GHCommitComment.class);
return r.wrap(owner);
}
public GHCommitComment createComment(String body) throws IOException {
return createComment(body, null, null, null);
}
/**
* Gets the status of this commit, newer ones first.
*/
public PagedIterable<GHCommitStatus> listStatuses() throws IOException {
return owner.listCommitStatuses(sha);
}
/**
* Gets the last status of this commit, which is what gets shown in the UI.
*/
public GHCommitStatus getLastStatus() throws IOException {
return owner.getLastCommitStatus(sha);
}
/**
* Some of the fields are not always filled in when this object is retrieved as a part of another API call.
*/
void populate() throws IOException {
if (files==null && stats==null)
owner.root.retrieve().to(owner.getApiTailUrl("commits/" + sha), this);
}
GHCommit wrapUp(GHRepository owner) {
this.owner = owner;
return this;
}
}
| Copy/paste error
| src/main/java/org/kohsuke/github/GHCommit.java | Copy/paste error | <ide><path>rc/main/java/org/kohsuke/github/GHCommit.java
<ide> }
<ide>
<ide> public Date getCommitDate() {
<del> return GitHub.parseDate(author.date);
<add> return GitHub.parseDate(committer.date);
<ide> }
<ide>
<ide> /** |
|
Java | bsd-2-clause | d7407758a55d1b8109f46d25e9d4c7ba5fccd641 | 0 | abelbriggs1/runelite,Sethtroll/runelite,runelite/runelite,l2-/runelite,runelite/runelite,Noremac201/runelite,abelbriggs1/runelite,KronosDesign/runelite,l2-/runelite,KronosDesign/runelite,Sethtroll/runelite,abelbriggs1/runelite,devinfrench/runelite,runelite/runelite,Noremac201/runelite,devinfrench/runelite | /*
* Copyright (c) 2018, Tomas Slusny <[email protected]>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package net.runelite.client.plugins.playerindicators;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Polygon;
import lombok.extern.slf4j.Slf4j;
import net.runelite.api.Client;
import net.runelite.api.Player;
import net.runelite.client.ui.overlay.Overlay;
import net.runelite.client.ui.overlay.OverlayPosition;
import net.runelite.client.ui.overlay.OverlayPriority;
import net.runelite.client.ui.overlay.OverlayUtil;
@Slf4j
public class PlayerIndicatorsOverlay extends Overlay
{
private static final Color CYAN = new Color(0, 184, 212);
private static final Color GREEN = new Color(0, 200, 83);
private static final Color PURPLE = new Color(170, 0, 255);
private static final Color RED = new Color(255, 0, 0);
private final Client client;
private final PlayerIndicatorsConfig config;
PlayerIndicatorsOverlay(Client client, PlayerIndicatorsConfig config)
{
this.config = config;
this.client = client;
setPosition(OverlayPosition.DYNAMIC);
setPriority(OverlayPriority.HIGH);
}
@Override
public Dimension render(Graphics2D graphics, Point parent)
{
if (!config.drawOwnName() && !config.drawClanMemberNames()
&& !config.drawFriendNames() && !config.drawNonClanMemberNames())
{
return null;
}
for (Player player : client.getPlayers())
{
if (player == null || player.getName() == null)
{
continue;
}
boolean isClanMember = player.isClanMember();
if (player == client.getLocalPlayer())
{
if (config.drawOwnName())
{
renderPlayerOverlay(graphics, player, CYAN);
}
}
else if (config.drawFriendNames() && player.isFriend())
{
renderPlayerOverlay(graphics, player, GREEN);
}
else if (config.drawClanMemberNames() && isClanMember)
{
renderPlayerOverlay(graphics, player, PURPLE);
}
else if (config.drawNonClanMemberNames() && !isClanMember)
{
renderPlayerOverlay(graphics, player, RED);
}
}
return null;
}
private void renderPlayerOverlay(Graphics2D graphics, Player actor, Color color)
{
if (config.drawTiles())
{
Polygon poly = actor.getCanvasTilePoly();
if (poly != null)
{
OverlayUtil.renderPolygon(graphics, poly, color);
}
}
final String name = actor.getName().replace('\u00A0', ' ');
net.runelite.api.Point textLocation = actor
.getCanvasTextLocation(graphics, name, actor.getLogicalHeight() + 40);
if (textLocation != null)
{
OverlayUtil.renderTextLocation(graphics, textLocation, name, color);
}
}
}
| runelite-client/src/main/java/net/runelite/client/plugins/playerindicators/PlayerIndicatorsOverlay.java | /*
* Copyright (c) 2018, Tomas Slusny <[email protected]>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package net.runelite.client.plugins.playerindicators;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Polygon;
import lombok.extern.slf4j.Slf4j;
import net.runelite.api.Client;
import net.runelite.api.Player;
import net.runelite.client.ui.overlay.Overlay;
import net.runelite.client.ui.overlay.OverlayPosition;
import net.runelite.client.ui.overlay.OverlayPriority;
import net.runelite.client.ui.overlay.OverlayUtil;
@Slf4j
public class PlayerIndicatorsOverlay extends Overlay
{
private static final Color CYAN = new Color(0, 184, 212);
private static final Color GREEN = new Color(0, 200, 83);
private static final Color PURPLE = new Color(170, 0, 255);
private static final Color RED = new Color(255, 0, 0);
private final Client client;
private final PlayerIndicatorsConfig config;
PlayerIndicatorsOverlay(Client client, PlayerIndicatorsConfig config)
{
this.config = config;
this.client = client;
setPosition(OverlayPosition.DYNAMIC);
setPriority(OverlayPriority.HIGH);
}
@Override
public Dimension render(Graphics2D graphics, Point parent)
{
if (!config.drawOwnName() && !config.drawClanMemberNames() &&
!config.drawFriendNames() && !config.drawNonClanMemberNames())
{
return null;
}
for (Player player : client.getPlayers())
{
if (player == null || player.getName() == null)
{
continue;
}
final String name = player.getName();
if (player == client.getLocalPlayer())
{
if (config.drawOwnName())
{
renderPlayerOverlay(graphics, player, CYAN);
}
}
else if (config.drawFriendNames() && client.isFriended(name, false))
{
renderPlayerOverlay(graphics, player, GREEN);
}
else if (config.drawClanMemberNames() && client.isClanMember(name))
{
renderPlayerOverlay(graphics, player, PURPLE);
}
else if (config.drawNonClanMemberNames() && !client.isClanMember(name))
{
renderPlayerOverlay(graphics, player, RED);
}
}
return null;
}
private void renderPlayerOverlay(Graphics2D graphics, Player actor, Color color)
{
if (config.drawTiles())
{
Polygon poly = actor.getCanvasTilePoly();
if (poly != null)
{
OverlayUtil.renderPolygon(graphics, poly, color);
}
}
final String name = actor.getName().replace('\u00A0', ' ');
net.runelite.api.Point textLocation = actor
.getCanvasTextLocation(graphics, name, actor.getLogicalHeight() + 40);
if (textLocation != null)
{
OverlayUtil.renderTextLocation(graphics, textLocation, name, color);
}
}
}
| player indicators: use new isFriend/isClanMember api
| runelite-client/src/main/java/net/runelite/client/plugins/playerindicators/PlayerIndicatorsOverlay.java | player indicators: use new isFriend/isClanMember api | <ide><path>unelite-client/src/main/java/net/runelite/client/plugins/playerindicators/PlayerIndicatorsOverlay.java
<ide> @Override
<ide> public Dimension render(Graphics2D graphics, Point parent)
<ide> {
<del> if (!config.drawOwnName() && !config.drawClanMemberNames() &&
<del> !config.drawFriendNames() && !config.drawNonClanMemberNames())
<add> if (!config.drawOwnName() && !config.drawClanMemberNames()
<add> && !config.drawFriendNames() && !config.drawNonClanMemberNames())
<ide> {
<ide> return null;
<ide> }
<ide> continue;
<ide> }
<ide>
<del> final String name = player.getName();
<add> boolean isClanMember = player.isClanMember();
<ide>
<ide> if (player == client.getLocalPlayer())
<ide> {
<ide> renderPlayerOverlay(graphics, player, CYAN);
<ide> }
<ide> }
<del> else if (config.drawFriendNames() && client.isFriended(name, false))
<add> else if (config.drawFriendNames() && player.isFriend())
<ide> {
<ide> renderPlayerOverlay(graphics, player, GREEN);
<ide> }
<del> else if (config.drawClanMemberNames() && client.isClanMember(name))
<add> else if (config.drawClanMemberNames() && isClanMember)
<ide> {
<ide> renderPlayerOverlay(graphics, player, PURPLE);
<ide> }
<del> else if (config.drawNonClanMemberNames() && !client.isClanMember(name))
<add> else if (config.drawNonClanMemberNames() && !isClanMember)
<ide> {
<ide> renderPlayerOverlay(graphics, player, RED);
<ide> } |
|
Java | lgpl-2.1 | 09fadb40e4590b0d59848f11600ca7fb76167a2b | 0 | Darkhax-Minecraft/Dark-Utilities | package net.darkhax.darkutils.blocks;
import net.darkhax.darkutils.DarkUtils;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
public class BlockTrapBase extends Block {
public static final AxisAlignedBB BOUNDS = new AxisAlignedBB(0d, 0d, 0.0625d, 1d, 0.0125d, 1d);
public BlockTrapBase() {
super(Material.ROCK);
this.setCreativeTab(DarkUtils.TAB);
this.setHardness(3.0F);
this.setResistance(10f);
this.setHarvestLevel("pickaxe", 1);
}
private boolean checkForDrop (World world, BlockPos pos, IBlockState state) {
if (!this.canBlockStay(world, pos)) {
this.dropBlockAsItem(world, pos, state, 0);
world.setBlockToAir(pos);
return false;
}
else
return true;
}
@Override
public AxisAlignedBB getBoundingBox (IBlockState state, IBlockAccess source, BlockPos pos) {
return BOUNDS;
}
private boolean canBlockStay (World world, BlockPos pos) {
return !(world.isAirBlock(pos.down()) || !world.isSideSolid(pos.down(), EnumFacing.UP));
}
@Override
public boolean canPlaceBlockAt (World world, BlockPos pos) {
return super.canPlaceBlockAt(world, pos) && this.canBlockStay(world, pos);
}
@Override
public void onNeighborBlockChange (World world, BlockPos pos, IBlockState state, Block neighborBlock) {
this.checkForDrop(world, pos, state);
}
@Override
public boolean isFullCube (IBlockState state) {
return false;
}
@Override
public boolean isOpaqueCube (IBlockState state) {
return false;
}
} | src/main/java/net/darkhax/darkutils/blocks/BlockTrapBase.java | package net.darkhax.darkutils.blocks;
import net.darkhax.darkutils.DarkUtils;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
public class BlockTrapBase extends Block {
public static final AxisAlignedBB BOUNDS = new AxisAlignedBB(0d, 0d, 0.0625d, 1d, 0.0125d, 1d);
public BlockTrapBase() {
super(Material.ROCK);
this.setCreativeTab(DarkUtils.TAB);
this.setHardness(3.0F);
this.setResistance(10f);
this.setHarvestLevel("pickaxe", 1);
}
private boolean checkForDrop (World world, BlockPos pos, IBlockState state) {
if (!this.canBlockStay(world, pos)) {
this.dropBlockAsItem(world, pos, state, 0);
world.setBlockToAir(pos);
return false;
}
else
return true;
}
private boolean canBlockStay (World world, BlockPos pos) {
return !(world.isAirBlock(pos.down()) || !world.isSideSolid(pos.down(), EnumFacing.UP));
}
@Override
public boolean canPlaceBlockAt (World world, BlockPos pos) {
return super.canPlaceBlockAt(world, pos) && this.canBlockStay(world, pos);
}
@Override
public void onNeighborBlockChange (World world, BlockPos pos, IBlockState state, Block neighborBlock) {
this.checkForDrop(world, pos, state);
}
@Override
public boolean isFullCube (IBlockState state) {
return false;
}
@Override
public boolean isOpaqueCube (IBlockState state) {
return false;
}
} | Fixed broken block bounds. | src/main/java/net/darkhax/darkutils/blocks/BlockTrapBase.java | Fixed broken block bounds. | <ide><path>rc/main/java/net/darkhax/darkutils/blocks/BlockTrapBase.java
<ide> import net.minecraft.util.EnumFacing;
<ide> import net.minecraft.util.math.AxisAlignedBB;
<ide> import net.minecraft.util.math.BlockPos;
<add>import net.minecraft.world.IBlockAccess;
<ide> import net.minecraft.world.World;
<ide>
<ide> public class BlockTrapBase extends Block {
<ide>
<ide> else
<ide> return true;
<add> }
<add>
<add> @Override
<add> public AxisAlignedBB getBoundingBox (IBlockState state, IBlockAccess source, BlockPos pos) {
<add>
<add> return BOUNDS;
<ide> }
<ide>
<ide> private boolean canBlockStay (World world, BlockPos pos) { |
|
Java | apache-2.0 | cf55d7a356f80cdc2b89811066cc8aedb0264320 | 0 | CS-SI/Orekit,CS-SI/Orekit | /* Copyright 2002-2022 CS GROUP
* Licensed to CS GROUP (CS) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* CS licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.orekit.files.ccsds.ndm.cdm;
import java.util.ArrayList;
import java.util.List;
import org.orekit.data.DataContext;
import org.orekit.files.ccsds.definitions.TimeSystem;
import org.orekit.files.ccsds.ndm.ParsedUnitsBehavior;
import org.orekit.files.ccsds.section.CommentsContainer;
import org.orekit.files.ccsds.section.KvnStructureProcessingState;
import org.orekit.files.ccsds.section.MetadataKey;
import org.orekit.files.ccsds.section.XmlStructureProcessingState;
import org.orekit.files.ccsds.utils.ContextBinding;
import org.orekit.files.ccsds.utils.FileFormat;
import org.orekit.files.ccsds.utils.lexical.ParseToken;
import org.orekit.files.ccsds.utils.lexical.TokenType;
import org.orekit.files.ccsds.utils.parsing.AbstractConstituentParser;
import org.orekit.files.ccsds.utils.parsing.ProcessingState;
import org.orekit.utils.IERSConventions;
/**
* Base class for Conjunction Data Message parsers.
* <p>
* Note than starting with Orekit 11.0, CCSDS message parsers are
* mutable objects that gather the data being parsed, until the
* message is complete and the {@link #parseMessage(org.orekit.data.DataSource)
* parseMessage} method has returned. This implies that parsers
* should <em>not</em> be used in a multi-thread context. The recommended
* way to use parsers is to either dedicate one parser for each message
* and drop it afterwards, or to use a single-thread loop.
* </p>
* @author Melina Vanel
* @since 11.2
*/
public class CdmParser extends AbstractConstituentParser<Cdm, CdmParser> {
/** Comment key. */
private static String COMMENT = "COMMENT";
/** XML relative metadata key. */
private static String RELATIVEMETADATA = "relativeMetadataData";
/** XML metadata key. */
private static String METADATA = "metadata";
/** File header. */
private CdmHeader header;
/** File segments. */
private List<CdmSegment> segments;
/** CDM metadata being read. */
private CdmMetadata metadata;
/** CDM relative metadata being read. */
private CdmRelativeMetadata relativeMetadata;
/** Context binding valid for current metadata. */
private ContextBinding context;
/** CDM general data comments block being read. */
private CommentsContainer commentsBlock;
/** CDM OD parameters logical block being read. */
private ODParameters odParameters;
/** CDM additional parameters logical block being read. */
private AdditionalParameters addParameters;
/** CDM state vector logical block being read. */
private StateVector stateVector;
/** CDM covariance matrix logical block being read. */
private RTNCovariance covMatrix;
/** Processor for global message structure. */
private ProcessingState structureProcessor;
/** Flag to only compute once relative metadata. */
private boolean doRelativeMetadata;
/** Flag to indicate that data block parsing is finished. */
private boolean isDatafinished;
/** Complete constructor.
* <p>
* Calling this constructor directly is not recommended. Users should rather use
* {@link org.orekit.files.ccsds.ndm.ParserBuilder#buildCdmParser()
* parserBuilder.buildCdmParser()}.
* </p>
* @param conventions IERS Conventions
* @param simpleEOP if true, tidal effects are ignored when interpolating EOP
* @param dataContext used to retrieve frames, time scales, etc.
* @param parsedUnitsBehavior behavior to adopt for handling parsed units
*/
public CdmParser(final IERSConventions conventions, final boolean simpleEOP, final DataContext dataContext,
final ParsedUnitsBehavior parsedUnitsBehavior) {
super(Cdm.ROOT, Cdm.FORMAT_VERSION_KEY, conventions, simpleEOP, dataContext, parsedUnitsBehavior);
this.doRelativeMetadata = true;
this.isDatafinished = false;
}
/** {@inheritDoc} */
@Override
public CdmHeader getHeader() {
return header;
}
/** {@inheritDoc} */
@Override
public void reset(final FileFormat fileFormat) {
header = new CdmHeader(1.0);
segments = new ArrayList<>();
metadata = null;
relativeMetadata = null;
context = null;
odParameters = null;
addParameters = null;
stateVector = null;
covMatrix = null;
commentsBlock = null;
if (fileFormat == FileFormat.XML) {
structureProcessor = new XmlStructureProcessingState(Cdm.ROOT, this);
reset(fileFormat, structureProcessor);
} else {
structureProcessor = new KvnStructureProcessingState(this);
reset(fileFormat, new CdmHeaderProcessingState(this));
}
}
/** {@inheritDoc} */
@Override
public boolean prepareHeader() {
anticipateNext(new CdmHeaderProcessingState(this));
return true;
}
/** {@inheritDoc} */
@Override
public boolean inHeader() {
anticipateNext(getFileFormat() == FileFormat.XML ? structureProcessor : this::processMetadataToken);
return true;
}
/** {@inheritDoc} */
@Override
public boolean finalizeHeader() {
anticipateNext(getFileFormat() == FileFormat.XML ? this::processXmlSubStructureToken : structureProcessor);
header.validate(header.getFormatVersion());
return true;
}
/** {@inheritDoc} */
@Override
public boolean prepareMetadata() {
if (metadata != null) {
return false;
}
if (doRelativeMetadata) {
// if parser is just after header it is time to create / read relative metadata,
// their are only initialized once and then shared between metadata for object 1 and 2
relativeMetadata = new CdmRelativeMetadata();
relativeMetadata.setTimeSystem(TimeSystem.UTC);
}
metadata = new CdmMetadata();
metadata.setRelativeMetadata(relativeMetadata);
// As no time system is defined in CDM because all dates are given in UTC,
// time system is set here to UTC, we use relative metadata and not metadata
// because setting time system on metadata implies refusingfurthercomments
// witch would be a problem as metadata comments have not been read yet.
context = new ContextBinding(this::getConventions, this::isSimpleEOP,
this::getDataContext, this::getParsedUnitsBehavior,
() -> null, relativeMetadata::getTimeSystem,
() -> 0.0, () -> 1.0);
anticipateNext(this::processMetadataToken);
return true;
}
/** {@inheritDoc} */
@Override
public boolean inMetadata() {
anticipateNext(getFileFormat() == FileFormat.XML ? this::processXmlSubStructureToken : this::processGeneralCommentToken);
return true;
}
/** {@inheritDoc} */
@Override
public boolean finalizeMetadata() {
metadata.validate(header.getFormatVersion());
relativeMetadata.validate();
anticipateNext(getFileFormat() == FileFormat.XML ? structureProcessor : structureProcessor);
return true;
}
/** {@inheritDoc} */
@Override
public boolean prepareData() {
// stateVector and RTNCovariance blocks are 2 mandatory data blocks
stateVector = new StateVector();
covMatrix = new RTNCovariance();
// initialize comments block for general data comments
commentsBlock = new CommentsContainer();
anticipateNext(getFileFormat() == FileFormat.XML ? this::processXmlSubStructureToken : this::processGeneralCommentToken);
return true;
}
/** {@inheritDoc} */
@Override
public boolean inData() {
return true;
}
/** {@inheritDoc} */
@Override
public boolean finalizeData() {
// call at the and of data block for object 1 or 2
if (metadata != null) {
final CdmData data = new CdmData(commentsBlock, odParameters, addParameters,
stateVector, covMatrix);
data.validate(header.getFormatVersion());
segments.add(new CdmSegment(metadata, data));
}
metadata = null;
context = null;
odParameters = null;
addParameters = null;
stateVector = null;
covMatrix = null;
commentsBlock = null;
return true;
}
/** {@inheritDoc} */
@Override
public Cdm build() {
// CDM KVN file lack a DATA_STOP keyword, hence we can't call finalizeData()
// automatically before the end of the file
finalizeData();
final Cdm file = new Cdm(header, segments, getConventions(), getDataContext());
return file;
}
/** Add a general comment.
* @param comment comment to add
* @return always return true
*/
boolean addGeneralComment(final String comment) {
return commentsBlock.addComment(comment);
}
/** Manage relative metadata section.
* @param starting if true, parser is entering the section
* otherwise it is leaving the section
* @return always return true
*/
boolean manageRelativeMetadataSection(final boolean starting) {
anticipateNext(starting ? this::processMetadataToken : structureProcessor);
return true;
}
/** Manage relative metadata state vector section.
* @param starting if true, parser is entering the section
* otherwise it is leaving the section
* @return always return true
*/
boolean manageRelativeStateVectorSection(final boolean starting) {
anticipateNext(this::processMetadataToken);
return true;
}
/** Manage OD parameters section.
* @param starting if true, parser is entering the section
* otherwise it is leaving the section
* @return always return true
*/
boolean manageODParametersSection(final boolean starting) {
commentsBlock.refuseFurtherComments();
anticipateNext(starting ? this::processODParamToken : structureProcessor);
return true;
}
/** Manage additional parameters section.
* @param starting if true, parser is entering the section
* otherwise it is leaving the section
* @return always return true
*/
boolean manageAdditionalParametersSection(final boolean starting) {
commentsBlock.refuseFurtherComments();
anticipateNext(starting ? this::processAdditionalParametersToken : structureProcessor);
return true;
}
/** Manage state vector section.
* @param starting if true, parser is entering the section
* otherwise it is leaving the section
* @return always return true
*/
boolean manageStateVectorSection(final boolean starting) {
commentsBlock.refuseFurtherComments();
anticipateNext(starting ? this::processStateVectorToken : structureProcessor);
return true;
}
/** Manage covariance matrix section.
* @param starting if true, parser is entering the section
* otherwise it is leaving the section
* @return always return true
*/
boolean manageCovMatrixSection(final boolean starting) {
commentsBlock.refuseFurtherComments();
anticipateNext(starting ? this::processCovMatrixToken : structureProcessor);
return true;
}
/** Process one metadata token.
* @param token token to process
* @return true if token was processed, false otherwise
*/
private boolean processMetadataToken(final ParseToken token) {
if (isDatafinished && getFileFormat() != FileFormat.XML) {
finalizeData();
isDatafinished = false;
}
if (metadata == null) {
// CDM KVN file lack a META_START keyword, hence we can't call prepareMetadata()
// automatically before the first metadata token arrives
prepareMetadata();
}
inMetadata();
// There can be a COMMENT key at the beginning of relative metadata, but as the relative
// metadata are processed in the same try and catch loop than metadata because Orekit is
// build to read metadata and then data (and not relative metadata), it would be problematic
// to make relative metadata extends comments container(because of the COMMENTS in the middle
// of relativemetadata and metadata section. Indeed, as said in {@link
// #CommentsContainer} COMMENT should only be at the beginning of sections but in this case
// there is a comment at the beginning corresponding to the relative metadata comment
// and 1 in the middle for object 1 metadata and one further for object 2 metadata. That
// is why this special syntax was used and initializes the relative metadata COMMENT once
// at the beginning as relative metadata is not a comment container
if (COMMENT.equals(token.getName()) && doRelativeMetadata ) {
if (token.getType() == TokenType.ENTRY) {
relativeMetadata.addComment(token.getContentAsNormalizedString());
return true;
}
}
doRelativeMetadata = false;
try {
return token.getName() != null &&
CdmRelativeMetadataKey.valueOf(token.getName()).process(token, context, relativeMetadata);
} catch (IllegalArgumentException iaeM) {
try {
return MetadataKey.valueOf(token.getName()).process(token, context, metadata);
} catch (IllegalArgumentException iaeD) {
try {
return CdmMetadataKey.valueOf(token.getName()).process(token, context, metadata);
} catch (IllegalArgumentException iaeC) {
// token has not been recognized
return false;
}
}
}
}
/** Process one XML data substructure token.
* @param token token to process
* @return true if token was processed, false otherwise
*/
private boolean processXmlSubStructureToken(final ParseToken token) {
// As no relativemetadata token exists in the structure processor and as RelativeMetadata keys are
// processed in the same try and catch loop in processMetadatatoken as CdmMetadata keys, if the relativemetadata
// token is read it should be as if the token was equal to metadata to start to initialize relative metadata
// and metadata and to go in the processMetadataToken try and catch loop. The following relativemetadata
// stop should be ignored to stay in the processMetadataToken try and catch loop and the following metadata
// start also ignored to stay in the processMetadataToken try and catch loop. Then arrives the end of metadata
// so we call structure processor with metadata stop. This distinction of cases is useful for relativemetadata
// block followed by metadata block for object 1 and also useful to only close metadata block for object 2.
// The metadata start for object 2 is processed by structureProcessor
if (METADATA.equals(token.getName()) && TokenType.START.equals(token.getType()) ||
RELATIVEMETADATA.equals(token.getName()) && TokenType.STOP.equals(token.getType())) {
anticipateNext(this::processMetadataToken);
return true;
} else if (RELATIVEMETADATA.equals(token.getName()) && TokenType.START.equals(token.getType()) ||
METADATA.equals(token.getName()) && TokenType.STOP.equals(token.getType())) {
final ParseToken replaceToken = new ParseToken(token.getType(), METADATA,
null, token.getUnits(), token.getLineNumber(), token.getFileName());
return structureProcessor.processToken(replaceToken);
} else {
// Relative metadata COMMENT and metadata COMMENT should not be read by XmlSubStructureKey that
// is why 2 cases are distinguished here : the COMMENT for relative metadata and the COMMENT
// for metadata.
if (commentsBlock == null && COMMENT.equals(token.getName())) {
// COMMENT adding for Relative Metadata in XML
if (doRelativeMetadata) {
if (token.getType() == TokenType.ENTRY) {
relativeMetadata.addComment(token.getContentAsNormalizedString());
doRelativeMetadata = false;
return true;
} else {
// if the token Type is still not ENTRY we return true as at the next step
// it will be ENTRY ad we will be able to store the comment (similar treatment
// as OD parameter or Additional parameter or State Vector ... COMMENT treatment.)
return true;
}
}
// COMMENT adding for Metadata in XML
if (!doRelativeMetadata) {
if (token.getType() == TokenType.ENTRY) {
metadata.addComment(token.getContentAsNormalizedString());
return true;
} else {
// same as above
return true;
}
}
}
// to treat XmlSubStructureKey keys ( OD parameters, relative Metadata ...)
try {
return token.getName() != null && !doRelativeMetadata &&
XmlSubStructureKey.valueOf(token.getName()).process(token, this);
} catch (IllegalArgumentException iae) {
// token has not been recognized
return false;
}
}
}
/** Process one comment token.
* @param token token to process
* @return true if token was processed, false otherwise
*/
private boolean processGeneralCommentToken(final ParseToken token) {
if (commentsBlock == null) {
// CDM KVN file lack a META_STOP keyword, hence we can't call finalizeMetadata()
// automatically before the first data token arrives
finalizeMetadata();
// CDM KVN file lack a DATA_START keyword, hence we can't call prepareData()
// automatically before the first data token arrives
prepareData();
}
anticipateNext(getFileFormat() == FileFormat.XML ? this::processXmlSubStructureToken : this::processODParamToken);
if (COMMENT.equals(token.getName()) && commentsBlock.acceptComments()) {
if (token.getType() == TokenType.ENTRY) {
commentsBlock.addComment(token.getContentAsNormalizedString());
}
// in order to be able to differentiate general data comments and next block comment (OD parameters if not empty)
// only 1 line comment is allowed for general data comment.
commentsBlock.refuseFurtherComments();
return true;
} else {
return false;
}
}
/** Process one od parameter data token.
* @param token token to process
* @return true if token was processed, false otherwise
*/
private boolean processODParamToken(final ParseToken token) {
if (odParameters == null) {
odParameters = new ODParameters();
}
anticipateNext(getFileFormat() == FileFormat.XML ? this::processXmlSubStructureToken : this::processAdditionalParametersToken);
try {
return token.getName() != null &&
ODParametersKey.valueOf(token.getName()).process(token, context, odParameters);
} catch (IllegalArgumentException iae) {
// token has not been recognized
return false;
}
}
/** Process one additional parameter data token.
* @param token token to process
* @return true if token was processed, false otherwise
*/
private boolean processAdditionalParametersToken(final ParseToken token) {
if (addParameters == null) {
addParameters = new AdditionalParameters();
}
if (moveCommentsIfEmpty(odParameters, addParameters)) {
// get rid of the empty logical block
odParameters = null;
}
anticipateNext(getFileFormat() == FileFormat.XML ? this::processXmlSubStructureToken : this::processStateVectorToken);
try {
return token.getName() != null &&
AdditionalParametersKey.valueOf(token.getName()).process(token, context, addParameters);
} catch (IllegalArgumentException iae) {
// token has not been recognized
return false;
}
}
/** Process one state vector data token.
* @param token token to process
* @return true if token was processed, false otherwise
*/
private boolean processStateVectorToken(final ParseToken token) {
if (moveCommentsIfEmpty(addParameters, stateVector)) {
// get rid of the empty logical block
addParameters = null;
}
anticipateNext(getFileFormat() == FileFormat.XML ? this::processXmlSubStructureToken : this::processCovMatrixToken);
try {
return token.getName() != null &&
StateVectorKey.valueOf(token.getName()).process(token, context, stateVector);
} catch (IllegalArgumentException iae) {
// token has not been recognized
return false;
}
}
/** Process covariance matrix data token.
* @param token token to process
* @return true if token was processed, false otherwise
*/
private boolean processCovMatrixToken(final ParseToken token) {
isDatafinished = true;
anticipateNext(getFileFormat() == FileFormat.XML ? this::processXmlSubStructureToken : this::processMetadataToken);
try {
return token.getName() != null &&
RTNCovarianceKey.valueOf(token.getName()).process(token, context, covMatrix);
} catch (IllegalArgumentException iae) {
// token has not been recognized
return false;
}
}
/** Move comments from one empty logical block to another logical block.
* @param origin origin block
* @param destination destination block
* @return true if origin block was empty
*/
private boolean moveCommentsIfEmpty(final CommentsContainer origin, final CommentsContainer destination) {
if (origin != null && origin.acceptComments()) {
// origin block is empty, move the existing comments
for (final String comment : origin.getComments()) {
destination.addComment(comment);
}
return true;
} else {
return false;
}
}
}
| src/main/java/org/orekit/files/ccsds/ndm/cdm/CdmParser.java | /* Copyright 2002-2022 CS GROUP
* Licensed to CS GROUP (CS) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* CS licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.orekit.files.ccsds.ndm.cdm;
import java.util.ArrayList;
import java.util.List;
import org.orekit.data.DataContext;
import org.orekit.files.ccsds.definitions.TimeSystem;
import org.orekit.files.ccsds.ndm.ParsedUnitsBehavior;
import org.orekit.files.ccsds.section.CommentsContainer;
import org.orekit.files.ccsds.section.KvnStructureProcessingState;
import org.orekit.files.ccsds.section.MetadataKey;
import org.orekit.files.ccsds.section.XmlStructureProcessingState;
import org.orekit.files.ccsds.utils.ContextBinding;
import org.orekit.files.ccsds.utils.FileFormat;
import org.orekit.files.ccsds.utils.lexical.ParseToken;
import org.orekit.files.ccsds.utils.lexical.TokenType;
import org.orekit.files.ccsds.utils.parsing.AbstractConstituentParser;
import org.orekit.files.ccsds.utils.parsing.ProcessingState;
import org.orekit.utils.IERSConventions;
/**
* Base class for Conjunction Data Message parsers.
* <p>
* Note than starting with Orekit 11.0, CCSDS message parsers are
* mutable objects that gather the data being parsed, until the
* message is complete and the {@link #parseMessage(org.orekit.data.DataSource)
* parseMessage} method has returned. This implies that parsers
* should <em>not</em> be used in a multi-thread context. The recommended
* way to use parsers is to either dedicate one parser for each message
* and drop it afterwards, or to use a single-thread loop.
* </p>
* @param <T> type of the file
* @param <P> type of the parser
* @author Melina Vanel
* @since 11.2
*/
public class CdmParser extends AbstractConstituentParser<Cdm, CdmParser> {
/** Comment key. */
private static String COMMENT = "COMMENT";
/** XML relative metadata key. */
private static String RELATIVEMETADATA = "relativeMetadataData";
/** XML metadata key. */
private static String METADATA = "metadata";
/** File header. */
private CdmHeader header;
/** File segments. */
private List<CdmSegment> segments;
/** CDM metadata being read. */
private CdmMetadata metadata;
/** CDM relative metadata being read. */
private CdmRelativeMetadata relativeMetadata;
/** Context binding valid for current metadata. */
private ContextBinding context;
/** CDM general data comments block being read. */
private CommentsContainer commentsBlock;
/** CDM OD parameters logical block being read. */
private ODParameters odParameters;
/** CDM additional parameters logical block being read. */
private AdditionalParameters addParameters;
/** CDM state vector logical block being read. */
private StateVector stateVector;
/** CDM covariance matrix logical block being read. */
private RTNCovariance covMatrix;
/** Processor for global message structure. */
private ProcessingState structureProcessor;
/** Flag to only compute once relative metadata. */
private boolean doRelativeMetadata;
/** Flag to indicate that data block parsing is finished. */
private boolean isDatafinished;
/** Complete constructor.
* <p>
* Calling this constructor directly is not recommended. Users should rather use
* {@link org.orekit.files.ccsds.ndm.ParserBuilder#buildCdmParser()
* parserBuilder.buildCdmParser()}.
* </p>
* @param conventions IERS Conventions
* @param simpleEOP if true, tidal effects are ignored when interpolating EOP
* @param dataContext used to retrieve frames, time scales, etc.
* @param parsedUnitsBehavior behavior to adopt for handling parsed units
*/
public CdmParser(final IERSConventions conventions, final boolean simpleEOP, final DataContext dataContext,
final ParsedUnitsBehavior parsedUnitsBehavior) {
super(Cdm.ROOT, Cdm.FORMAT_VERSION_KEY, conventions, simpleEOP, dataContext, parsedUnitsBehavior);
this.doRelativeMetadata = true;
this.isDatafinished = false;
}
/** {@inheritDoc} */
@Override
public CdmHeader getHeader() {
return header;
}
/** {@inheritDoc} */
@Override
public void reset(final FileFormat fileFormat) {
header = new CdmHeader(1.0);
segments = new ArrayList<>();
metadata = null;
relativeMetadata = null;
context = null;
odParameters = null;
addParameters = null;
stateVector = null;
covMatrix = null;
commentsBlock = null;
if (fileFormat == FileFormat.XML) {
structureProcessor = new XmlStructureProcessingState(Cdm.ROOT, this);
reset(fileFormat, structureProcessor);
} else {
structureProcessor = new KvnStructureProcessingState(this);
reset(fileFormat, new CdmHeaderProcessingState(this));
}
}
/** {@inheritDoc} */
@Override
public boolean prepareHeader() {
anticipateNext(new CdmHeaderProcessingState(this));
return true;
}
/** {@inheritDoc} */
@Override
public boolean inHeader() {
anticipateNext(getFileFormat() == FileFormat.XML ? structureProcessor : this::processMetadataToken);
return true;
}
/** {@inheritDoc} */
@Override
public boolean finalizeHeader() {
anticipateNext(getFileFormat() == FileFormat.XML ? this::processXmlSubStructureToken : structureProcessor);
header.validate(header.getFormatVersion());
return true;
}
/** {@inheritDoc} */
@Override
public boolean prepareMetadata() {
if (metadata != null) {
return false;
}
if (doRelativeMetadata) {
// if parser is just after header it is time to create / read relative metadata,
// their are only initialized once and then shared between metadata for object 1 and 2
relativeMetadata = new CdmRelativeMetadata();
relativeMetadata.setTimeSystem(TimeSystem.UTC);
}
metadata = new CdmMetadata();
metadata.setRelativeMetadata(relativeMetadata);
// As no time system is defined in CDM because all dates are given in UTC,
// time system is set here to UTC, we use relative metadata and not metadata
// because setting time system on metadata implies refusingfurthercomments
// witch would be a problem as metadata comments have not been read yet.
context = new ContextBinding(this::getConventions, this::isSimpleEOP,
this::getDataContext, this::getParsedUnitsBehavior,
() -> null, relativeMetadata::getTimeSystem,
() -> 0.0, () -> 1.0);
anticipateNext(this::processMetadataToken);
return true;
}
/** {@inheritDoc} */
@Override
public boolean inMetadata() {
anticipateNext(getFileFormat() == FileFormat.XML ? this::processXmlSubStructureToken : this::processGeneralCommentToken);
return true;
}
/** {@inheritDoc} */
@Override
public boolean finalizeMetadata() {
metadata.validate(header.getFormatVersion());
relativeMetadata.validate();
anticipateNext(getFileFormat() == FileFormat.XML ? structureProcessor : structureProcessor);
return true;
}
/** {@inheritDoc} */
@Override
public boolean prepareData() {
// stateVector and RTNCovariance blocks are 2 mandatory data blocks
stateVector = new StateVector();
covMatrix = new RTNCovariance();
// initialize comments block for general data comments
commentsBlock = new CommentsContainer();
anticipateNext(getFileFormat() == FileFormat.XML ? this::processXmlSubStructureToken : this::processGeneralCommentToken);
return true;
}
/** {@inheritDoc} */
@Override
public boolean inData() {
return true;
}
/** {@inheritDoc} */
@Override
public boolean finalizeData() {
// call at the and of data block for object 1 or 2
if (metadata != null) {
final CdmData data = new CdmData(commentsBlock, odParameters, addParameters,
stateVector, covMatrix);
data.validate(header.getFormatVersion());
segments.add(new CdmSegment(metadata, data));
}
metadata = null;
context = null;
odParameters = null;
addParameters = null;
stateVector = null;
covMatrix = null;
commentsBlock = null;
return true;
}
/** {@inheritDoc} */
@Override
public Cdm build() {
// CDM KVN file lack a DATA_STOP keyword, hence we can't call finalizeData()
// automatically before the end of the file
finalizeData();
final Cdm file = new Cdm(header, segments, getConventions(), getDataContext());
return file;
}
/** Add a general comment.
* @param comment comment to add
* @return always return true
*/
boolean addGeneralComment(final String comment) {
return commentsBlock.addComment(comment);
}
/** Manage relative metadata section.
* @param starting if true, parser is entering the section
* otherwise it is leaving the section
* @return always return true
*/
boolean manageRelativeMetadataSection(final boolean starting) {
anticipateNext(starting ? this::processMetadataToken : structureProcessor);
return true;
}
/** Manage relative metadata state vector section.
* @param starting if true, parser is entering the section
* otherwise it is leaving the section
* @return always return true
*/
boolean manageRelativeStateVectorSection(final boolean starting) {
anticipateNext(this::processMetadataToken);
return true;
}
/** Manage OD parameters section.
* @param starting if true, parser is entering the section
* otherwise it is leaving the section
* @return always return true
*/
boolean manageODParametersSection(final boolean starting) {
commentsBlock.refuseFurtherComments();
anticipateNext(starting ? this::processODParamToken : structureProcessor);
return true;
}
/** Manage additional parameters section.
* @param starting if true, parser is entering the section
* otherwise it is leaving the section
* @return always return true
*/
boolean manageAdditionalParametersSection(final boolean starting) {
commentsBlock.refuseFurtherComments();
anticipateNext(starting ? this::processAdditionalParametersToken : structureProcessor);
return true;
}
/** Manage state vector section.
* @param starting if true, parser is entering the section
* otherwise it is leaving the section
* @return always return true
*/
boolean manageStateVectorSection(final boolean starting) {
commentsBlock.refuseFurtherComments();
anticipateNext(starting ? this::processStateVectorToken : structureProcessor);
return true;
}
/** Manage covariance matrix section.
* @param starting if true, parser is entering the section
* otherwise it is leaving the section
* @return always return true
*/
boolean manageCovMatrixSection(final boolean starting) {
commentsBlock.refuseFurtherComments();
anticipateNext(starting ? this::processCovMatrixToken : structureProcessor);
return true;
}
/** Process one metadata token.
* @param token token to process
* @return true if token was processed, false otherwise
*/
private boolean processMetadataToken(final ParseToken token) {
if (isDatafinished && getFileFormat() != FileFormat.XML) {
finalizeData();
isDatafinished = false;
}
if (metadata == null) {
// CDM KVN file lack a META_START keyword, hence we can't call prepareMetadata()
// automatically before the first metadata token arrives
prepareMetadata();
}
inMetadata();
// There can be a COMMENT key at the beginning of relative metadata, but as the relative
// metadata are processed in the same try and catch loop than metadata because Orekit is
// build to read metadata and then data (and not relative metadata), it would be problematic
// to make relative metadata extends comments container(because of the COMMENTS in the middle
// of relativemetadata and metadata section. Indeed, as said in {@link
// #CommentsContainer} COMMENT should only be at the beginning of sections but in this case
// there is a comment at the beginning corresponding to the relative metadata comment
// and 1 in the middle for object 1 metadata and one further for object 2 metadata. That
// is why this special syntax was used and initializes the relative metadata COMMENT once
// at the beginning as relative metadata is not a comment container
if (COMMENT.equals(token.getName()) && doRelativeMetadata ) {
if (token.getType() == TokenType.ENTRY) {
relativeMetadata.addComment(token.getContentAsNormalizedString());
return true;
}
}
doRelativeMetadata = false;
try {
return token.getName() != null &&
CdmRelativeMetadataKey.valueOf(token.getName()).process(token, context, relativeMetadata);
} catch (IllegalArgumentException iaeM) {
try {
return MetadataKey.valueOf(token.getName()).process(token, context, metadata);
} catch (IllegalArgumentException iaeD) {
try {
return CdmMetadataKey.valueOf(token.getName()).process(token, context, metadata);
} catch (IllegalArgumentException iaeC) {
// token has not been recognized
return false;
}
}
}
}
/** Process one XML data substructure token.
* @param token token to process
* @return true if token was processed, false otherwise
*/
private boolean processXmlSubStructureToken(final ParseToken token) {
// As no relativemetadata token exists in the structure processor and as RelativeMetadata keys are
// processed in the same try and catch loop in processMetadatatoken as CdmMetadata keys, if the relativemetadata
// token is read it should be as if the token was equal to metadata to start to initialize relative metadata
// and metadata and to go in the processMetadataToken try and catch loop. The following relativemetadata
// stop should be ignored to stay in the processMetadataToken try and catch loop and the following metadata
// start also ignored to stay in the processMetadataToken try and catch loop. Then arrives the end of metadata
// so we call structure processor with metadata stop. This distinction of cases is useful for relativemetadata
// block followed by metadata block for object 1 and also useful to only close metadata block for object 2.
// The metadata start for object 2 is processed by structureProcessor
if (METADATA.equals(token.getName()) && TokenType.START.equals(token.getType()) ||
RELATIVEMETADATA.equals(token.getName()) && TokenType.STOP.equals(token.getType())) {
anticipateNext(this::processMetadataToken);
return true;
} else if (RELATIVEMETADATA.equals(token.getName()) && TokenType.START.equals(token.getType()) ||
METADATA.equals(token.getName()) && TokenType.STOP.equals(token.getType())) {
final ParseToken replaceToken = new ParseToken(token.getType(), METADATA,
null, token.getUnits(), token.getLineNumber(), token.getFileName());
return structureProcessor.processToken(replaceToken);
} else {
// Relative metadata COMMENT and metadata COMMENT should not be read by XmlSubStructureKey that
// is why 2 cases are distinguished here : the COMMENT for relative metadata and the COMMENT
// for metadata.
if (commentsBlock == null && COMMENT.equals(token.getName())) {
// COMMENT adding for Relative Metadata in XML
if (doRelativeMetadata) {
if (token.getType() == TokenType.ENTRY) {
relativeMetadata.addComment(token.getContentAsNormalizedString());
doRelativeMetadata = false;
return true;
} else {
// if the token Type is still not ENTRY we return true as at the next step
// it will be ENTRY ad we will be able to store the comment (similar treatment
// as OD parameter or Additional parameter or State Vector ... COMMENT treatment.)
return true;
}
}
// COMMENT adding for Metadata in XML
if (!doRelativeMetadata) {
if (token.getType() == TokenType.ENTRY) {
metadata.addComment(token.getContentAsNormalizedString());
return true;
} else {
// same as above
return true;
}
}
}
// to treat XmlSubStructureKey keys ( OD parameters, relative Metadata ...)
try {
return token.getName() != null && !doRelativeMetadata &&
XmlSubStructureKey.valueOf(token.getName()).process(token, this);
} catch (IllegalArgumentException iae) {
// token has not been recognized
return false;
}
}
}
/** Process one comment token.
* @param token token to process
* @return true if token was processed, false otherwise
*/
private boolean processGeneralCommentToken(final ParseToken token) {
if (commentsBlock == null) {
// CDM KVN file lack a META_STOP keyword, hence we can't call finalizeMetadata()
// automatically before the first data token arrives
finalizeMetadata();
// CDM KVN file lack a DATA_START keyword, hence we can't call prepareData()
// automatically before the first data token arrives
prepareData();
}
anticipateNext(getFileFormat() == FileFormat.XML ? this::processXmlSubStructureToken : this::processODParamToken);
if (COMMENT.equals(token.getName()) && commentsBlock.acceptComments()) {
if (token.getType() == TokenType.ENTRY) {
commentsBlock.addComment(token.getContentAsNormalizedString());
}
// in order to be able to differentiate general data comments and next block comment (OD parameters if not empty)
// only 1 line comment is allowed for general data comment.
commentsBlock.refuseFurtherComments();
return true;
} else {
return false;
}
}
/** Process one od parameter data token.
* @param token token to process
* @return true if token was processed, false otherwise
*/
private boolean processODParamToken(final ParseToken token) {
if (odParameters == null) {
odParameters = new ODParameters();
}
anticipateNext(getFileFormat() == FileFormat.XML ? this::processXmlSubStructureToken : this::processAdditionalParametersToken);
try {
return token.getName() != null &&
ODParametersKey.valueOf(token.getName()).process(token, context, odParameters);
} catch (IllegalArgumentException iae) {
// token has not been recognized
return false;
}
}
/** Process one additional parameter data token.
* @param token token to process
* @return true if token was processed, false otherwise
*/
private boolean processAdditionalParametersToken(final ParseToken token) {
if (addParameters == null) {
addParameters = new AdditionalParameters();
}
if (moveCommentsIfEmpty(odParameters, addParameters)) {
// get rid of the empty logical block
odParameters = null;
}
anticipateNext(getFileFormat() == FileFormat.XML ? this::processXmlSubStructureToken : this::processStateVectorToken);
try {
return token.getName() != null &&
AdditionalParametersKey.valueOf(token.getName()).process(token, context, addParameters);
} catch (IllegalArgumentException iae) {
// token has not been recognized
return false;
}
}
/** Process one state vector data token.
* @param token token to process
* @return true if token was processed, false otherwise
*/
private boolean processStateVectorToken(final ParseToken token) {
if (moveCommentsIfEmpty(addParameters, stateVector)) {
// get rid of the empty logical block
addParameters = null;
}
anticipateNext(getFileFormat() == FileFormat.XML ? this::processXmlSubStructureToken : this::processCovMatrixToken);
try {
return token.getName() != null &&
StateVectorKey.valueOf(token.getName()).process(token, context, stateVector);
} catch (IllegalArgumentException iae) {
// token has not been recognized
return false;
}
}
/** Process covariance matrix data token.
* @param token token to process
* @return true if token was processed, false otherwise
*/
private boolean processCovMatrixToken(final ParseToken token) {
isDatafinished = true;
anticipateNext(getFileFormat() == FileFormat.XML ? this::processXmlSubStructureToken : this::processMetadataToken);
try {
return token.getName() != null &&
RTNCovarianceKey.valueOf(token.getName()).process(token, context, covMatrix);
} catch (IllegalArgumentException iae) {
// token has not been recognized
return false;
}
}
/** Move comments from one empty logical block to another logical block.
* @param origin origin block
* @param destination destination block
* @return true if origin block was empty
*/
private boolean moveCommentsIfEmpty(final CommentsContainer origin, final CommentsContainer destination) {
if (origin != null && origin.acceptComments()) {
// origin block is empty, move the existing comments
for (final String comment : origin.getComments()) {
destination.addComment(comment);
}
return true;
} else {
return false;
}
}
}
| Fixed JavaDoc warnings. | src/main/java/org/orekit/files/ccsds/ndm/cdm/CdmParser.java | Fixed JavaDoc warnings. | <ide><path>rc/main/java/org/orekit/files/ccsds/ndm/cdm/CdmParser.java
<ide> * way to use parsers is to either dedicate one parser for each message
<ide> * and drop it afterwards, or to use a single-thread loop.
<ide> * </p>
<del> * @param <T> type of the file
<del> * @param <P> type of the parser
<ide> * @author Melina Vanel
<ide> * @since 11.2
<ide> */ |
|
Java | apache-2.0 | 93fa61b2257d48ac4e579a03c127bf7b65dd1dbc | 0 | jomarko/drools,manstis/drools,lanceleverich/drools,sutaakar/drools,romartin/drools,sutaakar/drools,manstis/drools,winklerm/drools,reynoldsm88/drools,reynoldsm88/drools,jomarko/drools,romartin/drools,winklerm/drools,sutaakar/drools,jomarko/drools,reynoldsm88/drools,sotty/drools,droolsjbpm/drools,ngs-mtech/drools,droolsjbpm/drools,manstis/drools,lanceleverich/drools,romartin/drools,jomarko/drools,manstis/drools,reynoldsm88/drools,droolsjbpm/drools,ngs-mtech/drools,winklerm/drools,lanceleverich/drools,ngs-mtech/drools,lanceleverich/drools,romartin/drools,droolsjbpm/drools,sutaakar/drools,ngs-mtech/drools,sutaakar/drools,sotty/drools,sotty/drools,winklerm/drools,sotty/drools,manstis/drools,winklerm/drools,sotty/drools,romartin/drools,droolsjbpm/drools,lanceleverich/drools,jomarko/drools,reynoldsm88/drools,ngs-mtech/drools | /*
* Copyright 2015 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.drools.compiler.builder.impl;
import org.drools.compiler.compiler.AnnotationDeclarationError;
import org.drools.compiler.compiler.BPMN2ProcessFactory;
import org.drools.compiler.compiler.BaseKnowledgeBuilderResultImpl;
import org.drools.compiler.compiler.ConfigurableSeverityResult;
import org.drools.compiler.compiler.DecisionTableFactory;
import org.drools.compiler.compiler.DeprecatedResourceTypeWarning;
import org.drools.compiler.compiler.Dialect;
import org.drools.compiler.compiler.DialectCompiletimeRegistry;
import org.drools.compiler.compiler.DrlParser;
import org.drools.compiler.compiler.DroolsError;
import org.drools.compiler.compiler.DroolsErrorWrapper;
import org.drools.compiler.compiler.DroolsParserException;
import org.drools.compiler.compiler.DroolsWarning;
import org.drools.compiler.compiler.DroolsWarningWrapper;
import org.drools.compiler.compiler.DuplicateFunction;
import org.drools.compiler.compiler.DuplicateRule;
import org.drools.compiler.compiler.GlobalError;
import org.drools.compiler.compiler.GuidedDecisionTableFactory;
import org.drools.compiler.compiler.GuidedDecisionTableProvider;
import org.drools.compiler.compiler.GuidedRuleTemplateFactory;
import org.drools.compiler.compiler.GuidedRuleTemplateProvider;
import org.drools.compiler.compiler.GuidedScoreCardFactory;
import org.drools.compiler.compiler.PMMLCompiler;
import org.drools.compiler.compiler.PMMLCompilerFactory;
import org.drools.compiler.compiler.PackageBuilderErrors;
import org.drools.compiler.compiler.PackageBuilderResults;
import org.drools.compiler.compiler.PackageRegistry;
import org.drools.compiler.compiler.ParserError;
import org.drools.compiler.compiler.ProcessBuilder;
import org.drools.compiler.compiler.ProcessBuilderFactory;
import org.drools.compiler.compiler.ProcessLoadError;
import org.drools.compiler.compiler.ResourceConversionResult;
import org.drools.compiler.compiler.ResourceTypeDeclarationWarning;
import org.drools.compiler.compiler.RuleBuildError;
import org.drools.compiler.compiler.ScoreCardFactory;
import org.drools.compiler.compiler.TypeDeclarationError;
import org.drools.compiler.compiler.xml.XmlPackageReader;
import org.drools.compiler.lang.ExpanderException;
import org.drools.compiler.lang.descr.AbstractClassTypeDeclarationDescr;
import org.drools.compiler.lang.descr.AccumulateImportDescr;
import org.drools.compiler.lang.descr.AnnotatedBaseDescr;
import org.drools.compiler.lang.descr.AnnotationDescr;
import org.drools.compiler.lang.descr.AttributeDescr;
import org.drools.compiler.lang.descr.BaseDescr;
import org.drools.compiler.lang.descr.CompositePackageDescr;
import org.drools.compiler.lang.descr.ConditionalElementDescr;
import org.drools.compiler.lang.descr.EntryPointDeclarationDescr;
import org.drools.compiler.lang.descr.EnumDeclarationDescr;
import org.drools.compiler.lang.descr.FunctionDescr;
import org.drools.compiler.lang.descr.FunctionImportDescr;
import org.drools.compiler.lang.descr.GlobalDescr;
import org.drools.compiler.lang.descr.ImportDescr;
import org.drools.compiler.lang.descr.PackageDescr;
import org.drools.compiler.lang.descr.PatternDescr;
import org.drools.compiler.lang.descr.PatternDestinationDescr;
import org.drools.compiler.lang.descr.RuleDescr;
import org.drools.compiler.lang.descr.TypeDeclarationDescr;
import org.drools.compiler.lang.descr.TypeFieldDescr;
import org.drools.compiler.lang.descr.WindowDeclarationDescr;
import org.drools.compiler.lang.dsl.DSLMappingFile;
import org.drools.compiler.lang.dsl.DSLTokenizedMappingFile;
import org.drools.compiler.lang.dsl.DefaultExpander;
import org.drools.compiler.rule.builder.RuleBuildContext;
import org.drools.compiler.rule.builder.RuleBuilder;
import org.drools.compiler.rule.builder.RuleConditionBuilder;
import org.drools.compiler.rule.builder.dialect.DialectError;
import org.drools.compiler.runtime.pipeline.impl.DroolsJaxbHelperProviderImpl;
import org.drools.core.base.ClassFieldAccessorCache;
import org.drools.core.base.TypeResolver;
import org.drools.core.builder.conf.impl.JaxbConfigurationImpl;
import org.drools.core.common.ProjectClassLoader;
import org.drools.core.definitions.InternalKnowledgePackage;
import org.drools.core.definitions.impl.KnowledgePackageImpl;
import org.drools.core.definitions.rule.impl.RuleImpl;
import org.drools.core.impl.InternalKnowledgeBase;
import org.drools.core.io.impl.BaseResource;
import org.drools.core.io.impl.ClassPathResource;
import org.drools.core.io.impl.DescrResource;
import org.drools.core.io.impl.ReaderResource;
import org.drools.core.io.internal.InternalResource;
import org.drools.core.rule.Function;
import org.drools.core.rule.ImportDeclaration;
import org.drools.core.rule.JavaDialectRuntimeData;
import org.drools.core.rule.Pattern;
import org.drools.core.rule.TypeDeclaration;
import org.drools.core.rule.WindowDeclaration;
import org.drools.core.util.DroolsStreamUtils;
import org.drools.core.util.IoUtils;
import org.drools.core.util.StringUtils;
import org.drools.core.xml.XmlChangeSetReader;
import org.kie.api.KieBaseConfiguration;
import org.kie.api.definition.process.Process;
import org.kie.api.io.Resource;
import org.kie.api.io.ResourceConfiguration;
import org.kie.api.io.ResourceType;
import org.kie.api.runtime.rule.AccumulateFunction;
import org.kie.internal.ChangeSet;
import org.kie.internal.KnowledgeBase;
import org.kie.internal.KnowledgeBaseFactory;
import org.kie.internal.assembler.KieAssemblerService;
import org.kie.internal.assembler.KieAssemblers;
import org.kie.internal.builder.CompositeKnowledgeBuilder;
import org.kie.internal.builder.DecisionTableConfiguration;
import org.kie.internal.builder.KnowledgeBuilder;
import org.kie.internal.builder.KnowledgeBuilderError;
import org.kie.internal.builder.KnowledgeBuilderErrors;
import org.kie.internal.builder.KnowledgeBuilderResult;
import org.kie.internal.builder.KnowledgeBuilderResults;
import org.kie.internal.builder.ResourceChange;
import org.kie.internal.builder.ResultSeverity;
import org.kie.internal.builder.ScoreCardConfiguration;
import org.kie.internal.definition.KnowledgePackage;
import org.kie.internal.utils.ServiceRegistryImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.SAXException;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.StringReader;
import java.lang.reflect.Array;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Stack;
import java.util.UUID;
import static org.drools.core.impl.KnowledgeBaseImpl.registerFunctionClassAndInnerClasses;
import static org.drools.core.util.StringUtils.isEmpty;
import static org.drools.core.util.StringUtils.ucFirst;
public class KnowledgeBuilderImpl implements KnowledgeBuilder {
protected static final transient Logger logger = LoggerFactory.getLogger(KnowledgeBuilderImpl.class);
private final Map<String, PackageRegistry> pkgRegistryMap;
private List<KnowledgeBuilderResult> results;
private final KnowledgeBuilderConfigurationImpl configuration;
public static final RuleBuilder ruleBuilder = new RuleBuilder();
/**
* Optional RuleBase for incremental live building
*/
private InternalKnowledgeBase kBase;
/**
* default dialect
*/
private final String defaultDialect;
private ClassLoader rootClassLoader;
private final Map<String, Class<?>> globals = new HashMap<String, Class<?>>();
private Resource resource;
private List<DSLTokenizedMappingFile> dslFiles;
private final org.drools.compiler.compiler.ProcessBuilder processBuilder;
private IllegalArgumentException processBuilderCreationFailure;
private PMMLCompiler pmmlCompiler;
//This list of package level attributes is initialised with the PackageDescr's attributes added to the assembler.
//The package level attributes are inherited by individual rules not containing explicit overriding parameters.
//The map is keyed on the PackageDescr's namespace and contains a map of AttributeDescr's keyed on the
//AttributeDescr's name.
private final Map<String, Map<String, AttributeDescr>> packageAttributes = new HashMap<String, Map<String, AttributeDescr>>();
//PackageDescrs' list of ImportDescrs are kept identical as subsequent PackageDescrs are added.
private final Map<String, List<PackageDescr>> packages = new HashMap<String, List<PackageDescr>>();
private final Stack<List<Resource>> buildResources = new Stack<List<Resource>>();
private int currentRulePackage = 0;
private AssetFilter assetFilter = null;
private final TypeDeclarationBuilder typeBuilder;
/**
* Use this when package is starting from scratch.
*/
public KnowledgeBuilderImpl() {
this((InternalKnowledgeBase) null,
null);
}
/**
* This will allow you to merge rules into this pre existing package.
*/
public KnowledgeBuilderImpl(final InternalKnowledgePackage pkg) {
this(pkg,
null);
}
public KnowledgeBuilderImpl(final InternalKnowledgeBase kBase) {
this(kBase,
null);
}
/**
* Pass a specific configuration for the PackageBuilder
*
* PackageBuilderConfiguration is not thread safe and it also contains
* state. Once it is created and used in one or more PackageBuilders it
* should be considered immutable. Do not modify its properties while it is
* being used by a PackageBuilder.
*/
public KnowledgeBuilderImpl(final KnowledgeBuilderConfigurationImpl configuration) {
this((InternalKnowledgeBase) null,
configuration);
}
public KnowledgeBuilderImpl(InternalKnowledgePackage pkg,
KnowledgeBuilderConfigurationImpl configuration) {
if (configuration == null) {
this.configuration = new KnowledgeBuilderConfigurationImpl();
} else {
this.configuration = configuration;
}
this.rootClassLoader = this.configuration.getClassLoader();
this.defaultDialect = this.configuration.getDefaultDialect();
this.pkgRegistryMap = new LinkedHashMap<String, PackageRegistry>();
this.results = new ArrayList<KnowledgeBuilderResult>();
PackageRegistry pkgRegistry = new PackageRegistry(rootClassLoader, this.configuration, pkg);
pkgRegistry.setDialect(this.defaultDialect);
this.pkgRegistryMap.put(pkg.getName(),
pkgRegistry);
// add imports to pkg registry
for (final ImportDeclaration implDecl : pkg.getImports().values()) {
pkgRegistry.addImport(new ImportDescr(implDecl.getTarget()));
}
processBuilder = createProcessBuilder();
typeBuilder = new TypeDeclarationBuilder(this);
}
public KnowledgeBuilderImpl(InternalKnowledgeBase kBase,
KnowledgeBuilderConfigurationImpl configuration) {
if (configuration == null) {
this.configuration = new KnowledgeBuilderConfigurationImpl();
} else {
this.configuration = configuration;
}
if (kBase != null) {
this.rootClassLoader = kBase.getRootClassLoader();
} else {
this.rootClassLoader = this.configuration.getClassLoader();
}
// FIXME, we need to get drools to support "default" namespace.
//this.defaultNamespace = pkg.getName();
this.defaultDialect = this.configuration.getDefaultDialect();
this.pkgRegistryMap = new LinkedHashMap<String, PackageRegistry>();
this.results = new ArrayList<KnowledgeBuilderResult>();
this.kBase = kBase;
processBuilder = createProcessBuilder();
typeBuilder = new TypeDeclarationBuilder(this);
}
private ProcessBuilder createProcessBuilder() {
try {
return ProcessBuilderFactory.newProcessBuilder(this);
} catch (IllegalArgumentException e) {
processBuilderCreationFailure = e;
return null;
}
}
private PMMLCompiler getPMMLCompiler() {
if (this.pmmlCompiler == null) {
this.pmmlCompiler = PMMLCompilerFactory.getPMMLCompiler();
}
return this.pmmlCompiler;
}
Resource getCurrentResource() {
return resource;
}
public InternalKnowledgeBase getKnowledgeBase() {
return kBase;
}
TypeDeclarationBuilder getTypeBuilder() {
return typeBuilder;
}
/**
* Load a rule package from DRL source.
*
* @throws DroolsParserException
* @throws java.io.IOException
*/
public void addPackageFromDrl(final Reader reader) throws DroolsParserException,
IOException {
addPackageFromDrl(reader, new ReaderResource(reader, ResourceType.DRL));
}
/**
* Load a rule package from DRL source and associate all loaded artifacts
* with the given resource.
*
* @param reader
* @param sourceResource the source resource for the read artifacts
* @throws DroolsParserException
* @throws IOException
*/
public void addPackageFromDrl(final Reader reader,
final Resource sourceResource) throws DroolsParserException,
IOException {
this.resource = sourceResource;
final DrlParser parser = new DrlParser(configuration.getLanguageLevel());
final PackageDescr pkg = parser.parse(sourceResource, reader);
this.results.addAll(parser.getErrors());
if (pkg == null) {
addBuilderResult(new ParserError(sourceResource, "Parser returned a null Package", 0, 0));
}
if (!parser.hasErrors()) {
addPackage(pkg);
}
this.resource = null;
}
public void addPackageFromDecisionTable(Resource resource,
ResourceConfiguration configuration) throws DroolsParserException,
IOException {
this.resource = resource;
addPackage( decisionTableToPackageDescr( resource, configuration ) );
this.resource = null;
}
PackageDescr decisionTableToPackageDescr(Resource resource,
ResourceConfiguration configuration) throws DroolsParserException,
IOException {
DecisionTableConfiguration dtableConfiguration = configuration instanceof DecisionTableConfiguration ?
(DecisionTableConfiguration) configuration :
null;
if ( dtableConfiguration != null && !dtableConfiguration.getRuleTemplateConfigurations().isEmpty() ) {
List<String> generatedDrls = DecisionTableFactory.loadFromInputStreamWithTemplates( resource, dtableConfiguration );
if ( generatedDrls.size() == 1 ) {
return generatedDrlToPackageDescr( resource, generatedDrls.get(0) );
}
CompositePackageDescr compositePackageDescr = null;
for ( String generatedDrl : generatedDrls ) {
PackageDescr packageDescr = generatedDrlToPackageDescr( resource, generatedDrl );
if ( packageDescr != null ) {
if ( compositePackageDescr == null ) {
compositePackageDescr = new CompositePackageDescr( resource, packageDescr );
} else {
compositePackageDescr.addPackageDescr( resource, packageDescr );
}
}
}
return compositePackageDescr;
}
String generatedDrl = DecisionTableFactory.loadFromResource(resource, dtableConfiguration);
return generatedDrlToPackageDescr( resource, generatedDrl );
}
public void addPackageFromGuidedDecisionTable(Resource resource) throws DroolsParserException,
IOException {
this.resource = resource;
addPackage( guidedDecisionTableToPackageDescr( resource ) );
this.resource = null;
}
PackageDescr guidedDecisionTableToPackageDescr(Resource resource) throws DroolsParserException,
IOException {
GuidedDecisionTableProvider guidedDecisionTableProvider = GuidedDecisionTableFactory.getGuidedDecisionTableProvider();
ResourceConversionResult conversionResult = guidedDecisionTableProvider.loadFromInputStream(resource.getInputStream());
return conversionResultToPackageDescr(resource, conversionResult);
}
private PackageDescr generatedDrlToPackageDescr( Resource resource, String generatedDrl ) throws DroolsParserException {
// dump the generated DRL if the dump dir was configured
if (this.configuration.getDumpDir() != null) {
dumpDrlGeneratedFromDTable(this.configuration.getDumpDir(), generatedDrl, resource.getSourcePath());
}
DrlParser parser = new DrlParser(configuration.getLanguageLevel());
PackageDescr pkg = parser.parse(resource, new StringReader(generatedDrl));
this.results.addAll(parser.getErrors());
if (pkg == null) {
addBuilderResult(new ParserError(resource, "Parser returned a null Package", 0, 0));
} else {
pkg.setResource(resource);
}
return parser.hasErrors() ? null : pkg;
}
PackageDescr generatedDslrToPackageDescr(Resource resource, String dslr) throws DroolsParserException {
return dslrReaderToPackageDescr(resource, new StringReader(dslr));
}
private void dumpDrlGeneratedFromDTable(File dumpDir, String generatedDrl, String srcPath) {
File dumpFile;
if (srcPath != null) {
dumpFile = createDumpDrlFile(dumpDir, srcPath, ".drl");
} else {
dumpFile = createDumpDrlFile(dumpDir, "decision-table-" + UUID.randomUUID(), ".drl");
}
try {
IoUtils.write(dumpFile, generatedDrl.getBytes(IoUtils.UTF8_CHARSET));
} catch (IOException ex) {
// nothing serious, just failure when writing the generated DRL to file, just log the exception and continue
logger.warn("Can't write the DRL generated from decision table to file " + dumpFile.getAbsolutePath() + "!\n" +
Arrays.toString(ex.getStackTrace()));
}
}
protected static File createDumpDrlFile(File dumpDir, String fileName, String extension) {
return new File(dumpDir, fileName.replaceAll("[^a-zA-Z0-9\\.\\-_]+", "_") + extension);
}
public void addPackageFromScoreCard(Resource resource,
ResourceConfiguration configuration) throws DroolsParserException,
IOException {
this.resource = resource;
addPackage( scoreCardToPackageDescr( resource, configuration ) );
this.resource = null;
}
PackageDescr scoreCardToPackageDescr(Resource resource,
ResourceConfiguration configuration) throws DroolsParserException,
IOException {
ScoreCardConfiguration scardConfiguration = configuration instanceof ScoreCardConfiguration ?
(ScoreCardConfiguration) configuration :
null;
String string = ScoreCardFactory.loadFromInputStream(resource.getInputStream(), scardConfiguration);
return generatedDrlToPackageDescr( resource, string );
}
public void addPackageFromGuidedScoreCard(Resource resource) throws DroolsParserException,
IOException {
this.resource = resource;
addPackage( guidedScoreCardToPackageDescr(resource) );
this.resource = null;
}
PackageDescr guidedScoreCardToPackageDescr(Resource resource) throws DroolsParserException,
IOException {
String drl = GuidedScoreCardFactory.loadFromInputStream(resource.getInputStream());
return generatedDrlToPackageDescr(resource, drl);
}
public void addPackageFromTemplate(Resource resource) throws DroolsParserException,
IOException {
this.resource = resource;
addPackage(templateToPackageDescr(resource));
this.resource = null;
}
PackageDescr templateToPackageDescr(Resource resource) throws DroolsParserException,
IOException {
GuidedRuleTemplateProvider guidedRuleTemplateProvider = GuidedRuleTemplateFactory.getGuidedRuleTemplateProvider();
ResourceConversionResult conversionResult = guidedRuleTemplateProvider.loadFromInputStream(resource.getInputStream());
return conversionResultToPackageDescr(resource, conversionResult);
}
private PackageDescr conversionResultToPackageDescr(Resource resource, ResourceConversionResult resourceConversionResult)
throws DroolsParserException {
ResourceType resourceType = resourceConversionResult.getType();
if (ResourceType.DSLR.equals(resourceType)) {
return generatedDslrToPackageDescr(resource, resourceConversionResult.getContent());
} else if (ResourceType.DRL.equals(resourceType)) {
return generatedDrlToPackageDescr(resource, resourceConversionResult.getContent());
} else {
throw new RuntimeException("Converting generated " + resourceType + " into PackageDescr is not supported!");
}
}
public void addPackageFromDrl(Resource resource) throws DroolsParserException,
IOException {
this.resource = resource;
addPackage(drlToPackageDescr(resource));
this.resource = null;
}
PackageDescr drlToPackageDescr(Resource resource) throws DroolsParserException,
IOException {
PackageDescr pkg;
boolean hasErrors = false;
if (resource instanceof DescrResource) {
pkg = (PackageDescr) ((DescrResource) resource).getDescr();
} else {
final DrlParser parser = new DrlParser(configuration.getLanguageLevel());
pkg = parser.parse(resource);
this.results.addAll(parser.getErrors());
if (pkg == null) {
addBuilderResult(new ParserError(resource, "Parser returned a null Package", 0, 0));
}
hasErrors = parser.hasErrors();
}
if (pkg != null) {
pkg.setResource(resource);
}
return hasErrors ? null : pkg;
}
/**
* Load a rule package from XML source.
*
* @param reader
* @throws DroolsParserException
* @throws IOException
*/
public void addPackageFromXml(final Reader reader) throws DroolsParserException,
IOException {
this.resource = new ReaderResource(reader, ResourceType.XDRL);
final XmlPackageReader xmlReader = new XmlPackageReader(this.configuration.getSemanticModules());
xmlReader.getParser().setClassLoader(this.rootClassLoader);
try {
xmlReader.read(reader);
} catch (final SAXException e) {
throw new DroolsParserException(e.toString(),
e.getCause());
}
addPackage(xmlReader.getPackageDescr());
this.resource = null;
}
public void addPackageFromXml(final Resource resource) throws DroolsParserException,
IOException {
this.resource = resource;
addPackage(xmlToPackageDescr(resource));
this.resource = null;
}
PackageDescr xmlToPackageDescr(Resource resource) throws DroolsParserException,
IOException {
final XmlPackageReader xmlReader = new XmlPackageReader(this.configuration.getSemanticModules());
xmlReader.getParser().setClassLoader( this.rootClassLoader );
Reader reader = null;
try {
reader = resource.getReader();
xmlReader.read(reader);
} catch (final SAXException e) {
throw new DroolsParserException(e.toString(),
e.getCause());
} finally {
if (reader != null) {
reader.close();
}
}
return xmlReader.getPackageDescr();
}
/**
* Load a rule package from DRL source using the supplied DSL configuration.
*
* @param source
* The source of the rules.
* @param dsl
* The source of the domain specific language configuration.
* @throws DroolsParserException
* @throws IOException
*/
public void addPackageFromDrl(final Reader source,
final Reader dsl) throws DroolsParserException,
IOException {
this.resource = new ReaderResource(source, ResourceType.DSLR);
final DrlParser parser = new DrlParser(configuration.getLanguageLevel());
final PackageDescr pkg = parser.parse(source, dsl);
this.results.addAll( parser.getErrors() );
if (!parser.hasErrors()) {
addPackage(pkg);
}
this.resource = null;
}
public void addPackageFromDslr(final Resource resource) throws DroolsParserException,
IOException {
this.resource = resource;
addPackage(dslrToPackageDescr(resource));
this.resource = null;
}
PackageDescr dslrToPackageDescr(Resource resource) throws DroolsParserException,
IOException {
return dslrReaderToPackageDescr(resource, resource.getReader());
}
private PackageDescr dslrReaderToPackageDescr(Resource resource, Reader dslrReader) throws DroolsParserException {
boolean hasErrors;
PackageDescr pkg;
DrlParser parser = new DrlParser(configuration.getLanguageLevel());
DefaultExpander expander = getDslExpander();
try {
if (expander == null) {
expander = new DefaultExpander();
}
String str = expander.expand(dslrReader);
if (expander.hasErrors()) {
for (ExpanderException error : expander.getErrors()) {
error.setResource(resource);
addBuilderResult(error);
}
}
pkg = parser.parse(resource, str);
this.results.addAll(parser.getErrors());
hasErrors = parser.hasErrors();
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if (dslrReader != null) {
try {
dslrReader.close();
} catch (IOException e) {
}
}
}
return hasErrors ? null : pkg;
}
public void addDsl(Resource resource) throws IOException {
this.resource = resource;
DSLTokenizedMappingFile file = new DSLTokenizedMappingFile();
Reader reader = null;
try {
reader = resource.getReader();
if (!file.parseAndLoad(reader)) {
this.results.addAll(file.getErrors());
}
if (this.dslFiles == null) {
this.dslFiles = new ArrayList<DSLTokenizedMappingFile>();
}
this.dslFiles.add(file);
} finally {
if (reader != null) {
reader.close();
}
this.resource = null;
}
}
/**
* Add a ruleflow (.rfm) asset to this package.
*/
public void addRuleFlow(Reader processSource) {
addProcessFromXml(processSource);
}
public void addProcessFromXml(Resource resource) {
if (processBuilder == null) {
throw new RuntimeException("Unable to instantiate a process assembler", processBuilderCreationFailure);
}
if (ResourceType.DRF.equals(resource.getResourceType())) {
addBuilderResult(new DeprecatedResourceTypeWarning(resource, "RF"));
}
this.resource = resource;
try {
List<Process> processes = processBuilder.addProcessFromXml(resource);
List<BaseKnowledgeBuilderResultImpl> errors = processBuilder.getErrors();
if ( errors.isEmpty() ) {
if ( this.kBase != null && processes != null ) {
for (Process process : processes) {
if ( filterAccepts( ResourceChange.Type.PROCESS, process.getNamespace(), process.getId() ) ) {
this.kBase.addProcess(process);
}
}
}
} else {
this.results.addAll(errors);
errors.clear();
}
} catch (Exception e) {
if (e instanceof RuntimeException) {
throw (RuntimeException) e;
}
addBuilderResult(new ProcessLoadError(resource, "Unable to load process.", e));
}
this.results = getResults(this.results);
this.resource = null;
}
public void addProcessFromXml(Reader processSource) {
addProcessFromXml(new ReaderResource(processSource, ResourceType.DRF));
}
public void addKnowledgeResource(Resource resource,
ResourceType type,
ResourceConfiguration configuration) {
try {
((InternalResource) resource).setResourceType(type);
if (ResourceType.DRL.equals(type)) {
addPackageFromDrl(resource);
} else if (ResourceType.GDRL.equals(type)) {
addPackageFromDrl(resource);
} else if (ResourceType.RDRL.equals(type)) {
addPackageFromDrl(resource);
} else if (ResourceType.DESCR.equals(type)) {
addPackageFromDrl(resource);
} else if (ResourceType.DSLR.equals(type)) {
addPackageFromDslr(resource);
} else if (ResourceType.RDSLR.equals(type)) {
addPackageFromDslr(resource);
} else if (ResourceType.DSL.equals(type)) {
addDsl(resource);
} else if (ResourceType.XDRL.equals(type)) {
addPackageFromXml(resource);
} else if (ResourceType.DRF.equals(type)) {
addProcessFromXml(resource);
} else if (ResourceType.BPMN2.equals(type)) {
BPMN2ProcessFactory.configurePackageBuilder(this);
addProcessFromXml(resource);
} else if (ResourceType.DTABLE.equals(type)) {
addPackageFromDecisionTable(resource, configuration);
} else if (ResourceType.PKG.equals(type)) {
addPackageFromInputStream(resource);
} else if (ResourceType.CHANGE_SET.equals(type)) {
addPackageFromChangeSet(resource);
} else if (ResourceType.XSD.equals(type)) {
addPackageFromXSD(resource, (JaxbConfigurationImpl) configuration);
} else if (ResourceType.PMML.equals(type)) {
addPackageFromPMML(resource, type, configuration);
} else if (ResourceType.SCARD.equals(type)) {
addPackageFromScoreCard(resource, configuration);
} else if (ResourceType.TDRL.equals(type)) {
addPackageFromDrl(resource);
} else if (ResourceType.TEMPLATE.equals(type)) {
addPackageFromTemplate(resource);
} else if (ResourceType.GDST.equals(type)) {
addPackageFromGuidedDecisionTable(resource);
} else if (ResourceType.SCGD.equals(type)) {
addPackageFromGuidedScoreCard(resource);
} else {
addPackageForExternalType(resource, type, configuration);
}
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
void addPackageForExternalType(Resource resource,
ResourceType type,
ResourceConfiguration configuration) throws Exception {
KieAssemblers assemblers = ServiceRegistryImpl.getInstance().get(KieAssemblers.class);
KieAssemblerService assembler = assemblers.getAssemblers().get( type );
if (assembler != null) {
assembler.addResource( this,
resource,
type,
configuration );
} else {
throw new RuntimeException("Unknown resource type: " + type);
}
}
public void addPackageFromPMML(Resource resource,
ResourceType type,
ResourceConfiguration configuration) throws Exception {
PMMLCompiler compiler = getPMMLCompiler();
if (compiler != null) {
if (compiler.getResults().isEmpty()) {
this.resource = resource;
PackageDescr descr = pmmlModelToPackageDescr(compiler, resource);
if (descr != null) {
addPackage(descr);
}
this.resource = null;
} else {
this.results.addAll(compiler.getResults());
}
compiler.clearResults();
} else {
addPackageForExternalType(resource, type, configuration);
}
}
PackageDescr pmmlModelToPackageDescr(PMMLCompiler compiler,
Resource resource) throws DroolsParserException,
IOException {
String theory = compiler.compile(resource.getInputStream(),
rootClassLoader);
if (!compiler.getResults().isEmpty()) {
this.results.addAll(compiler.getResults());
return null;
}
return generatedDrlToPackageDescr( resource, theory );
}
void addPackageFromXSD(Resource resource,
JaxbConfigurationImpl configuration) throws IOException {
if (configuration != null) {
String[] classes = DroolsJaxbHelperProviderImpl.addXsdModel(resource,
this,
configuration.getXjcOpts(),
configuration.getSystemId());
for (String cls : classes) {
configuration.getClasses().add(cls);
}
}
}
void addPackageFromChangeSet(Resource resource) throws SAXException,
IOException {
XmlChangeSetReader reader = new XmlChangeSetReader(this.configuration.getSemanticModules());
if (resource instanceof ClassPathResource) {
reader.setClassLoader(((ClassPathResource) resource).getClassLoader(),
((ClassPathResource) resource).getClazz());
} else {
reader.setClassLoader(this.configuration.getClassLoader(),
null);
}
Reader resourceReader = null;
try {
resourceReader = resource.getReader();
ChangeSet changeSet = reader.read(resourceReader);
if (changeSet == null) {
// @TODO should log an error
}
for (Resource nestedResource : changeSet.getResourcesAdded()) {
InternalResource iNestedResourceResource = (InternalResource) nestedResource;
if (iNestedResourceResource.isDirectory()) {
for (Resource childResource : iNestedResourceResource.listResources()) {
if (((InternalResource) childResource).isDirectory()) {
continue; // ignore sub directories
}
((InternalResource) childResource).setResourceType(iNestedResourceResource.getResourceType());
addKnowledgeResource(childResource,
iNestedResourceResource.getResourceType(),
iNestedResourceResource.getConfiguration());
}
} else {
addKnowledgeResource(iNestedResourceResource,
iNestedResourceResource.getResourceType(),
iNestedResourceResource.getConfiguration());
}
}
} finally {
if (resourceReader != null) {
resourceReader.close();
}
}
}
void addPackageFromInputStream(final Resource resource) throws IOException,
ClassNotFoundException {
InputStream is = resource.getInputStream();
Object object = DroolsStreamUtils.streamIn(is, this.configuration.getClassLoader());
is.close();
if (object instanceof Collection) {
// KnowledgeBuilder API
@SuppressWarnings("unchecked")
Collection<KnowledgePackage> pkgs = (Collection<KnowledgePackage>) object;
for (KnowledgePackage kpkg : pkgs) {
overrideReSource((KnowledgePackageImpl) kpkg, resource);
addPackage((KnowledgePackageImpl) kpkg);
}
} else if (object instanceof KnowledgePackageImpl) {
// KnowledgeBuilder API
KnowledgePackageImpl kpkg = (KnowledgePackageImpl) object;
overrideReSource(kpkg, resource);
addPackage(kpkg);
} else {
results.add(new DroolsError(resource) {
@Override
public String getMessage() {
return "Unknown binary format trying to load resource " + resource.toString();
}
@Override
public int[] getLines() {
return new int[0];
}
});
}
}
private void overrideReSource(InternalKnowledgePackage pkg,
Resource res) {
for (org.kie.api.definition.rule.Rule r : pkg.getRules()) {
if (isSwappable(((RuleImpl)r).getResource(), res)) {
((RuleImpl)r).setResource(res);
}
}
for (TypeDeclaration d : pkg.getTypeDeclarations().values()) {
if (isSwappable(d.getResource(), res)) {
d.setResource(res);
}
}
for (Function f : pkg.getFunctions().values()) {
if (isSwappable(f.getResource(), res)) {
f.setResource(res);
}
}
for (org.kie.api.definition.process.Process p : pkg.getRuleFlows().values()) {
if (isSwappable(p.getResource(), res)) {
p.setResource(res);
}
}
}
private boolean isSwappable(Resource original,
Resource source) {
return original == null
|| (original instanceof ReaderResource && ((ReaderResource) original).getReader() == null);
}
/**
* This adds a package from a Descr/AST This will also trigger a compile, if
* there are any generated classes to compile of course.
*/
public void addPackage(final PackageDescr packageDescr) {
PackageRegistry pkgRegistry = initPackageRegistry(packageDescr);
if (pkgRegistry == null) {
return;
}
currentRulePackage = pkgRegistryMap.size() - 1;
// merge into existing package
mergePackage(pkgRegistry, packageDescr);
compileAllRules(packageDescr, pkgRegistry);
}
void compileAllRules(PackageDescr packageDescr, PackageRegistry pkgRegistry) {
pkgRegistry.setDialect( getPackageDialect( packageDescr ) );
validateUniqueRuleNames( packageDescr );
compileRules(packageDescr, pkgRegistry);
compileAll();
try {
reloadAll();
} catch (Exception e) {
addBuilderResult(new DialectError(null, "Unable to wire compiled classes, probably related to compilation failures:" + e.getMessage()));
}
updateResults();
// iterate and compile
if (!hasErrors() && this.kBase != null) {
for (RuleDescr ruleDescr : packageDescr.getRules()) {
if( filterAccepts( ResourceChange.Type.RULE, ruleDescr.getNamespace(), ruleDescr.getName() ) ) {
pkgRegistry = this.pkgRegistryMap.get(ruleDescr.getNamespace());
this.kBase.addRule(pkgRegistry.getPackage(), pkgRegistry.getPackage().getRule(ruleDescr.getName()));
}
}
}
}
public void addBuilderResult(KnowledgeBuilderResult result) {
this.results.add(result);
}
PackageRegistry createPackageRegistry(PackageDescr packageDescr) {
PackageRegistry pkgRegistry = initPackageRegistry( packageDescr );
if (pkgRegistry == null) {
return null;
}
for (ImportDescr importDescr : packageDescr.getImports()) {
pkgRegistry.registerImport( importDescr.getTarget() );
}
return pkgRegistry;
}
private PackageRegistry initPackageRegistry(PackageDescr packageDescr) {
if (packageDescr == null) {
return null;
}
//Derive namespace
if (isEmpty(packageDescr.getNamespace())) {
packageDescr.setNamespace(this.configuration.getDefaultPackageName());
}
if (!checkNamespace(packageDescr.getNamespace())) {
return null;
}
initPackage(packageDescr);
PackageRegistry pkgRegistry = this.pkgRegistryMap.get( packageDescr.getNamespace() );
if (pkgRegistry == null) {
// initialise the package and namespace if it hasn't been used before
pkgRegistry = newPackage(packageDescr);
}
return pkgRegistry;
}
private void compileRules(PackageDescr packageDescr, PackageRegistry pkgRegistry) {
List<FunctionDescr> functions = packageDescr.getFunctions();
if (!functions.isEmpty()) {
for (FunctionDescr functionDescr : functions) {
if (isEmpty(functionDescr.getNamespace())) {
// make sure namespace is set on components
functionDescr.setNamespace(packageDescr.getNamespace());
}
// make sure functions are compiled using java dialect
functionDescr.setDialect("java");
preCompileAddFunction(functionDescr);
}
// iterate and compile
for (FunctionDescr functionDescr : functions) {
if (filterAccepts(ResourceChange.Type.FUNCTION, functionDescr.getNamespace(), functionDescr.getName()) ) {
// inherit the dialect from the package
addFunction(functionDescr);
}
}
// We need to compile all the functions now, so scripting
// languages like mvel can find them
compileAll();
for (FunctionDescr functionDescr : functions) {
if (filterAccepts(ResourceChange.Type.FUNCTION, functionDescr.getNamespace(), functionDescr.getName()) ) {
postCompileAddFunction(functionDescr);
}
}
}
// ensure that rules are ordered by dependency, so that dependent rules are built later
sortRulesByDependency(packageDescr);
// iterate and prepare RuleDescr
for (RuleDescr ruleDescr : packageDescr.getRules()) {
if (isEmpty(ruleDescr.getNamespace())) {
// make sure namespace is set on components
ruleDescr.setNamespace(packageDescr.getNamespace());
}
Map<String, AttributeDescr> pkgAttributes = packageAttributes.get(packageDescr.getNamespace());
inheritPackageAttributes(pkgAttributes,
ruleDescr);
if (isEmpty(ruleDescr.getDialect())) {
ruleDescr.addAttribute(new AttributeDescr("dialect",
pkgRegistry.getDialect()));
}
}
// Build up map of contexts and process all rules
Map<String, RuleBuildContext> ruleCxts = preProcessRules(packageDescr, pkgRegistry);
// iterate and compile
for (RuleDescr ruleDescr : packageDescr.getRules()) {
if (filterAccepts(ResourceChange.Type.RULE, ruleDescr.getNamespace(), ruleDescr.getName()) ) {
addRule(ruleCxts.get(ruleDescr.getName()));
}
}
}
boolean filterAccepts( ResourceChange.Type type, String namespace, String name ) {
return assetFilter == null || ! AssetFilter.Action.DO_NOTHING.equals( assetFilter.accept( type, namespace, name ) );
}
private boolean filterAcceptsRemoval( ResourceChange.Type type, String namespace, String name ) {
return assetFilter != null && AssetFilter.Action.REMOVE.equals( assetFilter.accept( type, namespace, name ) );
}
private Map<String, RuleBuildContext> preProcessRules(PackageDescr packageDescr, PackageRegistry pkgRegistry) {
Map<String, RuleBuildContext> ruleCxts = buildRuleBuilderContext(packageDescr.getRules());
InternalKnowledgePackage pkg = pkgRegistry.getPackage();
if (this.kBase != null) {
boolean needsRemoval = false;
// first, check if any rules no longer exist
for( org.kie.api.definition.rule.Rule rule : pkg.getRules() ) {
if (filterAcceptsRemoval( ResourceChange.Type.RULE, rule.getPackageName(), rule.getName() ) ) {
needsRemoval = true;
break;
}
}
if( !needsRemoval ) {
for (RuleDescr ruleDescr : packageDescr.getRules()) {
if (filterAccepts(ResourceChange.Type.RULE, ruleDescr.getNamespace(), ruleDescr.getName()) ) {
if (pkg.getRule(ruleDescr.getName()) != null) {
needsRemoval = true;
break;
}
}
}
}
if (needsRemoval) {
try {
this.kBase.lock();
for( org.kie.api.definition.rule.Rule rule : pkg.getRules() ) {
if (filterAcceptsRemoval( ResourceChange.Type.RULE, rule.getPackageName(), rule.getName() ) ) {
this.kBase.removeRule(pkg, pkg.getRule(rule.getName()));
pkg.removeRule(((RuleImpl)rule));
}
}
List<RuleImpl> rulesToBeRemoved = new ArrayList<RuleImpl>();
for (RuleDescr ruleDescr : packageDescr.getRules()) {
if (filterAccepts(ResourceChange.Type.RULE, ruleDescr.getNamespace(), ruleDescr.getName()) ) {
RuleImpl rule = (RuleImpl)pkg.getRule(ruleDescr.getName());
if (rule != null) {
rulesToBeRemoved.add(rule);
}
}
}
if (!rulesToBeRemoved.isEmpty()) {
kBase.removeRules( pkg, rulesToBeRemoved );
}
} finally {
this.kBase.unlock();
}
}
}
// Pre Process each rule, needed for Query signuture registration
for (RuleDescr ruleDescr : packageDescr.getRules()) {
if (filterAccepts(ResourceChange.Type.RULE, ruleDescr.getNamespace(), ruleDescr.getName()) ) {
RuleBuildContext ruleBuildContext = ruleCxts.get(ruleDescr.getName());
ruleBuilder.preProcess(ruleBuildContext);
pkg.addRule(ruleBuildContext.getRule());
}
}
return ruleCxts;
}
private void sortRulesByDependency(PackageDescr packageDescr) {
// Using a topological sorting algorithm
// see http://en.wikipedia.org/wiki/Topological_sorting
PackageRegistry pkgRegistry = this.pkgRegistryMap.get( packageDescr.getNamespace() );
InternalKnowledgePackage pkg = pkgRegistry.getPackage();
List<RuleDescr> roots = new LinkedList<RuleDescr>();
Map<String, List<RuleDescr>> children = new HashMap<String, List<RuleDescr>>();
LinkedHashMap<String, RuleDescr> sorted = new LinkedHashMap<String, RuleDescr>();
List<RuleDescr> queries = new ArrayList<RuleDescr>();
Set<String> compiledRules = new HashSet<String>();
for (RuleDescr ruleDescr : packageDescr.getRules()) {
if (ruleDescr.isQuery()) {
queries.add(ruleDescr);
} else if (!ruleDescr.hasParent()) {
roots.add(ruleDescr);
} else {
if (pkg.getRule(ruleDescr.getParentName()) != null) {
// The parent of this rule has been already compiled
compiledRules.add(ruleDescr.getParentName());
}
List<RuleDescr> childz = children.get(ruleDescr.getParentName());
if (childz == null) {
childz = new ArrayList<RuleDescr>();
children.put(ruleDescr.getParentName(), childz);
}
childz.add(ruleDescr);
}
}
if (children.isEmpty()) { // Sorting not necessary
if (!queries.isEmpty()) { // Build all queries first
packageDescr.getRules().removeAll(queries);
packageDescr.getRules().addAll(0, queries);
}
return;
}
for (String compiledRule : compiledRules) {
List<RuleDescr> childz = children.remove( compiledRule );
roots.addAll( childz );
}
while (!roots.isEmpty()) {
RuleDescr root = roots.remove(0);
sorted.put(root.getName(), root);
List<RuleDescr> childz = children.remove(root.getName());
if (childz != null) {
roots.addAll(childz);
}
}
reportHierarchyErrors(children, sorted);
packageDescr.getRules().clear();
packageDescr.getRules().addAll(queries);
for (RuleDescr descr : sorted.values() ) {
packageDescr.getRules().add( descr );
}
}
private void reportHierarchyErrors(Map<String, List<RuleDescr>> parents,
Map<String, RuleDescr> sorted) {
boolean circularDep = false;
for (List<RuleDescr> rds : parents.values()) {
for (RuleDescr ruleDescr : rds) {
if (parents.get(ruleDescr.getParentName()) != null
&& (sorted.containsKey(ruleDescr.getName()) || parents.containsKey(ruleDescr.getName()))) {
circularDep = true;
results.add( new RuleBuildError( new RuleImpl( ruleDescr.getName() ), ruleDescr, null,
"Circular dependency in rules hierarchy" ) );
break;
}
manageUnresolvedExtension( ruleDescr, sorted.values() );
}
if (circularDep) {
break;
}
}
}
private void manageUnresolvedExtension(RuleDescr ruleDescr,
Collection<RuleDescr> candidates) {
List<String> candidateRules = new LinkedList<String>();
for (RuleDescr r : candidates) {
if (StringUtils.stringSimilarity(ruleDescr.getParentName(), r.getName(), StringUtils.SIMILARITY_STRATS.DICE) >= 0.75) {
candidateRules.add(r.getName());
}
}
String msg = "Unresolved parent name " + ruleDescr.getParentName();
if (candidateRules.size() > 0) {
msg += " >> did you mean any of :" + candidateRules;
}
results.add(new RuleBuildError(new RuleImpl(ruleDescr.getName()), ruleDescr, msg,
"Unable to resolve parent rule, please check that both rules are in the same package"));
}
private void initPackage(PackageDescr packageDescr) {
//Gather all imports for all PackageDescrs for the current package and replicate into
//all PackageDescrs for the current package, thus maintaining a complete list of
//ImportDescrs for all PackageDescrs for the current package.
List<PackageDescr> packageDescrsForPackage = packages.get(packageDescr.getName());
if (packageDescrsForPackage == null) {
packageDescrsForPackage = new ArrayList<PackageDescr>();
packages.put(packageDescr.getName(),
packageDescrsForPackage);
}
packageDescrsForPackage.add(packageDescr);
Set<ImportDescr> imports = new HashSet<ImportDescr>();
for (PackageDescr pd : packageDescrsForPackage) {
imports.addAll(pd.getImports());
}
for (PackageDescr pd : packageDescrsForPackage) {
pd.getImports().clear();
pd.addAllImports(imports);
}
//Copy package level attributes for inclusion on individual rules
if (!packageDescr.getAttributes().isEmpty()) {
Map<String, AttributeDescr> pkgAttributes = packageAttributes.get(packageDescr.getNamespace());
if (pkgAttributes == null) {
pkgAttributes = new HashMap<String, AttributeDescr>();
this.packageAttributes.put(packageDescr.getNamespace(),
pkgAttributes);
}
for (AttributeDescr attr : packageDescr.getAttributes()) {
pkgAttributes.put(attr.getName(),
attr);
}
}
}
private String getPackageDialect(PackageDescr packageDescr) {
String dialectName = this.defaultDialect;
// see if this packageDescr overrides the current default dialect
for (AttributeDescr value : packageDescr.getAttributes()) {
if ("dialect".equals(value.getName())) {
dialectName = value.getValue();
break;
}
}
return dialectName;
}
// test
/**
* This checks to see if it should all be in the one namespace.
*/
private boolean checkNamespace(String newName) {
return configuration == null ||
!((!pkgRegistryMap.isEmpty()) && (!pkgRegistryMap.containsKey(newName))) ||
configuration.isAllowMultipleNamespaces();
}
public void updateResults() {
// some of the rules and functions may have been redefined
updateResults(this.results);
}
public void updateResults(List<KnowledgeBuilderResult> results) {
this.results = getResults(results);
}
public void compileAll() {
for (PackageRegistry pkgRegistry : this.pkgRegistryMap.values()) {
pkgRegistry.compileAll();
}
}
public void reloadAll() {
for (PackageRegistry pkgRegistry : this.pkgRegistryMap.values()) {
pkgRegistry.getDialectRuntimeRegistry().onBeforeExecute();
}
}
private List<KnowledgeBuilderResult> getResults(List<KnowledgeBuilderResult> results) {
for (PackageRegistry pkgRegistry : this.pkgRegistryMap.values()) {
results = pkgRegistry.getDialectCompiletimeRegistry().addResults(results);
}
return results;
}
public synchronized void addPackage(InternalKnowledgePackage newPkg) {
PackageRegistry pkgRegistry = this.pkgRegistryMap.get(newPkg.getName());
InternalKnowledgePackage pkg = null;
if (pkgRegistry != null) {
pkg = pkgRegistry.getPackage();
}
if (pkg == null) {
PackageDescr packageDescr = new PackageDescr(newPkg.getName());
pkgRegistry = newPackage(packageDescr);
mergePackage(this.pkgRegistryMap.get(packageDescr.getNamespace()), packageDescr);
pkg = pkgRegistry.getPackage();
}
// first merge anything related to classloader re-wiring
pkg.getDialectRuntimeRegistry().merge(newPkg.getDialectRuntimeRegistry(),
this.rootClassLoader);
if (newPkg.getFunctions() != null) {
for (Map.Entry<String, Function> entry : newPkg.getFunctions().entrySet()) {
if (pkg.getFunctions().containsKey(entry.getKey())) {
addBuilderResult(new DuplicateFunction(entry.getValue(),
this.configuration));
}
pkg.addFunction(entry.getValue());
}
}
pkg.getClassFieldAccessorStore().merge(newPkg.getClassFieldAccessorStore());
pkg.getDialectRuntimeRegistry().onBeforeExecute();
// we have to do this before the merging, as it does some classloader resolving
TypeDeclaration lastType = null;
try {
// Resolve the class for the type declaation
if (newPkg.getTypeDeclarations() != null) {
// add type declarations
for (TypeDeclaration type : newPkg.getTypeDeclarations().values()) {
lastType = type;
type.setTypeClass(this.rootClassLoader.loadClass(type.getTypeClassName()));
}
}
} catch (ClassNotFoundException e) {
throw new RuntimeException("unable to resolve Type Declaration class '" + lastType.getTypeName() + "'");
}
// now merge the new package into the existing one
mergePackage(pkg,
newPkg);
}
/**
* Merge a new package with an existing package. Most of the work is done by
* the concrete implementations, but this class does some work (including
* combining imports, compilation data, globals, and the actual Rule objects
* into the package).
*/
private void mergePackage(InternalKnowledgePackage pkg,
InternalKnowledgePackage newPkg) {
// Merge imports
final Map<String, ImportDeclaration> imports = pkg.getImports();
imports.putAll(newPkg.getImports());
String lastType = null;
try {
// merge globals
if (newPkg.getGlobals() != null && newPkg.getGlobals() != Collections.EMPTY_MAP) {
Map<String, String> globals = pkg.getGlobals();
// Add globals
for (final Map.Entry<String, String> entry : newPkg.getGlobals().entrySet()) {
final String identifier = entry.getKey();
final String type = entry.getValue();
lastType = type;
if (globals.containsKey(identifier) && !globals.get(identifier).equals(type)) {
throw new RuntimeException(pkg.getName() + " cannot be integrated");
} else {
pkg.addGlobal(identifier,
this.rootClassLoader.loadClass(type));
// this isn't a package merge, it's adding to the rulebase, but I've put it here for convenience
this.globals.put(identifier,
this.rootClassLoader.loadClass(type));
}
}
}
} catch (ClassNotFoundException e) {
throw new RuntimeException("Unable to resolve class '" + lastType + "'");
}
// merge the type declarations
if (newPkg.getTypeDeclarations() != null) {
// add type declarations
for (TypeDeclaration type : newPkg.getTypeDeclarations().values()) {
// @TODO should we allow overrides? only if the class is not in use.
if (!pkg.getTypeDeclarations().containsKey(type.getTypeName())) {
// add to package list of type declarations
pkg.addTypeDeclaration(type);
}
}
}
for (final org.kie.api.definition.rule.Rule newRule : newPkg.getRules()) {
pkg.addRule(((RuleImpl)newRule));
}
//Merge The Rule Flows
if (newPkg.getRuleFlows() != null) {
final Map flows = newPkg.getRuleFlows();
for (Object o : flows.values()) {
final Process flow = (Process) o;
pkg.addProcess(flow);
}
}
}
//
// private void validatePackageName(final PackageDescr packageDescr) {
// if ( (this.pkg == null || this.pkg.getName() == null || this.pkg.getName().equals( "" )) && (packageDescr.getName() == null || "".equals( packageDescr.getName() )) ) {
// throw new MissingPackageNameException( "Missing package name for rule package." );
// }
// if ( this.pkg != null && packageDescr.getName() != null && !"".equals( packageDescr.getName() ) && !this.pkg.getName().equals( packageDescr.getName() ) ) {
// throw new PackageMergeException( "Can't merge packages with different names. This package: " + this.pkg.getName() + " - New package: " + packageDescr.getName() );
// }
// return;
// }
private void validateUniqueRuleNames(final PackageDescr packageDescr) {
final Set<String> names = new HashSet<String>();
PackageRegistry packageRegistry = this.pkgRegistryMap.get(packageDescr.getNamespace());
InternalKnowledgePackage pkg = null;
if (packageRegistry != null) {
pkg = packageRegistry.getPackage();
}
for (final RuleDescr rule : packageDescr.getRules()) {
validateRule(packageDescr, rule);
final String name = rule.getName();
if (names.contains(name)) {
addBuilderResult(new ParserError(rule.getResource(),
"Duplicate rule name: " + name,
rule.getLine(),
rule.getColumn(),
packageDescr.getNamespace()));
}
if (pkg != null) {
RuleImpl duplicatedRule = pkg.getRule(name);
if (duplicatedRule != null) {
Resource resource = rule.getResource();
Resource duplicatedResource = duplicatedRule.getResource();
if (resource == null || duplicatedResource == null || duplicatedResource.getSourcePath() == null ||
duplicatedResource.getSourcePath().equals(resource.getSourcePath())) {
addBuilderResult(new DuplicateRule(rule,
packageDescr,
this.configuration));
} else {
addBuilderResult(new ParserError(rule.getResource(),
"Duplicate rule name: " + name,
rule.getLine(),
rule.getColumn(),
packageDescr.getNamespace()));
}
}
}
names.add(name);
}
}
private void validateRule(PackageDescr packageDescr,
RuleDescr rule) {
if (rule.hasErrors()) {
for (String error : rule.getErrors()) {
addBuilderResult(new ParserError(rule.getResource(),
error + " in rule " + rule.getName(),
rule.getLine(),
rule.getColumn(),
packageDescr.getNamespace()));
}
}
}
public PackageRegistry newPackage(final PackageDescr packageDescr) {
InternalKnowledgePackage pkg;
if (this.kBase == null || (pkg = this.kBase.getPackage(packageDescr.getName())) == null) {
// there is no rulebase or it does not define this package so define it
pkg = new KnowledgePackageImpl(packageDescr.getName());
pkg.setClassFieldAccessorCache(new ClassFieldAccessorCache(this.rootClassLoader));
// if there is a rulebase then add the package.
if (this.kBase != null) {
// Must lock here, otherwise the assumption about addPackage/getPackage behavior below might be violated
this.kBase.lock();
try {
this.kBase.addPackage(pkg);
pkg = this.kBase.getPackage(packageDescr.getName());
} finally {
this.kBase.unlock();
}
} else {
// the RuleBase will also initialise the
pkg.getDialectRuntimeRegistry().onAdd(this.rootClassLoader);
}
}
PackageRegistry pkgRegistry = new PackageRegistry(rootClassLoader, configuration, pkg);
// add default import for this namespace
pkgRegistry.addImport( new ImportDescr( packageDescr.getNamespace() + ".*" ) );
this.pkgRegistryMap.put( packageDescr.getName(), pkgRegistry );
return pkgRegistry;
}
void mergePackage(PackageRegistry pkgRegistry, PackageDescr packageDescr) {
for (final ImportDescr importDescr : packageDescr.getImports()) {
pkgRegistry.addImport(importDescr);
}
normalizeTypeDeclarationAnnotations( packageDescr );
processAccumulateFunctions(pkgRegistry, packageDescr);
processEntryPointDeclarations( pkgRegistry, packageDescr );
Map<String,AbstractClassTypeDeclarationDescr> unprocesseableDescrs = new HashMap<String,AbstractClassTypeDeclarationDescr>();
List<TypeDefinition> unresolvedTypes = new ArrayList<TypeDefinition>();
List<AbstractClassTypeDeclarationDescr> unsortedDescrs = new ArrayList<AbstractClassTypeDeclarationDescr>();
for ( TypeDeclarationDescr typeDeclarationDescr : packageDescr.getTypeDeclarations() ) {
unsortedDescrs.add( typeDeclarationDescr );
}
for ( EnumDeclarationDescr enumDeclarationDescr : packageDescr.getEnumDeclarations() ) {
unsortedDescrs.add( enumDeclarationDescr );
}
typeBuilder.processTypeDeclarations( Collections.singletonList( packageDescr ), unsortedDescrs, unresolvedTypes, unprocesseableDescrs );
for ( AbstractClassTypeDeclarationDescr descr : unprocesseableDescrs.values() ) {
this.addBuilderResult( new TypeDeclarationError( descr, "Unable to process type " + descr.getTypeName() ) );
}
processOtherDeclarations( pkgRegistry, packageDescr );
normalizeRuleAnnotations( packageDescr );
}
void processOtherDeclarations(PackageRegistry pkgRegistry, PackageDescr packageDescr) {
processAccumulateFunctions( pkgRegistry, packageDescr);
processWindowDeclarations(pkgRegistry, packageDescr);
processFunctions(pkgRegistry, packageDescr);
processGlobals(pkgRegistry, packageDescr);
// need to reinsert this to ensure that the package is the first/last one in the ordered map
// this feature is exploited by the knowledgeAgent
InternalKnowledgePackage current = getPackage();
this.pkgRegistryMap.remove(packageDescr.getName());
this.pkgRegistryMap.put(packageDescr.getName(), pkgRegistry);
if (current.getName().equals(packageDescr.getName())) {
currentRulePackage = pkgRegistryMap.size() - 1;
}
}
private void processGlobals(PackageRegistry pkgRegistry, PackageDescr packageDescr) {
InternalKnowledgePackage pkg = pkgRegistry.getPackage();
Set<String> existingGlobals = new HashSet<String>(pkg.getGlobals().keySet());
for (final GlobalDescr global : packageDescr.getGlobals()) {
final String identifier = global.getIdentifier();
existingGlobals.remove( identifier );
String className = global.getType();
// JBRULES-3039: can't handle type name with generic params
while (className.indexOf('<') >= 0) {
className = className.replaceAll("<[^<>]+?>", "");
}
try {
Class<?> clazz = pkgRegistry.getTypeResolver().resolveType(className);
if (clazz.isPrimitive()) {
addBuilderResult(new GlobalError(global, " Primitive types are not allowed in globals : " + className));
return;
}
pkg.addGlobal(identifier, clazz);
this.globals.put(identifier, clazz);
if (kBase != null) {
kBase.addGlobal(identifier, clazz);
}
} catch (final ClassNotFoundException e) {
addBuilderResult(new GlobalError(global, e.getMessage()));
e.printStackTrace();
}
}
for (String toBeRemoved : existingGlobals) {
if (filterAcceptsRemoval( ResourceChange.Type.GLOBAL, pkg.getName(), toBeRemoved )) {
pkg.removeGlobal( toBeRemoved );
if ( kBase != null ) {
kBase.removeGlobal( toBeRemoved );
}
}
}
}
private void processAccumulateFunctions(PackageRegistry pkgRegistry,
PackageDescr packageDescr) {
for (final AccumulateImportDescr aid : packageDescr.getAccumulateImports() ) {
AccumulateFunction af = loadAccumulateFunction(pkgRegistry,
aid.getFunctionName(),
aid.getTarget());
pkgRegistry.getPackage().addAccumulateFunction(aid.getFunctionName(), af);
}
}
@SuppressWarnings("unchecked")
private AccumulateFunction loadAccumulateFunction(PackageRegistry pkgRegistry,
String identifier,
String className) {
try {
Class< ? extends AccumulateFunction> clazz = (Class< ? extends AccumulateFunction>) pkgRegistry.getTypeResolver().resolveType(className);
return clazz.newInstance();
} catch ( ClassNotFoundException e ) {
throw new RuntimeException( "Error loading accumulate function for identifier " + identifier + ". Class " + className + " not found",
e );
} catch ( InstantiationException e ) {
throw new RuntimeException( "Error loading accumulate function for identifier " + identifier + ". Instantiation failed for class " + className,
e );
} catch ( IllegalAccessException e ) {
throw new RuntimeException( "Error loading accumulate function for identifier " + identifier + ". Illegal access to class " + className,
e );
}
}
private void processFunctions(PackageRegistry pkgRegistry,
PackageDescr packageDescr) {
for (FunctionDescr function : packageDescr.getFunctions()) {
Function existingFunc = pkgRegistry.getPackage().getFunctions().get(function.getName());
if (existingFunc != null && function.getNamespace().equals(existingFunc.getNamespace())) {
addBuilderResult(
new DuplicateFunction(function,
this.configuration));
}
}
for (final FunctionImportDescr functionImport : packageDescr.getFunctionImports()) {
String importEntry = functionImport.getTarget();
pkgRegistry.addStaticImport(functionImport);
pkgRegistry.getPackage().addStaticImport(importEntry);
}
}
public TypeDeclaration getAndRegisterTypeDeclaration(Class<?> cls, String packageName) {
return typeBuilder.getAndRegisterTypeDeclaration(cls, packageName);
}
void processEntryPointDeclarations(PackageRegistry pkgRegistry,
PackageDescr packageDescr) {
for (EntryPointDeclarationDescr epDescr : packageDescr.getEntryPointDeclarations()) {
pkgRegistry.getPackage().addEntryPointId(epDescr.getEntryPointId());
}
}
private void processWindowDeclarations(PackageRegistry pkgRegistry,
PackageDescr packageDescr) {
for (WindowDeclarationDescr wd : packageDescr.getWindowDeclarations()) {
WindowDeclaration window = new WindowDeclaration(wd.getName(), packageDescr.getName());
// TODO: process annotations
// process pattern
InternalKnowledgePackage pkg = pkgRegistry.getPackage();
DialectCompiletimeRegistry ctr = pkgRegistry.getDialectCompiletimeRegistry();
RuleDescr dummy = new RuleDescr(wd.getName() + " Window Declaration");
dummy.setResource(packageDescr.getResource());
dummy.addAttribute(new AttributeDescr("dialect", "java"));
RuleBuildContext context = new RuleBuildContext(this,
dummy,
ctr,
pkg,
ctr.getDialect(pkgRegistry.getDialect()));
final RuleConditionBuilder builder = (RuleConditionBuilder) context.getDialect().getBuilder(wd.getPattern().getClass());
if (builder != null) {
final Pattern pattern = (Pattern) builder.build(context,
wd.getPattern(),
null);
window.setPattern(pattern);
} else {
throw new RuntimeException(
"BUG: assembler not found for descriptor class " + wd.getPattern().getClass());
}
if (!context.getErrors().isEmpty()) {
for (DroolsError error : context.getErrors()) {
addBuilderResult(error);
}
} else {
pkgRegistry.getPackage().addWindowDeclaration(window);
}
}
}
private void addFunction(final FunctionDescr functionDescr) {
PackageRegistry pkgRegistry = this.pkgRegistryMap.get(functionDescr.getNamespace());
Dialect dialect = pkgRegistry.getDialectCompiletimeRegistry().getDialect(functionDescr.getDialect());
dialect.addFunction(functionDescr,
pkgRegistry.getTypeResolver(),
this.resource);
}
private void preCompileAddFunction(final FunctionDescr functionDescr) {
PackageRegistry pkgRegistry = this.pkgRegistryMap.get(functionDescr.getNamespace());
Dialect dialect = pkgRegistry.getDialectCompiletimeRegistry().getDialect(functionDescr.getDialect());
dialect.preCompileAddFunction(functionDescr,
pkgRegistry.getTypeResolver());
}
private void postCompileAddFunction(final FunctionDescr functionDescr) {
PackageRegistry pkgRegistry = this.pkgRegistryMap.get(functionDescr.getNamespace());
Dialect dialect = pkgRegistry.getDialectCompiletimeRegistry().getDialect(functionDescr.getDialect());
dialect.postCompileAddFunction(functionDescr, pkgRegistry.getTypeResolver());
if (rootClassLoader instanceof ProjectClassLoader) {
String functionClassName = functionDescr.getClassName();
JavaDialectRuntimeData runtime = ((JavaDialectRuntimeData) pkgRegistry.getDialectRuntimeRegistry().getDialectData( "java" ));
try {
registerFunctionClassAndInnerClasses( functionClassName, runtime,
(name, bytes) -> ((ProjectClassLoader)rootClassLoader).storeClass( name, bytes ));
} catch (ClassNotFoundException e) {
throw new RuntimeException( e );
}
}
}
private Map<String, RuleBuildContext> buildRuleBuilderContext(List<RuleDescr> rules) {
Map<String, RuleBuildContext> map = new HashMap<String, RuleBuildContext>();
for (RuleDescr ruleDescr : rules) {
if (ruleDescr.getResource() == null) {
ruleDescr.setResource(resource);
}
PackageRegistry pkgRegistry = this.pkgRegistryMap.get(ruleDescr.getNamespace());
InternalKnowledgePackage pkg = pkgRegistry.getPackage();
DialectCompiletimeRegistry ctr = pkgRegistry.getDialectCompiletimeRegistry();
RuleBuildContext context = new RuleBuildContext(this,
ruleDescr,
ctr,
pkg,
ctr.getDialect(pkgRegistry.getDialect()));
map.put(ruleDescr.getName(), context);
}
return map;
}
private void addRule(RuleBuildContext context) {
final RuleDescr ruleDescr = context.getRuleDescr();
InternalKnowledgePackage pkg = context.getPkg();
ruleBuilder.build(context);
this.results.addAll(context.getErrors());
this.results.addAll(context.getWarnings());
context.getRule().setResource(ruleDescr.getResource());
context.getDialect().addRule(context);
if (context.needsStreamMode()) {
pkg.setNeedStreamMode();
}
}
/**
* @return The compiled package. The package may contain errors, which you
* can report on by calling getErrors or printErrors. If you try to
* add an invalid package (or rule) to a RuleBase, you will get a
* runtime exception.
*
* Compiled packages are serializable.
*/
public InternalKnowledgePackage getPackage() {
PackageRegistry pkgRegistry = null;
if (!this.pkgRegistryMap.isEmpty()) {
pkgRegistry = (PackageRegistry) this.pkgRegistryMap.values().toArray()[currentRulePackage];
}
InternalKnowledgePackage pkg = null;
if (pkgRegistry != null) {
pkg = pkgRegistry.getPackage();
}
if (hasErrors() && pkg != null) {
pkg.setError(getErrors().toString());
}
return pkg;
}
public InternalKnowledgePackage[] getPackages() {
InternalKnowledgePackage[] pkgs = new InternalKnowledgePackage[this.pkgRegistryMap.size()];
String errors = null;
if (!getErrors().isEmpty()) {
errors = getErrors().toString();
}
int i = 0;
for (PackageRegistry pkgRegistry : this.pkgRegistryMap.values()) {
InternalKnowledgePackage pkg = pkgRegistry.getPackage();
pkg.getDialectRuntimeRegistry().onBeforeExecute();
if (errors != null) {
pkg.setError(errors);
}
pkgs[i++] = pkg;
}
return pkgs;
}
/**
* Return the PackageBuilderConfiguration for this PackageBuilder session
*
* @return The PackageBuilderConfiguration
*/
public KnowledgeBuilderConfigurationImpl getBuilderConfiguration() {
return this.configuration;
}
public PackageRegistry getPackageRegistry(String name) {
return this.pkgRegistryMap.get(name);
}
public Map<String, PackageRegistry> getPackageRegistry() {
return this.pkgRegistryMap;
}
public Collection<String> getPackageNames() {
return pkgRegistryMap.keySet();
}
public List<PackageDescr> getPackageDescrs(String packageName) {
return packages.get(packageName);
}
/**
* Returns an expander for DSLs (only if there is a DSL configured for this
* package).
*/
public DefaultExpander getDslExpander() {
DefaultExpander expander = new DefaultExpander();
if (this.dslFiles == null || this.dslFiles.isEmpty()) {
return null;
}
for (DSLMappingFile file : this.dslFiles) {
expander.addDSLMapping(file.getMapping());
}
return expander;
}
public Map<String, Class<?>> getGlobals() {
return this.globals;
}
/**
* This will return true if there were errors in the package building and
* compiling phase
*/
public boolean hasErrors() {
return !getErrorList().isEmpty();
}
public KnowledgeBuilderResults getResults(ResultSeverity... problemTypes) {
List<KnowledgeBuilderResult> problems = getResultList(problemTypes);
return new PackageBuilderResults(problems.toArray(new BaseKnowledgeBuilderResultImpl[problems.size()]));
}
private List<KnowledgeBuilderResult> getResultList(ResultSeverity... severities) {
List<ResultSeverity> typesToFetch = Arrays.asList(severities);
ArrayList<KnowledgeBuilderResult> problems = new ArrayList<KnowledgeBuilderResult>();
for (KnowledgeBuilderResult problem : results) {
if (typesToFetch.contains(problem.getSeverity())) {
problems.add(problem);
}
}
return problems;
}
public boolean hasResults(ResultSeverity... problemTypes) {
return !getResultList(problemTypes).isEmpty();
}
private List<DroolsError> getErrorList() {
List<DroolsError> errors = new ArrayList<DroolsError>();
for (KnowledgeBuilderResult problem : results) {
if (problem.getSeverity() == ResultSeverity.ERROR) {
if (problem instanceof ConfigurableSeverityResult) {
errors.add(new DroolsErrorWrapper(problem));
} else {
errors.add((DroolsError) problem);
}
}
}
return errors;
}
public boolean hasWarnings() {
return !getWarnings().isEmpty();
}
public boolean hasInfo() {
return !getInfoList().isEmpty();
}
public List<DroolsWarning> getWarnings() {
List<DroolsWarning> warnings = new ArrayList<DroolsWarning>();
for (KnowledgeBuilderResult problem : results) {
if (problem.getSeverity() == ResultSeverity.WARNING) {
if (problem instanceof ConfigurableSeverityResult) {
warnings.add(new DroolsWarningWrapper(problem));
} else {
warnings.add((DroolsWarning) problem);
}
}
}
return warnings;
}
private List<KnowledgeBuilderResult> getInfoList() {
return getResultList(ResultSeverity.INFO);
}
/**
* @return A list of Error objects that resulted from building and compiling
* the package.
*/
public PackageBuilderErrors getErrors() {
List<DroolsError> errors = getErrorList();
return new PackageBuilderErrors(errors.toArray(new DroolsError[errors.size()]));
}
/**
* Reset the error list. This is useful when incrementally building
* packages. Care should be used when building this, if you clear this when
* there were errors on items that a rule depends on (eg functions), then
* you will get spurious errors which will not be that helpful.
*/
protected void resetErrors() {
resetProblemType(ResultSeverity.ERROR);
}
protected void resetWarnings() {
resetProblemType(ResultSeverity.WARNING);
}
private void resetProblemType(ResultSeverity problemType) {
List<KnowledgeBuilderResult> toBeDeleted = new ArrayList<KnowledgeBuilderResult>();
for (KnowledgeBuilderResult problem : results) {
if (problemType != null && problemType.equals(problem.getSeverity())) {
toBeDeleted.add(problem);
}
}
this.results.removeAll(toBeDeleted);
}
protected void resetProblems() {
this.results.clear();
if (this.processBuilder != null) {
this.processBuilder.getErrors().clear();
}
}
public String getDefaultDialect() {
return this.defaultDialect;
}
public static class MissingPackageNameException extends IllegalArgumentException {
private static final long serialVersionUID = 510l;
public MissingPackageNameException(final String message) {
super(message);
}
}
public static class PackageMergeException extends IllegalArgumentException {
private static final long serialVersionUID = 400L;
public PackageMergeException(final String message) {
super(message);
}
}
public ClassLoader getRootClassLoader() {
return this.rootClassLoader;
}
//Entity rules inherit package attributes
private void inheritPackageAttributes(Map<String, AttributeDescr> pkgAttributes,
RuleDescr ruleDescr) {
if (pkgAttributes == null) {
return;
}
for (AttributeDescr attrDescr : pkgAttributes.values()) {
String name = attrDescr.getName();
AttributeDescr ruleAttrDescr = ruleDescr.getAttributes().get(name);
if (ruleAttrDescr == null) {
ruleDescr.getAttributes().put(name,
attrDescr);
}
}
}
private ChangeSet parseChangeSet(Resource resource) throws IOException, SAXException {
XmlChangeSetReader reader = new XmlChangeSetReader(this.configuration.getSemanticModules());
if (resource instanceof ClassPathResource) {
reader.setClassLoader(((ClassPathResource) resource).getClassLoader(),
((ClassPathResource) resource).getClazz());
} else {
reader.setClassLoader(this.configuration.getClassLoader(),
null);
}
Reader resourceReader = null;
try {
resourceReader = resource.getReader();
return reader.read(resourceReader);
} finally {
if (resourceReader != null) {
resourceReader.close();
}
}
}
public void registerBuildResource(final Resource resource, ResourceType type) {
InternalResource ires = (InternalResource) resource;
if (ires.getResourceType() == null) {
ires.setResourceType(type);
} else if (ires.getResourceType() != type) {
addBuilderResult(new ResourceTypeDeclarationWarning(resource, ires.getResourceType(), type));
}
if (ResourceType.CHANGE_SET == type) {
try {
ChangeSet changeSet = parseChangeSet(resource);
List<Resource> resources = new ArrayList<Resource>();
resources.add(resource);
for (Resource addedRes : changeSet.getResourcesAdded()) {
resources.add(addedRes);
}
for (Resource modifiedRes : changeSet.getResourcesModified()) {
resources.add(modifiedRes);
}
for (Resource removedRes : changeSet.getResourcesRemoved()) {
resources.add(removedRes);
}
buildResources.push(resources);
} catch (Exception e) {
results.add(new DroolsError() {
public String getMessage() {
return "Unable to register changeset resource " + resource;
}
public int[] getLines() {
return new int[0];
}
});
}
} else {
buildResources.push( Collections.singletonList( resource ) );
}
}
public void registerBuildResources(List<Resource> resources) {
buildResources.push(resources);
}
public void undo() {
if (buildResources.isEmpty()) {
return;
}
for (Resource resource : buildResources.pop()) {
removeObjectsGeneratedFromResource(resource);
}
}
public boolean removeObjectsGeneratedFromResource(Resource resource) {
boolean modified = false;
if (pkgRegistryMap != null) {
for (PackageRegistry packageRegistry : pkgRegistryMap.values()) {
modified = packageRegistry.removeObjectsGeneratedFromResource(resource) || modified;
}
}
if (results != null) {
Iterator<KnowledgeBuilderResult> i = results.iterator();
while (i.hasNext()) {
if (resource.equals(i.next().getResource())) {
i.remove();
}
}
}
if (processBuilder != null && processBuilder.getErrors() != null) {
Iterator<? extends KnowledgeBuilderResult> i = processBuilder.getErrors().iterator();
while (i.hasNext()) {
if (resource.equals(i.next().getResource())) {
i.remove();
}
}
}
if (results.size() == 0) {
// TODO Error attribution might be bugged
for (PackageRegistry packageRegistry : pkgRegistryMap.values()) {
packageRegistry.getPackage().resetErrors();
}
}
typeBuilder.removeTypesGeneratedFromResource(resource);
for (List<PackageDescr> pkgDescrs : packages.values()) {
for (PackageDescr pkgDescr : pkgDescrs) {
pkgDescr.removeObjectsGeneratedFromResource(resource);
}
}
if (kBase != null) {
modified = kBase.removeObjectsGeneratedFromResource(resource) || modified;
}
return modified;
}
public void rewireAllClassObjectTypes() {
if (kBase != null) {
for (InternalKnowledgePackage pkg : kBase.getPackagesMap().values()) {
pkg.getDialectRuntimeRegistry().getDialectData("java").setDirty(true);
pkg.getClassFieldAccessorStore().wire();
}
}
}
public interface AssetFilter {
enum Action {
DO_NOTHING, ADD, REMOVE, UPDATE
}
Action accept(ResourceChange.Type type, String pkgName, String assetName);
}
AssetFilter getAssetFilter() {
return assetFilter;
}
public void setAssetFilter(AssetFilter assetFilter) {
this.assetFilter = assetFilter;
}
public void add(Resource resource, ResourceType type) {
ResourceConfiguration resourceConfiguration = resource instanceof BaseResource ? resource.getConfiguration() : null;
add(resource, type, resourceConfiguration) ;
}
public CompositeKnowledgeBuilder batch() {
return new CompositeKnowledgeBuilderImpl(this);
}
public void add(Resource resource,
ResourceType type,
ResourceConfiguration configuration) {
registerBuildResource(resource, type);
addKnowledgeResource(resource, type, configuration);
}
public Collection<KnowledgePackage> getKnowledgePackages() {
if ( hasErrors() ) {
return new ArrayList<KnowledgePackage>( 0 );
}
InternalKnowledgePackage[] pkgs = getPackages();
List<KnowledgePackage> list = new ArrayList<KnowledgePackage>( pkgs.length );
Collections.addAll(list, pkgs);
return list;
}
public KnowledgeBase newKnowledgeBase() {
return newKnowledgeBase(null);
}
public KnowledgeBase newKnowledgeBase(KieBaseConfiguration conf) {
KnowledgeBuilderErrors errors = getErrors();
if (errors.size() > 0) {
for (KnowledgeBuilderError error: errors) {
logger.error(error.toString());
}
throw new IllegalArgumentException("Could not parse knowledge.");
}
KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(conf);
kbase.addKnowledgePackages(getKnowledgePackages());
return kbase;
}
public TypeDeclaration getTypeDeclaration(Class<?> cls) {
return typeBuilder.getTypeDeclaration(cls);
}
public void normalizeTypeDeclarationAnnotations(PackageDescr packageDescr) {
TypeResolver typeResolver = pkgRegistryMap.get(packageDescr.getName()).getTypeResolver();
boolean isStrict = configuration.getLanguageLevel().useJavaAnnotations();
for (TypeDeclarationDescr typeDeclarationDescr : packageDescr.getTypeDeclarations()) {
normalizeAnnotations(typeDeclarationDescr, typeResolver, isStrict);
for (TypeFieldDescr typeFieldDescr : typeDeclarationDescr.getFields().values()) {
normalizeAnnotations(typeFieldDescr, typeResolver, isStrict);
}
}
for (EnumDeclarationDescr enumDeclarationDescr : packageDescr.getEnumDeclarations()) {
normalizeAnnotations(enumDeclarationDescr, typeResolver, isStrict);
for (TypeFieldDescr typeFieldDescr : enumDeclarationDescr.getFields().values()) {
normalizeAnnotations(typeFieldDescr, typeResolver, isStrict);
}
}
}
public void normalizeRuleAnnotations(PackageDescr packageDescr) {
TypeResolver typeResolver = pkgRegistryMap.get(packageDescr.getName()).getTypeResolver();
boolean isStrict = configuration.getLanguageLevel().useJavaAnnotations();
for ( RuleDescr ruleDescr : packageDescr.getRules() ) {
normalizeAnnotations( ruleDescr, typeResolver, isStrict );
traverseAnnotations( ruleDescr.getLhs(), typeResolver, isStrict );
}
}
private void traverseAnnotations( BaseDescr descr, TypeResolver typeResolver, boolean isStrict ) {
if ( descr instanceof AnnotatedBaseDescr ) {
normalizeAnnotations( (AnnotatedBaseDescr) descr, typeResolver, isStrict );
}
if ( descr instanceof ConditionalElementDescr ) {
for ( BaseDescr baseDescr : ( (ConditionalElementDescr) descr ).getDescrs() ) {
traverseAnnotations( baseDescr, typeResolver, isStrict );
}
}
if ( descr instanceof PatternDescr && ( (PatternDescr) descr ).getSource() != null ) {
traverseAnnotations( ( (PatternDescr) descr ).getSource(), typeResolver, isStrict );
}
if ( descr instanceof PatternDestinationDescr ) {
traverseAnnotations( ( (PatternDestinationDescr) descr ).getInputPattern(), typeResolver, isStrict );
}
}
private void normalizeAnnotations(AnnotatedBaseDescr annotationsContainer, TypeResolver typeResolver, boolean isStrict) {
for (AnnotationDescr annotationDescr : annotationsContainer.getAnnotations()) {
annotationDescr.setResource(annotationsContainer.getResource());
annotationDescr.setStrict(isStrict);
if (annotationDescr.isDuplicated()) {
addBuilderResult(new AnnotationDeclarationError(annotationDescr,
"Duplicated annotation: " + annotationDescr.getName()));
}
if (isStrict) {
normalizeStrictAnnotation(typeResolver, annotationDescr);
} else {
normalizeAnnotation(typeResolver, annotationDescr);
}
}
annotationsContainer.indexByFQN(isStrict);
}
private AnnotationDescr normalizeAnnotation(TypeResolver typeResolver, AnnotationDescr annotationDescr) {
Class<?> annotationClass = null;
try {
annotationClass = typeResolver.resolveType(annotationDescr.getName(), TypeResolver.ONLY_ANNOTATION_CLASS_FILTER);
} catch (ClassNotFoundException e) {
String className = normalizeAnnotationNonStrictName(annotationDescr.getName());
try {
annotationClass = typeResolver.resolveType(className, TypeResolver.ONLY_ANNOTATION_CLASS_FILTER);
} catch (ClassNotFoundException e1) {
// non-strict annotation, ignore error
} catch (NoClassDefFoundError e1) {
// non-strict annotation, ignore error
}
} catch (NoClassDefFoundError e) {
String className = normalizeAnnotationNonStrictName(annotationDescr.getName());
try {
annotationClass = typeResolver.resolveType(className, TypeResolver.ONLY_ANNOTATION_CLASS_FILTER);
} catch (ClassNotFoundException e1) {
// non-strict annotation, ignore error
} catch (NoClassDefFoundError e1) {
// non-strict annotation, ignore error
}
}
if (annotationClass != null) {
annotationDescr.setFullyQualifiedName(annotationClass.getCanonicalName());
for ( String key : annotationDescr.getValueMap().keySet() ) {
try {
Method m = annotationClass.getMethod( key );
Object val = annotationDescr.getValue( key );
if ( val instanceof Object[] && ! m.getReturnType().isArray() ) {
addBuilderResult( new AnnotationDeclarationError( annotationDescr,
"Wrong cardinality on property " + key ) );
return annotationDescr;
}
if ( m.getReturnType().isArray() && ! (val instanceof Object[]) ) {
val = new Object[] { val };
annotationDescr.setKeyValue( key, val );
}
if ( m.getReturnType().isArray() ) {
int n = Array.getLength(val);
for ( int j = 0; j < n; j++ ) {
if ( Class.class.equals( m.getReturnType().getComponentType() ) ) {
String className = Array.get( val, j ).toString().replace( ".class", "" );
Array.set( val, j, typeResolver.resolveType( className ).getName() + ".class" );
} else if ( m.getReturnType().getComponentType().isAnnotation() ) {
Array.set( val, j, normalizeAnnotation( typeResolver,
(AnnotationDescr) Array.get( val, j ) ) );
}
}
} else {
if ( Class.class.equals( m.getReturnType() ) ) {
String className = annotationDescr.getValueAsString(key).replace( ".class", "" );
annotationDescr.setKeyValue( key, typeResolver.resolveType( className ).getName() + ".class" );
} else if ( m.getReturnType().isAnnotation() ) {
annotationDescr.setKeyValue( key,
normalizeAnnotation( typeResolver,
(AnnotationDescr) annotationDescr.getValue( key ) ) );
}
}
} catch ( NoSuchMethodException e ) {
addBuilderResult( new AnnotationDeclarationError( annotationDescr,
"Unknown annotation property " + key ) );
} catch ( ClassNotFoundException e ) {
addBuilderResult( new AnnotationDeclarationError( annotationDescr,
"Unknown class " + annotationDescr.getValue( key ) + " used in property " + key +
" of annotation " + annotationDescr.getName() ) );
} catch ( NoClassDefFoundError e ) {
addBuilderResult( new AnnotationDeclarationError( annotationDescr,
"Unknown class " + annotationDescr.getValue( key ) + " used in property " + key +
" of annotation " + annotationDescr.getName() ) );
}
}
}
return annotationDescr;
}
private String normalizeAnnotationNonStrictName(String name) {
if ("typesafe".equalsIgnoreCase(name)) {
return "TypeSafe";
}
return ucFirst(name);
}
private void normalizeStrictAnnotation(TypeResolver typeResolver, AnnotationDescr annotationDescr) {
try {
Class<?> annotationClass = typeResolver.resolveType(annotationDescr.getName(), TypeResolver.ONLY_ANNOTATION_CLASS_FILTER);
annotationDescr.setFullyQualifiedName(annotationClass.getCanonicalName());
} catch (ClassNotFoundException e) {
addBuilderResult(new AnnotationDeclarationError(annotationDescr,
"Unknown annotation: " + annotationDescr.getName()));
} catch (NoClassDefFoundError e) {
addBuilderResult(new AnnotationDeclarationError(annotationDescr,
"Unknown annotation: " + annotationDescr.getName()));
}
}
} | drools-compiler/src/main/java/org/drools/compiler/builder/impl/KnowledgeBuilderImpl.java | /*
* Copyright 2015 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.drools.compiler.builder.impl;
import org.drools.compiler.compiler.AnnotationDeclarationError;
import org.drools.compiler.compiler.BPMN2ProcessFactory;
import org.drools.compiler.compiler.BaseKnowledgeBuilderResultImpl;
import org.drools.compiler.compiler.ConfigurableSeverityResult;
import org.drools.compiler.compiler.DecisionTableFactory;
import org.drools.compiler.compiler.DeprecatedResourceTypeWarning;
import org.drools.compiler.compiler.Dialect;
import org.drools.compiler.compiler.DialectCompiletimeRegistry;
import org.drools.compiler.compiler.DrlParser;
import org.drools.compiler.compiler.DroolsError;
import org.drools.compiler.compiler.DroolsErrorWrapper;
import org.drools.compiler.compiler.DroolsParserException;
import org.drools.compiler.compiler.DroolsWarning;
import org.drools.compiler.compiler.DroolsWarningWrapper;
import org.drools.compiler.compiler.DuplicateFunction;
import org.drools.compiler.compiler.DuplicateRule;
import org.drools.compiler.compiler.GlobalError;
import org.drools.compiler.compiler.GuidedDecisionTableFactory;
import org.drools.compiler.compiler.GuidedDecisionTableProvider;
import org.drools.compiler.compiler.GuidedRuleTemplateFactory;
import org.drools.compiler.compiler.GuidedRuleTemplateProvider;
import org.drools.compiler.compiler.GuidedScoreCardFactory;
import org.drools.compiler.compiler.PMMLCompiler;
import org.drools.compiler.compiler.PMMLCompilerFactory;
import org.drools.compiler.compiler.PackageBuilderErrors;
import org.drools.compiler.compiler.PackageBuilderResults;
import org.drools.compiler.compiler.PackageRegistry;
import org.drools.compiler.compiler.ParserError;
import org.drools.compiler.compiler.ProcessBuilder;
import org.drools.compiler.compiler.ProcessBuilderFactory;
import org.drools.compiler.compiler.ProcessLoadError;
import org.drools.compiler.compiler.ResourceConversionResult;
import org.drools.compiler.compiler.ResourceTypeDeclarationWarning;
import org.drools.compiler.compiler.RuleBuildError;
import org.drools.compiler.compiler.ScoreCardFactory;
import org.drools.compiler.compiler.TypeDeclarationError;
import org.drools.compiler.compiler.xml.XmlPackageReader;
import org.drools.compiler.lang.ExpanderException;
import org.drools.compiler.lang.descr.AbstractClassTypeDeclarationDescr;
import org.drools.compiler.lang.descr.AccumulateImportDescr;
import org.drools.compiler.lang.descr.AnnotatedBaseDescr;
import org.drools.compiler.lang.descr.AnnotationDescr;
import org.drools.compiler.lang.descr.AttributeDescr;
import org.drools.compiler.lang.descr.BaseDescr;
import org.drools.compiler.lang.descr.CompositePackageDescr;
import org.drools.compiler.lang.descr.ConditionalElementDescr;
import org.drools.compiler.lang.descr.EntryPointDeclarationDescr;
import org.drools.compiler.lang.descr.EnumDeclarationDescr;
import org.drools.compiler.lang.descr.FunctionDescr;
import org.drools.compiler.lang.descr.FunctionImportDescr;
import org.drools.compiler.lang.descr.GlobalDescr;
import org.drools.compiler.lang.descr.ImportDescr;
import org.drools.compiler.lang.descr.PackageDescr;
import org.drools.compiler.lang.descr.PatternDescr;
import org.drools.compiler.lang.descr.PatternDestinationDescr;
import org.drools.compiler.lang.descr.RuleDescr;
import org.drools.compiler.lang.descr.TypeDeclarationDescr;
import org.drools.compiler.lang.descr.TypeFieldDescr;
import org.drools.compiler.lang.descr.WindowDeclarationDescr;
import org.drools.compiler.lang.dsl.DSLMappingFile;
import org.drools.compiler.lang.dsl.DSLTokenizedMappingFile;
import org.drools.compiler.lang.dsl.DefaultExpander;
import org.drools.compiler.rule.builder.RuleBuildContext;
import org.drools.compiler.rule.builder.RuleBuilder;
import org.drools.compiler.rule.builder.RuleConditionBuilder;
import org.drools.compiler.rule.builder.dialect.DialectError;
import org.drools.compiler.runtime.pipeline.impl.DroolsJaxbHelperProviderImpl;
import org.drools.core.base.ClassFieldAccessorCache;
import org.drools.core.base.TypeResolver;
import org.drools.core.builder.conf.impl.JaxbConfigurationImpl;
import org.drools.core.common.ProjectClassLoader;
import org.drools.core.definitions.InternalKnowledgePackage;
import org.drools.core.definitions.impl.KnowledgePackageImpl;
import org.drools.core.definitions.rule.impl.RuleImpl;
import org.drools.core.impl.InternalKnowledgeBase;
import org.drools.core.io.impl.BaseResource;
import org.drools.core.io.impl.ClassPathResource;
import org.drools.core.io.impl.DescrResource;
import org.drools.core.io.impl.ReaderResource;
import org.drools.core.io.internal.InternalResource;
import org.drools.core.rule.Function;
import org.drools.core.rule.ImportDeclaration;
import org.drools.core.rule.JavaDialectRuntimeData;
import org.drools.core.rule.Pattern;
import org.drools.core.rule.TypeDeclaration;
import org.drools.core.rule.WindowDeclaration;
import org.drools.core.util.DroolsStreamUtils;
import org.drools.core.util.IoUtils;
import org.drools.core.util.StringUtils;
import org.drools.core.xml.XmlChangeSetReader;
import org.kie.api.KieBaseConfiguration;
import org.kie.api.definition.process.Process;
import org.kie.api.io.Resource;
import org.kie.api.io.ResourceConfiguration;
import org.kie.api.io.ResourceType;
import org.kie.api.runtime.rule.AccumulateFunction;
import org.kie.internal.ChangeSet;
import org.kie.internal.KnowledgeBase;
import org.kie.internal.KnowledgeBaseFactory;
import org.kie.internal.assembler.KieAssemblerService;
import org.kie.internal.assembler.KieAssemblers;
import org.kie.internal.builder.CompositeKnowledgeBuilder;
import org.kie.internal.builder.DecisionTableConfiguration;
import org.kie.internal.builder.KnowledgeBuilder;
import org.kie.internal.builder.KnowledgeBuilderError;
import org.kie.internal.builder.KnowledgeBuilderErrors;
import org.kie.internal.builder.KnowledgeBuilderResult;
import org.kie.internal.builder.KnowledgeBuilderResults;
import org.kie.internal.builder.ResourceChange;
import org.kie.internal.builder.ResultSeverity;
import org.kie.internal.builder.ScoreCardConfiguration;
import org.kie.internal.definition.KnowledgePackage;
import org.kie.internal.utils.ServiceRegistryImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.SAXException;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.StringReader;
import java.lang.reflect.Array;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Stack;
import java.util.UUID;
import static org.drools.core.impl.KnowledgeBaseImpl.registerFunctionClassAndInnerClasses;
import static org.drools.core.util.StringUtils.isEmpty;
import static org.drools.core.util.StringUtils.ucFirst;
public class KnowledgeBuilderImpl implements KnowledgeBuilder {
protected static final transient Logger logger = LoggerFactory.getLogger(KnowledgeBuilderImpl.class);
private final Map<String, PackageRegistry> pkgRegistryMap;
private List<KnowledgeBuilderResult> results;
private final KnowledgeBuilderConfigurationImpl configuration;
public static final RuleBuilder ruleBuilder = new RuleBuilder();
/**
* Optional RuleBase for incremental live building
*/
private InternalKnowledgeBase kBase;
/**
* default dialect
*/
private final String defaultDialect;
private ClassLoader rootClassLoader;
private final Map<String, Class<?>> globals = new HashMap<String, Class<?>>();
private Resource resource;
private List<DSLTokenizedMappingFile> dslFiles;
private final org.drools.compiler.compiler.ProcessBuilder processBuilder;
private IllegalArgumentException processBuilderCreationFailure;
private PMMLCompiler pmmlCompiler;
//This list of package level attributes is initialised with the PackageDescr's attributes added to the assembler.
//The package level attributes are inherited by individual rules not containing explicit overriding parameters.
//The map is keyed on the PackageDescr's namespace and contains a map of AttributeDescr's keyed on the
//AttributeDescr's name.
private final Map<String, Map<String, AttributeDescr>> packageAttributes = new HashMap<String, Map<String, AttributeDescr>>();
//PackageDescrs' list of ImportDescrs are kept identical as subsequent PackageDescrs are added.
private final Map<String, List<PackageDescr>> packages = new HashMap<String, List<PackageDescr>>();
private final Stack<List<Resource>> buildResources = new Stack<List<Resource>>();
private int currentRulePackage = 0;
private AssetFilter assetFilter = null;
private final TypeDeclarationBuilder typeBuilder;
/**
* Use this when package is starting from scratch.
*/
public KnowledgeBuilderImpl() {
this((InternalKnowledgeBase) null,
null);
}
/**
* This will allow you to merge rules into this pre existing package.
*/
public KnowledgeBuilderImpl(final InternalKnowledgePackage pkg) {
this(pkg,
null);
}
public KnowledgeBuilderImpl(final InternalKnowledgeBase kBase) {
this(kBase,
null);
}
/**
* Pass a specific configuration for the PackageBuilder
*
* PackageBuilderConfiguration is not thread safe and it also contains
* state. Once it is created and used in one or more PackageBuilders it
* should be considered immutable. Do not modify its properties while it is
* being used by a PackageBuilder.
*/
public KnowledgeBuilderImpl(final KnowledgeBuilderConfigurationImpl configuration) {
this((InternalKnowledgeBase) null,
configuration);
}
public KnowledgeBuilderImpl(InternalKnowledgePackage pkg,
KnowledgeBuilderConfigurationImpl configuration) {
if (configuration == null) {
this.configuration = new KnowledgeBuilderConfigurationImpl();
} else {
this.configuration = configuration;
}
this.rootClassLoader = this.configuration.getClassLoader();
this.defaultDialect = this.configuration.getDefaultDialect();
this.pkgRegistryMap = new LinkedHashMap<String, PackageRegistry>();
this.results = new ArrayList<KnowledgeBuilderResult>();
PackageRegistry pkgRegistry = new PackageRegistry(rootClassLoader, this.configuration, pkg);
pkgRegistry.setDialect(this.defaultDialect);
this.pkgRegistryMap.put(pkg.getName(),
pkgRegistry);
// add imports to pkg registry
for (final ImportDeclaration implDecl : pkg.getImports().values()) {
pkgRegistry.addImport(new ImportDescr(implDecl.getTarget()));
}
processBuilder = createProcessBuilder();
typeBuilder = new TypeDeclarationBuilder(this);
}
public KnowledgeBuilderImpl(InternalKnowledgeBase kBase,
KnowledgeBuilderConfigurationImpl configuration) {
if (configuration == null) {
this.configuration = new KnowledgeBuilderConfigurationImpl();
} else {
this.configuration = configuration;
}
if (kBase != null) {
this.rootClassLoader = kBase.getRootClassLoader();
} else {
this.rootClassLoader = this.configuration.getClassLoader();
}
// FIXME, we need to get drools to support "default" namespace.
//this.defaultNamespace = pkg.getName();
this.defaultDialect = this.configuration.getDefaultDialect();
this.pkgRegistryMap = new LinkedHashMap<String, PackageRegistry>();
this.results = new ArrayList<KnowledgeBuilderResult>();
this.kBase = kBase;
processBuilder = createProcessBuilder();
typeBuilder = new TypeDeclarationBuilder(this);
}
private ProcessBuilder createProcessBuilder() {
try {
return ProcessBuilderFactory.newProcessBuilder(this);
} catch (IllegalArgumentException e) {
processBuilderCreationFailure = e;
return null;
}
}
private PMMLCompiler getPMMLCompiler() {
if (this.pmmlCompiler == null) {
this.pmmlCompiler = PMMLCompilerFactory.getPMMLCompiler();
}
return this.pmmlCompiler;
}
Resource getCurrentResource() {
return resource;
}
public InternalKnowledgeBase getKnowledgeBase() {
return kBase;
}
TypeDeclarationBuilder getTypeBuilder() {
return typeBuilder;
}
/**
* Load a rule package from DRL source.
*
* @throws DroolsParserException
* @throws java.io.IOException
*/
public void addPackageFromDrl(final Reader reader) throws DroolsParserException,
IOException {
addPackageFromDrl(reader, new ReaderResource(reader, ResourceType.DRL));
}
/**
* Load a rule package from DRL source and associate all loaded artifacts
* with the given resource.
*
* @param reader
* @param sourceResource the source resource for the read artifacts
* @throws DroolsParserException
* @throws IOException
*/
public void addPackageFromDrl(final Reader reader,
final Resource sourceResource) throws DroolsParserException,
IOException {
this.resource = sourceResource;
final DrlParser parser = new DrlParser(configuration.getLanguageLevel());
final PackageDescr pkg = parser.parse(sourceResource, reader);
this.results.addAll(parser.getErrors());
if (pkg == null) {
addBuilderResult(new ParserError(sourceResource, "Parser returned a null Package", 0, 0));
}
if (!parser.hasErrors()) {
addPackage(pkg);
}
this.resource = null;
}
public void addPackageFromDecisionTable(Resource resource,
ResourceConfiguration configuration) throws DroolsParserException,
IOException {
this.resource = resource;
addPackage( decisionTableToPackageDescr( resource, configuration ) );
this.resource = null;
}
PackageDescr decisionTableToPackageDescr(Resource resource,
ResourceConfiguration configuration) throws DroolsParserException,
IOException {
DecisionTableConfiguration dtableConfiguration = configuration instanceof DecisionTableConfiguration ?
(DecisionTableConfiguration) configuration :
null;
if ( dtableConfiguration != null && !dtableConfiguration.getRuleTemplateConfigurations().isEmpty() ) {
List<String> generatedDrls = DecisionTableFactory.loadFromInputStreamWithTemplates( resource, dtableConfiguration );
if ( generatedDrls.size() == 1 ) {
return generatedDrlToPackageDescr( resource, generatedDrls.get(0) );
}
CompositePackageDescr compositePackageDescr = null;
for ( String generatedDrl : generatedDrls ) {
PackageDescr packageDescr = generatedDrlToPackageDescr( resource, generatedDrl );
if ( packageDescr != null ) {
if ( compositePackageDescr == null ) {
compositePackageDescr = new CompositePackageDescr( resource, packageDescr );
} else {
compositePackageDescr.addPackageDescr( resource, packageDescr );
}
}
}
return compositePackageDescr;
}
String generatedDrl = DecisionTableFactory.loadFromResource(resource, dtableConfiguration);
return generatedDrlToPackageDescr( resource, generatedDrl );
}
public void addPackageFromGuidedDecisionTable(Resource resource) throws DroolsParserException,
IOException {
this.resource = resource;
addPackage( guidedDecisionTableToPackageDescr( resource ) );
this.resource = null;
}
PackageDescr guidedDecisionTableToPackageDescr(Resource resource) throws DroolsParserException,
IOException {
GuidedDecisionTableProvider guidedDecisionTableProvider = GuidedDecisionTableFactory.getGuidedDecisionTableProvider();
ResourceConversionResult conversionResult = guidedDecisionTableProvider.loadFromInputStream(resource.getInputStream());
return conversionResultToPackageDescr(resource, conversionResult);
}
private PackageDescr generatedDrlToPackageDescr( Resource resource, String generatedDrl ) throws DroolsParserException {
// dump the generated DRL if the dump dir was configured
if (this.configuration.getDumpDir() != null) {
dumpDrlGeneratedFromDTable(this.configuration.getDumpDir(), generatedDrl, resource.getSourcePath());
}
DrlParser parser = new DrlParser(configuration.getLanguageLevel());
PackageDescr pkg = parser.parse(resource, new StringReader(generatedDrl));
this.results.addAll(parser.getErrors());
if (pkg == null) {
addBuilderResult(new ParserError(resource, "Parser returned a null Package", 0, 0));
} else {
pkg.setResource(resource);
}
return parser.hasErrors() ? null : pkg;
}
PackageDescr generatedDslrToPackageDescr(Resource resource, String dslr) throws DroolsParserException {
return dslrReaderToPackageDescr(resource, new StringReader(dslr));
}
private void dumpDrlGeneratedFromDTable(File dumpDir, String generatedDrl, String srcPath) {
File dumpFile;
if (srcPath != null) {
dumpFile = createDumpDrlFile(dumpDir, srcPath, ".drl");
} else {
dumpFile = createDumpDrlFile(dumpDir, "decision-table-" + UUID.randomUUID(), ".drl");
}
try {
IoUtils.write(dumpFile, generatedDrl.getBytes(IoUtils.UTF8_CHARSET));
} catch (IOException ex) {
// nothing serious, just failure when writing the generated DRL to file, just log the exception and continue
logger.warn("Can't write the DRL generated from decision table to file " + dumpFile.getAbsolutePath() + "!\n" +
Arrays.toString(ex.getStackTrace()));
}
}
protected static File createDumpDrlFile(File dumpDir, String fileName, String extension) {
return new File(dumpDir, fileName.replaceAll("[^a-zA-Z0-9\\.\\-_]+", "_") + extension);
}
public void addPackageFromScoreCard(Resource resource,
ResourceConfiguration configuration) throws DroolsParserException,
IOException {
this.resource = resource;
addPackage( scoreCardToPackageDescr( resource, configuration ) );
this.resource = null;
}
PackageDescr scoreCardToPackageDescr(Resource resource,
ResourceConfiguration configuration) throws DroolsParserException,
IOException {
ScoreCardConfiguration scardConfiguration = configuration instanceof ScoreCardConfiguration ?
(ScoreCardConfiguration) configuration :
null;
String string = ScoreCardFactory.loadFromInputStream(resource.getInputStream(), scardConfiguration);
return generatedDrlToPackageDescr( resource, string );
}
public void addPackageFromGuidedScoreCard(Resource resource) throws DroolsParserException,
IOException {
this.resource = resource;
addPackage( guidedScoreCardToPackageDescr(resource) );
this.resource = null;
}
PackageDescr guidedScoreCardToPackageDescr(Resource resource) throws DroolsParserException,
IOException {
String drl = GuidedScoreCardFactory.loadFromInputStream(resource.getInputStream());
return generatedDrlToPackageDescr(resource, drl);
}
public void addPackageFromTemplate(Resource resource) throws DroolsParserException,
IOException {
this.resource = resource;
addPackage(templateToPackageDescr(resource));
this.resource = null;
}
PackageDescr templateToPackageDescr(Resource resource) throws DroolsParserException,
IOException {
GuidedRuleTemplateProvider guidedRuleTemplateProvider = GuidedRuleTemplateFactory.getGuidedRuleTemplateProvider();
ResourceConversionResult conversionResult = guidedRuleTemplateProvider.loadFromInputStream(resource.getInputStream());
return conversionResultToPackageDescr(resource, conversionResult);
}
private PackageDescr conversionResultToPackageDescr(Resource resource, ResourceConversionResult resourceConversionResult)
throws DroolsParserException {
ResourceType resourceType = resourceConversionResult.getType();
if (ResourceType.DSLR.equals(resourceType)) {
return generatedDslrToPackageDescr(resource, resourceConversionResult.getContent());
} else if (ResourceType.DRL.equals(resourceType)) {
return generatedDrlToPackageDescr(resource, resourceConversionResult.getContent());
} else {
throw new RuntimeException("Converting generated " + resourceType + " into PackageDescr is not supported!");
}
}
public void addPackageFromDrl(Resource resource) throws DroolsParserException,
IOException {
this.resource = resource;
addPackage(drlToPackageDescr(resource));
this.resource = null;
}
PackageDescr drlToPackageDescr(Resource resource) throws DroolsParserException,
IOException {
PackageDescr pkg;
boolean hasErrors = false;
if (resource instanceof DescrResource) {
pkg = (PackageDescr) ((DescrResource) resource).getDescr();
} else {
final DrlParser parser = new DrlParser(configuration.getLanguageLevel());
pkg = parser.parse(resource);
this.results.addAll(parser.getErrors());
if (pkg == null) {
addBuilderResult(new ParserError(resource, "Parser returned a null Package", 0, 0));
}
hasErrors = parser.hasErrors();
}
if (pkg != null) {
pkg.setResource(resource);
}
return hasErrors ? null : pkg;
}
/**
* Load a rule package from XML source.
*
* @param reader
* @throws DroolsParserException
* @throws IOException
*/
public void addPackageFromXml(final Reader reader) throws DroolsParserException,
IOException {
this.resource = new ReaderResource(reader, ResourceType.XDRL);
final XmlPackageReader xmlReader = new XmlPackageReader(this.configuration.getSemanticModules());
xmlReader.getParser().setClassLoader(this.rootClassLoader);
try {
xmlReader.read(reader);
} catch (final SAXException e) {
throw new DroolsParserException(e.toString(),
e.getCause());
}
addPackage(xmlReader.getPackageDescr());
this.resource = null;
}
public void addPackageFromXml(final Resource resource) throws DroolsParserException,
IOException {
this.resource = resource;
addPackage(xmlToPackageDescr(resource));
this.resource = null;
}
PackageDescr xmlToPackageDescr(Resource resource) throws DroolsParserException,
IOException {
final XmlPackageReader xmlReader = new XmlPackageReader(this.configuration.getSemanticModules());
xmlReader.getParser().setClassLoader( this.rootClassLoader );
Reader reader = null;
try {
reader = resource.getReader();
xmlReader.read(reader);
} catch (final SAXException e) {
throw new DroolsParserException(e.toString(),
e.getCause());
} finally {
if (reader != null) {
reader.close();
}
}
return xmlReader.getPackageDescr();
}
/**
* Load a rule package from DRL source using the supplied DSL configuration.
*
* @param source
* The source of the rules.
* @param dsl
* The source of the domain specific language configuration.
* @throws DroolsParserException
* @throws IOException
*/
public void addPackageFromDrl(final Reader source,
final Reader dsl) throws DroolsParserException,
IOException {
this.resource = new ReaderResource(source, ResourceType.DSLR);
final DrlParser parser = new DrlParser(configuration.getLanguageLevel());
final PackageDescr pkg = parser.parse(source, dsl);
this.results.addAll( parser.getErrors() );
if (!parser.hasErrors()) {
addPackage(pkg);
}
this.resource = null;
}
public void addPackageFromDslr(final Resource resource) throws DroolsParserException,
IOException {
this.resource = resource;
addPackage(dslrToPackageDescr(resource));
this.resource = null;
}
PackageDescr dslrToPackageDescr(Resource resource) throws DroolsParserException,
IOException {
return dslrReaderToPackageDescr(resource, resource.getReader());
}
private PackageDescr dslrReaderToPackageDescr(Resource resource, Reader dslrReader) throws DroolsParserException {
boolean hasErrors;
PackageDescr pkg;
DrlParser parser = new DrlParser(configuration.getLanguageLevel());
DefaultExpander expander = getDslExpander();
try {
if (expander == null) {
expander = new DefaultExpander();
}
String str = expander.expand(dslrReader);
if (expander.hasErrors()) {
for (ExpanderException error : expander.getErrors()) {
error.setResource(resource);
addBuilderResult(error);
}
}
pkg = parser.parse(resource, str);
this.results.addAll(parser.getErrors());
hasErrors = parser.hasErrors();
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if (dslrReader != null) {
try {
dslrReader.close();
} catch (IOException e) {
}
}
}
return hasErrors ? null : pkg;
}
public void addDsl(Resource resource) throws IOException {
this.resource = resource;
DSLTokenizedMappingFile file = new DSLTokenizedMappingFile();
Reader reader = null;
try {
reader = resource.getReader();
if (!file.parseAndLoad(reader)) {
this.results.addAll(file.getErrors());
}
if (this.dslFiles == null) {
this.dslFiles = new ArrayList<DSLTokenizedMappingFile>();
}
this.dslFiles.add(file);
} finally {
if (reader != null) {
reader.close();
}
this.resource = null;
}
}
/**
* Add a ruleflow (.rfm) asset to this package.
*/
public void addRuleFlow(Reader processSource) {
addProcessFromXml(processSource);
}
public void addProcessFromXml(Resource resource) {
if (processBuilder == null) {
throw new RuntimeException("Unable to instantiate a process assembler", processBuilderCreationFailure);
}
if (ResourceType.DRF.equals(resource.getResourceType())) {
addBuilderResult(new DeprecatedResourceTypeWarning(resource, "RF"));
}
this.resource = resource;
try {
List<Process> processes = processBuilder.addProcessFromXml(resource);
List<BaseKnowledgeBuilderResultImpl> errors = processBuilder.getErrors();
if ( errors.isEmpty() ) {
if ( this.kBase != null && processes != null ) {
for (Process process : processes) {
if ( filterAccepts( ResourceChange.Type.PROCESS, process.getNamespace(), process.getId() ) ) {
this.kBase.addProcess(process);
}
}
}
} else {
this.results.addAll(errors);
errors.clear();
}
} catch (Exception e) {
if (e instanceof RuntimeException) {
throw (RuntimeException) e;
}
addBuilderResult(new ProcessLoadError(resource, "Unable to load process.", e));
}
this.results = getResults(this.results);
this.resource = null;
}
public void addProcessFromXml(Reader processSource) {
addProcessFromXml(new ReaderResource(processSource, ResourceType.DRF));
}
public void addKnowledgeResource(Resource resource,
ResourceType type,
ResourceConfiguration configuration) {
try {
((InternalResource) resource).setResourceType(type);
if (ResourceType.DRL.equals(type)) {
addPackageFromDrl(resource);
} else if (ResourceType.GDRL.equals(type)) {
addPackageFromDrl(resource);
} else if (ResourceType.RDRL.equals(type)) {
addPackageFromDrl(resource);
} else if (ResourceType.DESCR.equals(type)) {
addPackageFromDrl(resource);
} else if (ResourceType.DSLR.equals(type)) {
addPackageFromDslr(resource);
} else if (ResourceType.RDSLR.equals(type)) {
addPackageFromDslr(resource);
} else if (ResourceType.DSL.equals(type)) {
addDsl(resource);
} else if (ResourceType.XDRL.equals(type)) {
addPackageFromXml(resource);
} else if (ResourceType.DRF.equals(type)) {
addProcessFromXml(resource);
} else if (ResourceType.BPMN2.equals(type)) {
BPMN2ProcessFactory.configurePackageBuilder(this);
addProcessFromXml(resource);
} else if (ResourceType.DTABLE.equals(type)) {
addPackageFromDecisionTable(resource, configuration);
} else if (ResourceType.PKG.equals(type)) {
addPackageFromInputStream(resource);
} else if (ResourceType.CHANGE_SET.equals(type)) {
addPackageFromChangeSet(resource);
} else if (ResourceType.XSD.equals(type)) {
addPackageFromXSD(resource, (JaxbConfigurationImpl) configuration);
} else if (ResourceType.PMML.equals(type)) {
addPackageFromPMML(resource, type, configuration);
} else if (ResourceType.SCARD.equals(type)) {
addPackageFromScoreCard(resource, configuration);
} else if (ResourceType.TDRL.equals(type)) {
addPackageFromDrl(resource);
} else if (ResourceType.TEMPLATE.equals(type)) {
addPackageFromTemplate(resource);
} else if (ResourceType.GDST.equals(type)) {
addPackageFromGuidedDecisionTable(resource);
} else if (ResourceType.SCGD.equals(type)) {
addPackageFromGuidedScoreCard(resource);
} else {
addPackageForExternalType(resource, type, configuration);
}
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
void addPackageForExternalType(Resource resource,
ResourceType type,
ResourceConfiguration configuration) throws Exception {
KieAssemblers assemblers = ServiceRegistryImpl.getInstance().get(KieAssemblers.class);
KieAssemblerService assembler = assemblers.getAssemblers().get( type );
if (assembler != null) {
assembler.addResource( this,
resource,
type,
configuration );
} else {
throw new RuntimeException("Unknown resource type: " + type);
}
}
public void addPackageFromPMML(Resource resource,
ResourceType type,
ResourceConfiguration configuration) throws Exception {
PMMLCompiler compiler = getPMMLCompiler();
if (compiler != null) {
if (compiler.getResults().isEmpty()) {
this.resource = resource;
PackageDescr descr = pmmlModelToPackageDescr(compiler, resource);
if (descr != null) {
addPackage(descr);
}
this.resource = null;
} else {
this.results.addAll(compiler.getResults());
}
compiler.clearResults();
} else {
addPackageForExternalType(resource, type, configuration);
}
}
PackageDescr pmmlModelToPackageDescr(PMMLCompiler compiler,
Resource resource) throws DroolsParserException,
IOException {
String theory = compiler.compile(resource.getInputStream(),
rootClassLoader);
if (!compiler.getResults().isEmpty()) {
this.results.addAll(compiler.getResults());
return null;
}
return generatedDrlToPackageDescr( resource, theory );
}
void addPackageFromXSD(Resource resource,
JaxbConfigurationImpl configuration) throws IOException {
if (configuration != null) {
String[] classes = DroolsJaxbHelperProviderImpl.addXsdModel(resource,
this,
configuration.getXjcOpts(),
configuration.getSystemId());
for (String cls : classes) {
configuration.getClasses().add(cls);
}
}
}
void addPackageFromChangeSet(Resource resource) throws SAXException,
IOException {
XmlChangeSetReader reader = new XmlChangeSetReader(this.configuration.getSemanticModules());
if (resource instanceof ClassPathResource) {
reader.setClassLoader(((ClassPathResource) resource).getClassLoader(),
((ClassPathResource) resource).getClazz());
} else {
reader.setClassLoader(this.configuration.getClassLoader(),
null);
}
Reader resourceReader = null;
try {
resourceReader = resource.getReader();
ChangeSet changeSet = reader.read(resourceReader);
if (changeSet == null) {
// @TODO should log an error
}
for (Resource nestedResource : changeSet.getResourcesAdded()) {
InternalResource iNestedResourceResource = (InternalResource) nestedResource;
if (iNestedResourceResource.isDirectory()) {
for (Resource childResource : iNestedResourceResource.listResources()) {
if (((InternalResource) childResource).isDirectory()) {
continue; // ignore sub directories
}
((InternalResource) childResource).setResourceType(iNestedResourceResource.getResourceType());
addKnowledgeResource(childResource,
iNestedResourceResource.getResourceType(),
iNestedResourceResource.getConfiguration());
}
} else {
addKnowledgeResource(iNestedResourceResource,
iNestedResourceResource.getResourceType(),
iNestedResourceResource.getConfiguration());
}
}
} finally {
if (resourceReader != null) {
resourceReader.close();
}
}
}
void addPackageFromInputStream(final Resource resource) throws IOException,
ClassNotFoundException {
InputStream is = resource.getInputStream();
Object object = DroolsStreamUtils.streamIn(is, this.configuration.getClassLoader());
is.close();
if (object instanceof Collection) {
// KnowledgeBuilder API
@SuppressWarnings("unchecked")
Collection<KnowledgePackage> pkgs = (Collection<KnowledgePackage>) object;
for (KnowledgePackage kpkg : pkgs) {
overrideReSource((KnowledgePackageImpl) kpkg, resource);
addPackage((KnowledgePackageImpl) kpkg);
}
} else if (object instanceof KnowledgePackageImpl) {
// KnowledgeBuilder API
KnowledgePackageImpl kpkg = (KnowledgePackageImpl) object;
overrideReSource(kpkg, resource);
addPackage(kpkg);
} else {
results.add(new DroolsError(resource) {
@Override
public String getMessage() {
return "Unknown binary format trying to load resource " + resource.toString();
}
@Override
public int[] getLines() {
return new int[0];
}
});
}
}
private void overrideReSource(InternalKnowledgePackage pkg,
Resource res) {
for (org.kie.api.definition.rule.Rule r : pkg.getRules()) {
if (isSwappable(((RuleImpl)r).getResource(), res)) {
((RuleImpl)r).setResource(res);
}
}
for (TypeDeclaration d : pkg.getTypeDeclarations().values()) {
if (isSwappable(d.getResource(), res)) {
d.setResource(res);
}
}
for (Function f : pkg.getFunctions().values()) {
if (isSwappable(f.getResource(), res)) {
f.setResource(res);
}
}
for (org.kie.api.definition.process.Process p : pkg.getRuleFlows().values()) {
if (isSwappable(p.getResource(), res)) {
p.setResource(res);
}
}
}
private boolean isSwappable(Resource original,
Resource source) {
return original == null
|| (original instanceof ReaderResource && ((ReaderResource) original).getReader() == null);
}
/**
* This adds a package from a Descr/AST This will also trigger a compile, if
* there are any generated classes to compile of course.
*/
public void addPackage(final PackageDescr packageDescr) {
PackageRegistry pkgRegistry = initPackageRegistry(packageDescr);
if (pkgRegistry == null) {
return;
}
currentRulePackage = pkgRegistryMap.size() - 1;
// merge into existing package
mergePackage(pkgRegistry, packageDescr);
compileAllRules(packageDescr, pkgRegistry);
}
void compileAllRules(PackageDescr packageDescr, PackageRegistry pkgRegistry) {
pkgRegistry.setDialect( getPackageDialect( packageDescr ) );
validateUniqueRuleNames( packageDescr );
compileRules(packageDescr, pkgRegistry);
compileAll();
try {
reloadAll();
} catch (Exception e) {
addBuilderResult(new DialectError(null, "Unable to wire compiled classes, probably related to compilation failures:" + e.getMessage()));
}
updateResults();
// iterate and compile
if (!hasErrors() && this.kBase != null) {
for (RuleDescr ruleDescr : packageDescr.getRules()) {
if( filterAccepts( ResourceChange.Type.RULE, ruleDescr.getNamespace(), ruleDescr.getName() ) ) {
pkgRegistry = this.pkgRegistryMap.get(ruleDescr.getNamespace());
this.kBase.addRule(pkgRegistry.getPackage(), pkgRegistry.getPackage().getRule(ruleDescr.getName()));
}
}
}
}
void addBuilderResult(KnowledgeBuilderResult result) {
this.results.add(result);
}
PackageRegistry createPackageRegistry(PackageDescr packageDescr) {
PackageRegistry pkgRegistry = initPackageRegistry( packageDescr );
if (pkgRegistry == null) {
return null;
}
for (ImportDescr importDescr : packageDescr.getImports()) {
pkgRegistry.registerImport( importDescr.getTarget() );
}
return pkgRegistry;
}
private PackageRegistry initPackageRegistry(PackageDescr packageDescr) {
if (packageDescr == null) {
return null;
}
//Derive namespace
if (isEmpty(packageDescr.getNamespace())) {
packageDescr.setNamespace(this.configuration.getDefaultPackageName());
}
if (!checkNamespace(packageDescr.getNamespace())) {
return null;
}
initPackage(packageDescr);
PackageRegistry pkgRegistry = this.pkgRegistryMap.get( packageDescr.getNamespace() );
if (pkgRegistry == null) {
// initialise the package and namespace if it hasn't been used before
pkgRegistry = newPackage(packageDescr);
}
return pkgRegistry;
}
private void compileRules(PackageDescr packageDescr, PackageRegistry pkgRegistry) {
List<FunctionDescr> functions = packageDescr.getFunctions();
if (!functions.isEmpty()) {
for (FunctionDescr functionDescr : functions) {
if (isEmpty(functionDescr.getNamespace())) {
// make sure namespace is set on components
functionDescr.setNamespace(packageDescr.getNamespace());
}
// make sure functions are compiled using java dialect
functionDescr.setDialect("java");
preCompileAddFunction(functionDescr);
}
// iterate and compile
for (FunctionDescr functionDescr : functions) {
if (filterAccepts(ResourceChange.Type.FUNCTION, functionDescr.getNamespace(), functionDescr.getName()) ) {
// inherit the dialect from the package
addFunction(functionDescr);
}
}
// We need to compile all the functions now, so scripting
// languages like mvel can find them
compileAll();
for (FunctionDescr functionDescr : functions) {
if (filterAccepts(ResourceChange.Type.FUNCTION, functionDescr.getNamespace(), functionDescr.getName()) ) {
postCompileAddFunction(functionDescr);
}
}
}
// ensure that rules are ordered by dependency, so that dependent rules are built later
sortRulesByDependency(packageDescr);
// iterate and prepare RuleDescr
for (RuleDescr ruleDescr : packageDescr.getRules()) {
if (isEmpty(ruleDescr.getNamespace())) {
// make sure namespace is set on components
ruleDescr.setNamespace(packageDescr.getNamespace());
}
Map<String, AttributeDescr> pkgAttributes = packageAttributes.get(packageDescr.getNamespace());
inheritPackageAttributes(pkgAttributes,
ruleDescr);
if (isEmpty(ruleDescr.getDialect())) {
ruleDescr.addAttribute(new AttributeDescr("dialect",
pkgRegistry.getDialect()));
}
}
// Build up map of contexts and process all rules
Map<String, RuleBuildContext> ruleCxts = preProcessRules(packageDescr, pkgRegistry);
// iterate and compile
for (RuleDescr ruleDescr : packageDescr.getRules()) {
if (filterAccepts(ResourceChange.Type.RULE, ruleDescr.getNamespace(), ruleDescr.getName()) ) {
addRule(ruleCxts.get(ruleDescr.getName()));
}
}
}
boolean filterAccepts( ResourceChange.Type type, String namespace, String name ) {
return assetFilter == null || ! AssetFilter.Action.DO_NOTHING.equals( assetFilter.accept( type, namespace, name ) );
}
private boolean filterAcceptsRemoval( ResourceChange.Type type, String namespace, String name ) {
return assetFilter != null && AssetFilter.Action.REMOVE.equals( assetFilter.accept( type, namespace, name ) );
}
private Map<String, RuleBuildContext> preProcessRules(PackageDescr packageDescr, PackageRegistry pkgRegistry) {
Map<String, RuleBuildContext> ruleCxts = buildRuleBuilderContext(packageDescr.getRules());
InternalKnowledgePackage pkg = pkgRegistry.getPackage();
if (this.kBase != null) {
boolean needsRemoval = false;
// first, check if any rules no longer exist
for( org.kie.api.definition.rule.Rule rule : pkg.getRules() ) {
if (filterAcceptsRemoval( ResourceChange.Type.RULE, rule.getPackageName(), rule.getName() ) ) {
needsRemoval = true;
break;
}
}
if( !needsRemoval ) {
for (RuleDescr ruleDescr : packageDescr.getRules()) {
if (filterAccepts(ResourceChange.Type.RULE, ruleDescr.getNamespace(), ruleDescr.getName()) ) {
if (pkg.getRule(ruleDescr.getName()) != null) {
needsRemoval = true;
break;
}
}
}
}
if (needsRemoval) {
try {
this.kBase.lock();
for( org.kie.api.definition.rule.Rule rule : pkg.getRules() ) {
if (filterAcceptsRemoval( ResourceChange.Type.RULE, rule.getPackageName(), rule.getName() ) ) {
this.kBase.removeRule(pkg, pkg.getRule(rule.getName()));
pkg.removeRule(((RuleImpl)rule));
}
}
List<RuleImpl> rulesToBeRemoved = new ArrayList<RuleImpl>();
for (RuleDescr ruleDescr : packageDescr.getRules()) {
if (filterAccepts(ResourceChange.Type.RULE, ruleDescr.getNamespace(), ruleDescr.getName()) ) {
RuleImpl rule = (RuleImpl)pkg.getRule(ruleDescr.getName());
if (rule != null) {
rulesToBeRemoved.add(rule);
}
}
}
if (!rulesToBeRemoved.isEmpty()) {
kBase.removeRules( pkg, rulesToBeRemoved );
}
} finally {
this.kBase.unlock();
}
}
}
// Pre Process each rule, needed for Query signuture registration
for (RuleDescr ruleDescr : packageDescr.getRules()) {
if (filterAccepts(ResourceChange.Type.RULE, ruleDescr.getNamespace(), ruleDescr.getName()) ) {
RuleBuildContext ruleBuildContext = ruleCxts.get(ruleDescr.getName());
ruleBuilder.preProcess(ruleBuildContext);
pkg.addRule(ruleBuildContext.getRule());
}
}
return ruleCxts;
}
private void sortRulesByDependency(PackageDescr packageDescr) {
// Using a topological sorting algorithm
// see http://en.wikipedia.org/wiki/Topological_sorting
PackageRegistry pkgRegistry = this.pkgRegistryMap.get( packageDescr.getNamespace() );
InternalKnowledgePackage pkg = pkgRegistry.getPackage();
List<RuleDescr> roots = new LinkedList<RuleDescr>();
Map<String, List<RuleDescr>> children = new HashMap<String, List<RuleDescr>>();
LinkedHashMap<String, RuleDescr> sorted = new LinkedHashMap<String, RuleDescr>();
List<RuleDescr> queries = new ArrayList<RuleDescr>();
Set<String> compiledRules = new HashSet<String>();
for (RuleDescr ruleDescr : packageDescr.getRules()) {
if (ruleDescr.isQuery()) {
queries.add(ruleDescr);
} else if (!ruleDescr.hasParent()) {
roots.add(ruleDescr);
} else {
if (pkg.getRule(ruleDescr.getParentName()) != null) {
// The parent of this rule has been already compiled
compiledRules.add(ruleDescr.getParentName());
}
List<RuleDescr> childz = children.get(ruleDescr.getParentName());
if (childz == null) {
childz = new ArrayList<RuleDescr>();
children.put(ruleDescr.getParentName(), childz);
}
childz.add(ruleDescr);
}
}
if (children.isEmpty()) { // Sorting not necessary
if (!queries.isEmpty()) { // Build all queries first
packageDescr.getRules().removeAll(queries);
packageDescr.getRules().addAll(0, queries);
}
return;
}
for (String compiledRule : compiledRules) {
List<RuleDescr> childz = children.remove( compiledRule );
roots.addAll( childz );
}
while (!roots.isEmpty()) {
RuleDescr root = roots.remove(0);
sorted.put(root.getName(), root);
List<RuleDescr> childz = children.remove(root.getName());
if (childz != null) {
roots.addAll(childz);
}
}
reportHierarchyErrors(children, sorted);
packageDescr.getRules().clear();
packageDescr.getRules().addAll(queries);
for (RuleDescr descr : sorted.values() ) {
packageDescr.getRules().add( descr );
}
}
private void reportHierarchyErrors(Map<String, List<RuleDescr>> parents,
Map<String, RuleDescr> sorted) {
boolean circularDep = false;
for (List<RuleDescr> rds : parents.values()) {
for (RuleDescr ruleDescr : rds) {
if (parents.get(ruleDescr.getParentName()) != null
&& (sorted.containsKey(ruleDescr.getName()) || parents.containsKey(ruleDescr.getName()))) {
circularDep = true;
results.add( new RuleBuildError( new RuleImpl( ruleDescr.getName() ), ruleDescr, null,
"Circular dependency in rules hierarchy" ) );
break;
}
manageUnresolvedExtension( ruleDescr, sorted.values() );
}
if (circularDep) {
break;
}
}
}
private void manageUnresolvedExtension(RuleDescr ruleDescr,
Collection<RuleDescr> candidates) {
List<String> candidateRules = new LinkedList<String>();
for (RuleDescr r : candidates) {
if (StringUtils.stringSimilarity(ruleDescr.getParentName(), r.getName(), StringUtils.SIMILARITY_STRATS.DICE) >= 0.75) {
candidateRules.add(r.getName());
}
}
String msg = "Unresolved parent name " + ruleDescr.getParentName();
if (candidateRules.size() > 0) {
msg += " >> did you mean any of :" + candidateRules;
}
results.add(new RuleBuildError(new RuleImpl(ruleDescr.getName()), ruleDescr, msg,
"Unable to resolve parent rule, please check that both rules are in the same package"));
}
private void initPackage(PackageDescr packageDescr) {
//Gather all imports for all PackageDescrs for the current package and replicate into
//all PackageDescrs for the current package, thus maintaining a complete list of
//ImportDescrs for all PackageDescrs for the current package.
List<PackageDescr> packageDescrsForPackage = packages.get(packageDescr.getName());
if (packageDescrsForPackage == null) {
packageDescrsForPackage = new ArrayList<PackageDescr>();
packages.put(packageDescr.getName(),
packageDescrsForPackage);
}
packageDescrsForPackage.add(packageDescr);
Set<ImportDescr> imports = new HashSet<ImportDescr>();
for (PackageDescr pd : packageDescrsForPackage) {
imports.addAll(pd.getImports());
}
for (PackageDescr pd : packageDescrsForPackage) {
pd.getImports().clear();
pd.addAllImports(imports);
}
//Copy package level attributes for inclusion on individual rules
if (!packageDescr.getAttributes().isEmpty()) {
Map<String, AttributeDescr> pkgAttributes = packageAttributes.get(packageDescr.getNamespace());
if (pkgAttributes == null) {
pkgAttributes = new HashMap<String, AttributeDescr>();
this.packageAttributes.put(packageDescr.getNamespace(),
pkgAttributes);
}
for (AttributeDescr attr : packageDescr.getAttributes()) {
pkgAttributes.put(attr.getName(),
attr);
}
}
}
private String getPackageDialect(PackageDescr packageDescr) {
String dialectName = this.defaultDialect;
// see if this packageDescr overrides the current default dialect
for (AttributeDescr value : packageDescr.getAttributes()) {
if ("dialect".equals(value.getName())) {
dialectName = value.getValue();
break;
}
}
return dialectName;
}
// test
/**
* This checks to see if it should all be in the one namespace.
*/
private boolean checkNamespace(String newName) {
return configuration == null ||
!((!pkgRegistryMap.isEmpty()) && (!pkgRegistryMap.containsKey(newName))) ||
configuration.isAllowMultipleNamespaces();
}
public void updateResults() {
// some of the rules and functions may have been redefined
updateResults(this.results);
}
public void updateResults(List<KnowledgeBuilderResult> results) {
this.results = getResults(results);
}
public void compileAll() {
for (PackageRegistry pkgRegistry : this.pkgRegistryMap.values()) {
pkgRegistry.compileAll();
}
}
public void reloadAll() {
for (PackageRegistry pkgRegistry : this.pkgRegistryMap.values()) {
pkgRegistry.getDialectRuntimeRegistry().onBeforeExecute();
}
}
private List<KnowledgeBuilderResult> getResults(List<KnowledgeBuilderResult> results) {
for (PackageRegistry pkgRegistry : this.pkgRegistryMap.values()) {
results = pkgRegistry.getDialectCompiletimeRegistry().addResults(results);
}
return results;
}
public synchronized void addPackage(InternalKnowledgePackage newPkg) {
PackageRegistry pkgRegistry = this.pkgRegistryMap.get(newPkg.getName());
InternalKnowledgePackage pkg = null;
if (pkgRegistry != null) {
pkg = pkgRegistry.getPackage();
}
if (pkg == null) {
PackageDescr packageDescr = new PackageDescr(newPkg.getName());
pkgRegistry = newPackage(packageDescr);
mergePackage(this.pkgRegistryMap.get(packageDescr.getNamespace()), packageDescr);
pkg = pkgRegistry.getPackage();
}
// first merge anything related to classloader re-wiring
pkg.getDialectRuntimeRegistry().merge(newPkg.getDialectRuntimeRegistry(),
this.rootClassLoader);
if (newPkg.getFunctions() != null) {
for (Map.Entry<String, Function> entry : newPkg.getFunctions().entrySet()) {
if (pkg.getFunctions().containsKey(entry.getKey())) {
addBuilderResult(new DuplicateFunction(entry.getValue(),
this.configuration));
}
pkg.addFunction(entry.getValue());
}
}
pkg.getClassFieldAccessorStore().merge(newPkg.getClassFieldAccessorStore());
pkg.getDialectRuntimeRegistry().onBeforeExecute();
// we have to do this before the merging, as it does some classloader resolving
TypeDeclaration lastType = null;
try {
// Resolve the class for the type declaation
if (newPkg.getTypeDeclarations() != null) {
// add type declarations
for (TypeDeclaration type : newPkg.getTypeDeclarations().values()) {
lastType = type;
type.setTypeClass(this.rootClassLoader.loadClass(type.getTypeClassName()));
}
}
} catch (ClassNotFoundException e) {
throw new RuntimeException("unable to resolve Type Declaration class '" + lastType.getTypeName() + "'");
}
// now merge the new package into the existing one
mergePackage(pkg,
newPkg);
}
/**
* Merge a new package with an existing package. Most of the work is done by
* the concrete implementations, but this class does some work (including
* combining imports, compilation data, globals, and the actual Rule objects
* into the package).
*/
private void mergePackage(InternalKnowledgePackage pkg,
InternalKnowledgePackage newPkg) {
// Merge imports
final Map<String, ImportDeclaration> imports = pkg.getImports();
imports.putAll(newPkg.getImports());
String lastType = null;
try {
// merge globals
if (newPkg.getGlobals() != null && newPkg.getGlobals() != Collections.EMPTY_MAP) {
Map<String, String> globals = pkg.getGlobals();
// Add globals
for (final Map.Entry<String, String> entry : newPkg.getGlobals().entrySet()) {
final String identifier = entry.getKey();
final String type = entry.getValue();
lastType = type;
if (globals.containsKey(identifier) && !globals.get(identifier).equals(type)) {
throw new RuntimeException(pkg.getName() + " cannot be integrated");
} else {
pkg.addGlobal(identifier,
this.rootClassLoader.loadClass(type));
// this isn't a package merge, it's adding to the rulebase, but I've put it here for convenience
this.globals.put(identifier,
this.rootClassLoader.loadClass(type));
}
}
}
} catch (ClassNotFoundException e) {
throw new RuntimeException("Unable to resolve class '" + lastType + "'");
}
// merge the type declarations
if (newPkg.getTypeDeclarations() != null) {
// add type declarations
for (TypeDeclaration type : newPkg.getTypeDeclarations().values()) {
// @TODO should we allow overrides? only if the class is not in use.
if (!pkg.getTypeDeclarations().containsKey(type.getTypeName())) {
// add to package list of type declarations
pkg.addTypeDeclaration(type);
}
}
}
for (final org.kie.api.definition.rule.Rule newRule : newPkg.getRules()) {
pkg.addRule(((RuleImpl)newRule));
}
//Merge The Rule Flows
if (newPkg.getRuleFlows() != null) {
final Map flows = newPkg.getRuleFlows();
for (Object o : flows.values()) {
final Process flow = (Process) o;
pkg.addProcess(flow);
}
}
}
//
// private void validatePackageName(final PackageDescr packageDescr) {
// if ( (this.pkg == null || this.pkg.getName() == null || this.pkg.getName().equals( "" )) && (packageDescr.getName() == null || "".equals( packageDescr.getName() )) ) {
// throw new MissingPackageNameException( "Missing package name for rule package." );
// }
// if ( this.pkg != null && packageDescr.getName() != null && !"".equals( packageDescr.getName() ) && !this.pkg.getName().equals( packageDescr.getName() ) ) {
// throw new PackageMergeException( "Can't merge packages with different names. This package: " + this.pkg.getName() + " - New package: " + packageDescr.getName() );
// }
// return;
// }
private void validateUniqueRuleNames(final PackageDescr packageDescr) {
final Set<String> names = new HashSet<String>();
PackageRegistry packageRegistry = this.pkgRegistryMap.get(packageDescr.getNamespace());
InternalKnowledgePackage pkg = null;
if (packageRegistry != null) {
pkg = packageRegistry.getPackage();
}
for (final RuleDescr rule : packageDescr.getRules()) {
validateRule(packageDescr, rule);
final String name = rule.getName();
if (names.contains(name)) {
addBuilderResult(new ParserError(rule.getResource(),
"Duplicate rule name: " + name,
rule.getLine(),
rule.getColumn(),
packageDescr.getNamespace()));
}
if (pkg != null) {
RuleImpl duplicatedRule = pkg.getRule(name);
if (duplicatedRule != null) {
Resource resource = rule.getResource();
Resource duplicatedResource = duplicatedRule.getResource();
if (resource == null || duplicatedResource == null || duplicatedResource.getSourcePath() == null ||
duplicatedResource.getSourcePath().equals(resource.getSourcePath())) {
addBuilderResult(new DuplicateRule(rule,
packageDescr,
this.configuration));
} else {
addBuilderResult(new ParserError(rule.getResource(),
"Duplicate rule name: " + name,
rule.getLine(),
rule.getColumn(),
packageDescr.getNamespace()));
}
}
}
names.add(name);
}
}
private void validateRule(PackageDescr packageDescr,
RuleDescr rule) {
if (rule.hasErrors()) {
for (String error : rule.getErrors()) {
addBuilderResult(new ParserError(rule.getResource(),
error + " in rule " + rule.getName(),
rule.getLine(),
rule.getColumn(),
packageDescr.getNamespace()));
}
}
}
public PackageRegistry newPackage(final PackageDescr packageDescr) {
InternalKnowledgePackage pkg;
if (this.kBase == null || (pkg = this.kBase.getPackage(packageDescr.getName())) == null) {
// there is no rulebase or it does not define this package so define it
pkg = new KnowledgePackageImpl(packageDescr.getName());
pkg.setClassFieldAccessorCache(new ClassFieldAccessorCache(this.rootClassLoader));
// if there is a rulebase then add the package.
if (this.kBase != null) {
// Must lock here, otherwise the assumption about addPackage/getPackage behavior below might be violated
this.kBase.lock();
try {
this.kBase.addPackage(pkg);
pkg = this.kBase.getPackage(packageDescr.getName());
} finally {
this.kBase.unlock();
}
} else {
// the RuleBase will also initialise the
pkg.getDialectRuntimeRegistry().onAdd(this.rootClassLoader);
}
}
PackageRegistry pkgRegistry = new PackageRegistry(rootClassLoader, configuration, pkg);
// add default import for this namespace
pkgRegistry.addImport( new ImportDescr( packageDescr.getNamespace() + ".*" ) );
this.pkgRegistryMap.put( packageDescr.getName(), pkgRegistry );
return pkgRegistry;
}
void mergePackage(PackageRegistry pkgRegistry, PackageDescr packageDescr) {
for (final ImportDescr importDescr : packageDescr.getImports()) {
pkgRegistry.addImport(importDescr);
}
normalizeTypeDeclarationAnnotations( packageDescr );
processAccumulateFunctions(pkgRegistry, packageDescr);
processEntryPointDeclarations( pkgRegistry, packageDescr );
Map<String,AbstractClassTypeDeclarationDescr> unprocesseableDescrs = new HashMap<String,AbstractClassTypeDeclarationDescr>();
List<TypeDefinition> unresolvedTypes = new ArrayList<TypeDefinition>();
List<AbstractClassTypeDeclarationDescr> unsortedDescrs = new ArrayList<AbstractClassTypeDeclarationDescr>();
for ( TypeDeclarationDescr typeDeclarationDescr : packageDescr.getTypeDeclarations() ) {
unsortedDescrs.add( typeDeclarationDescr );
}
for ( EnumDeclarationDescr enumDeclarationDescr : packageDescr.getEnumDeclarations() ) {
unsortedDescrs.add( enumDeclarationDescr );
}
typeBuilder.processTypeDeclarations( Collections.singletonList( packageDescr ), unsortedDescrs, unresolvedTypes, unprocesseableDescrs );
for ( AbstractClassTypeDeclarationDescr descr : unprocesseableDescrs.values() ) {
this.addBuilderResult( new TypeDeclarationError( descr, "Unable to process type " + descr.getTypeName() ) );
}
processOtherDeclarations( pkgRegistry, packageDescr );
normalizeRuleAnnotations( packageDescr );
}
void processOtherDeclarations(PackageRegistry pkgRegistry, PackageDescr packageDescr) {
processAccumulateFunctions( pkgRegistry, packageDescr);
processWindowDeclarations(pkgRegistry, packageDescr);
processFunctions(pkgRegistry, packageDescr);
processGlobals(pkgRegistry, packageDescr);
// need to reinsert this to ensure that the package is the first/last one in the ordered map
// this feature is exploited by the knowledgeAgent
InternalKnowledgePackage current = getPackage();
this.pkgRegistryMap.remove(packageDescr.getName());
this.pkgRegistryMap.put(packageDescr.getName(), pkgRegistry);
if (current.getName().equals(packageDescr.getName())) {
currentRulePackage = pkgRegistryMap.size() - 1;
}
}
private void processGlobals(PackageRegistry pkgRegistry, PackageDescr packageDescr) {
InternalKnowledgePackage pkg = pkgRegistry.getPackage();
Set<String> existingGlobals = new HashSet<String>(pkg.getGlobals().keySet());
for (final GlobalDescr global : packageDescr.getGlobals()) {
final String identifier = global.getIdentifier();
existingGlobals.remove( identifier );
String className = global.getType();
// JBRULES-3039: can't handle type name with generic params
while (className.indexOf('<') >= 0) {
className = className.replaceAll("<[^<>]+?>", "");
}
try {
Class<?> clazz = pkgRegistry.getTypeResolver().resolveType(className);
if (clazz.isPrimitive()) {
addBuilderResult(new GlobalError(global, " Primitive types are not allowed in globals : " + className));
return;
}
pkg.addGlobal(identifier, clazz);
this.globals.put(identifier, clazz);
if (kBase != null) {
kBase.addGlobal(identifier, clazz);
}
} catch (final ClassNotFoundException e) {
addBuilderResult(new GlobalError(global, e.getMessage()));
e.printStackTrace();
}
}
for (String toBeRemoved : existingGlobals) {
if (filterAcceptsRemoval( ResourceChange.Type.GLOBAL, pkg.getName(), toBeRemoved )) {
pkg.removeGlobal( toBeRemoved );
if ( kBase != null ) {
kBase.removeGlobal( toBeRemoved );
}
}
}
}
private void processAccumulateFunctions(PackageRegistry pkgRegistry,
PackageDescr packageDescr) {
for (final AccumulateImportDescr aid : packageDescr.getAccumulateImports() ) {
AccumulateFunction af = loadAccumulateFunction(pkgRegistry,
aid.getFunctionName(),
aid.getTarget());
pkgRegistry.getPackage().addAccumulateFunction(aid.getFunctionName(), af);
}
}
@SuppressWarnings("unchecked")
private AccumulateFunction loadAccumulateFunction(PackageRegistry pkgRegistry,
String identifier,
String className) {
try {
Class< ? extends AccumulateFunction> clazz = (Class< ? extends AccumulateFunction>) pkgRegistry.getTypeResolver().resolveType(className);
return clazz.newInstance();
} catch ( ClassNotFoundException e ) {
throw new RuntimeException( "Error loading accumulate function for identifier " + identifier + ". Class " + className + " not found",
e );
} catch ( InstantiationException e ) {
throw new RuntimeException( "Error loading accumulate function for identifier " + identifier + ". Instantiation failed for class " + className,
e );
} catch ( IllegalAccessException e ) {
throw new RuntimeException( "Error loading accumulate function for identifier " + identifier + ". Illegal access to class " + className,
e );
}
}
private void processFunctions(PackageRegistry pkgRegistry,
PackageDescr packageDescr) {
for (FunctionDescr function : packageDescr.getFunctions()) {
Function existingFunc = pkgRegistry.getPackage().getFunctions().get(function.getName());
if (existingFunc != null && function.getNamespace().equals(existingFunc.getNamespace())) {
addBuilderResult(
new DuplicateFunction(function,
this.configuration));
}
}
for (final FunctionImportDescr functionImport : packageDescr.getFunctionImports()) {
String importEntry = functionImport.getTarget();
pkgRegistry.addStaticImport(functionImport);
pkgRegistry.getPackage().addStaticImport(importEntry);
}
}
public TypeDeclaration getAndRegisterTypeDeclaration(Class<?> cls, String packageName) {
return typeBuilder.getAndRegisterTypeDeclaration(cls, packageName);
}
void processEntryPointDeclarations(PackageRegistry pkgRegistry,
PackageDescr packageDescr) {
for (EntryPointDeclarationDescr epDescr : packageDescr.getEntryPointDeclarations()) {
pkgRegistry.getPackage().addEntryPointId(epDescr.getEntryPointId());
}
}
private void processWindowDeclarations(PackageRegistry pkgRegistry,
PackageDescr packageDescr) {
for (WindowDeclarationDescr wd : packageDescr.getWindowDeclarations()) {
WindowDeclaration window = new WindowDeclaration(wd.getName(), packageDescr.getName());
// TODO: process annotations
// process pattern
InternalKnowledgePackage pkg = pkgRegistry.getPackage();
DialectCompiletimeRegistry ctr = pkgRegistry.getDialectCompiletimeRegistry();
RuleDescr dummy = new RuleDescr(wd.getName() + " Window Declaration");
dummy.setResource(packageDescr.getResource());
dummy.addAttribute(new AttributeDescr("dialect", "java"));
RuleBuildContext context = new RuleBuildContext(this,
dummy,
ctr,
pkg,
ctr.getDialect(pkgRegistry.getDialect()));
final RuleConditionBuilder builder = (RuleConditionBuilder) context.getDialect().getBuilder(wd.getPattern().getClass());
if (builder != null) {
final Pattern pattern = (Pattern) builder.build(context,
wd.getPattern(),
null);
window.setPattern(pattern);
} else {
throw new RuntimeException(
"BUG: assembler not found for descriptor class " + wd.getPattern().getClass());
}
if (!context.getErrors().isEmpty()) {
for (DroolsError error : context.getErrors()) {
addBuilderResult(error);
}
} else {
pkgRegistry.getPackage().addWindowDeclaration(window);
}
}
}
private void addFunction(final FunctionDescr functionDescr) {
PackageRegistry pkgRegistry = this.pkgRegistryMap.get(functionDescr.getNamespace());
Dialect dialect = pkgRegistry.getDialectCompiletimeRegistry().getDialect(functionDescr.getDialect());
dialect.addFunction(functionDescr,
pkgRegistry.getTypeResolver(),
this.resource);
}
private void preCompileAddFunction(final FunctionDescr functionDescr) {
PackageRegistry pkgRegistry = this.pkgRegistryMap.get(functionDescr.getNamespace());
Dialect dialect = pkgRegistry.getDialectCompiletimeRegistry().getDialect(functionDescr.getDialect());
dialect.preCompileAddFunction(functionDescr,
pkgRegistry.getTypeResolver());
}
private void postCompileAddFunction(final FunctionDescr functionDescr) {
PackageRegistry pkgRegistry = this.pkgRegistryMap.get(functionDescr.getNamespace());
Dialect dialect = pkgRegistry.getDialectCompiletimeRegistry().getDialect(functionDescr.getDialect());
dialect.postCompileAddFunction(functionDescr, pkgRegistry.getTypeResolver());
if (rootClassLoader instanceof ProjectClassLoader) {
String functionClassName = functionDescr.getClassName();
JavaDialectRuntimeData runtime = ((JavaDialectRuntimeData) pkgRegistry.getDialectRuntimeRegistry().getDialectData( "java" ));
try {
registerFunctionClassAndInnerClasses( functionClassName, runtime,
(name, bytes) -> ((ProjectClassLoader)rootClassLoader).storeClass( name, bytes ));
} catch (ClassNotFoundException e) {
throw new RuntimeException( e );
}
}
}
private Map<String, RuleBuildContext> buildRuleBuilderContext(List<RuleDescr> rules) {
Map<String, RuleBuildContext> map = new HashMap<String, RuleBuildContext>();
for (RuleDescr ruleDescr : rules) {
if (ruleDescr.getResource() == null) {
ruleDescr.setResource(resource);
}
PackageRegistry pkgRegistry = this.pkgRegistryMap.get(ruleDescr.getNamespace());
InternalKnowledgePackage pkg = pkgRegistry.getPackage();
DialectCompiletimeRegistry ctr = pkgRegistry.getDialectCompiletimeRegistry();
RuleBuildContext context = new RuleBuildContext(this,
ruleDescr,
ctr,
pkg,
ctr.getDialect(pkgRegistry.getDialect()));
map.put(ruleDescr.getName(), context);
}
return map;
}
private void addRule(RuleBuildContext context) {
final RuleDescr ruleDescr = context.getRuleDescr();
InternalKnowledgePackage pkg = context.getPkg();
ruleBuilder.build(context);
this.results.addAll(context.getErrors());
this.results.addAll(context.getWarnings());
context.getRule().setResource(ruleDescr.getResource());
context.getDialect().addRule(context);
if (context.needsStreamMode()) {
pkg.setNeedStreamMode();
}
}
/**
* @return The compiled package. The package may contain errors, which you
* can report on by calling getErrors or printErrors. If you try to
* add an invalid package (or rule) to a RuleBase, you will get a
* runtime exception.
*
* Compiled packages are serializable.
*/
public InternalKnowledgePackage getPackage() {
PackageRegistry pkgRegistry = null;
if (!this.pkgRegistryMap.isEmpty()) {
pkgRegistry = (PackageRegistry) this.pkgRegistryMap.values().toArray()[currentRulePackage];
}
InternalKnowledgePackage pkg = null;
if (pkgRegistry != null) {
pkg = pkgRegistry.getPackage();
}
if (hasErrors() && pkg != null) {
pkg.setError(getErrors().toString());
}
return pkg;
}
public InternalKnowledgePackage[] getPackages() {
InternalKnowledgePackage[] pkgs = new InternalKnowledgePackage[this.pkgRegistryMap.size()];
String errors = null;
if (!getErrors().isEmpty()) {
errors = getErrors().toString();
}
int i = 0;
for (PackageRegistry pkgRegistry : this.pkgRegistryMap.values()) {
InternalKnowledgePackage pkg = pkgRegistry.getPackage();
pkg.getDialectRuntimeRegistry().onBeforeExecute();
if (errors != null) {
pkg.setError(errors);
}
pkgs[i++] = pkg;
}
return pkgs;
}
/**
* Return the PackageBuilderConfiguration for this PackageBuilder session
*
* @return The PackageBuilderConfiguration
*/
public KnowledgeBuilderConfigurationImpl getBuilderConfiguration() {
return this.configuration;
}
public PackageRegistry getPackageRegistry(String name) {
return this.pkgRegistryMap.get(name);
}
public Map<String, PackageRegistry> getPackageRegistry() {
return this.pkgRegistryMap;
}
public Collection<String> getPackageNames() {
return pkgRegistryMap.keySet();
}
public List<PackageDescr> getPackageDescrs(String packageName) {
return packages.get(packageName);
}
/**
* Returns an expander for DSLs (only if there is a DSL configured for this
* package).
*/
public DefaultExpander getDslExpander() {
DefaultExpander expander = new DefaultExpander();
if (this.dslFiles == null || this.dslFiles.isEmpty()) {
return null;
}
for (DSLMappingFile file : this.dslFiles) {
expander.addDSLMapping(file.getMapping());
}
return expander;
}
public Map<String, Class<?>> getGlobals() {
return this.globals;
}
/**
* This will return true if there were errors in the package building and
* compiling phase
*/
public boolean hasErrors() {
return !getErrorList().isEmpty();
}
public KnowledgeBuilderResults getResults(ResultSeverity... problemTypes) {
List<KnowledgeBuilderResult> problems = getResultList(problemTypes);
return new PackageBuilderResults(problems.toArray(new BaseKnowledgeBuilderResultImpl[problems.size()]));
}
private List<KnowledgeBuilderResult> getResultList(ResultSeverity... severities) {
List<ResultSeverity> typesToFetch = Arrays.asList(severities);
ArrayList<KnowledgeBuilderResult> problems = new ArrayList<KnowledgeBuilderResult>();
for (KnowledgeBuilderResult problem : results) {
if (typesToFetch.contains(problem.getSeverity())) {
problems.add(problem);
}
}
return problems;
}
public boolean hasResults(ResultSeverity... problemTypes) {
return !getResultList(problemTypes).isEmpty();
}
private List<DroolsError> getErrorList() {
List<DroolsError> errors = new ArrayList<DroolsError>();
for (KnowledgeBuilderResult problem : results) {
if (problem.getSeverity() == ResultSeverity.ERROR) {
if (problem instanceof ConfigurableSeverityResult) {
errors.add(new DroolsErrorWrapper(problem));
} else {
errors.add((DroolsError) problem);
}
}
}
return errors;
}
public boolean hasWarnings() {
return !getWarnings().isEmpty();
}
public boolean hasInfo() {
return !getInfoList().isEmpty();
}
public List<DroolsWarning> getWarnings() {
List<DroolsWarning> warnings = new ArrayList<DroolsWarning>();
for (KnowledgeBuilderResult problem : results) {
if (problem.getSeverity() == ResultSeverity.WARNING) {
if (problem instanceof ConfigurableSeverityResult) {
warnings.add(new DroolsWarningWrapper(problem));
} else {
warnings.add((DroolsWarning) problem);
}
}
}
return warnings;
}
private List<KnowledgeBuilderResult> getInfoList() {
return getResultList(ResultSeverity.INFO);
}
/**
* @return A list of Error objects that resulted from building and compiling
* the package.
*/
public PackageBuilderErrors getErrors() {
List<DroolsError> errors = getErrorList();
return new PackageBuilderErrors(errors.toArray(new DroolsError[errors.size()]));
}
/**
* Reset the error list. This is useful when incrementally building
* packages. Care should be used when building this, if you clear this when
* there were errors on items that a rule depends on (eg functions), then
* you will get spurious errors which will not be that helpful.
*/
protected void resetErrors() {
resetProblemType(ResultSeverity.ERROR);
}
protected void resetWarnings() {
resetProblemType(ResultSeverity.WARNING);
}
private void resetProblemType(ResultSeverity problemType) {
List<KnowledgeBuilderResult> toBeDeleted = new ArrayList<KnowledgeBuilderResult>();
for (KnowledgeBuilderResult problem : results) {
if (problemType != null && problemType.equals(problem.getSeverity())) {
toBeDeleted.add(problem);
}
}
this.results.removeAll(toBeDeleted);
}
protected void resetProblems() {
this.results.clear();
if (this.processBuilder != null) {
this.processBuilder.getErrors().clear();
}
}
public String getDefaultDialect() {
return this.defaultDialect;
}
public static class MissingPackageNameException extends IllegalArgumentException {
private static final long serialVersionUID = 510l;
public MissingPackageNameException(final String message) {
super(message);
}
}
public static class PackageMergeException extends IllegalArgumentException {
private static final long serialVersionUID = 400L;
public PackageMergeException(final String message) {
super(message);
}
}
public ClassLoader getRootClassLoader() {
return this.rootClassLoader;
}
//Entity rules inherit package attributes
private void inheritPackageAttributes(Map<String, AttributeDescr> pkgAttributes,
RuleDescr ruleDescr) {
if (pkgAttributes == null) {
return;
}
for (AttributeDescr attrDescr : pkgAttributes.values()) {
String name = attrDescr.getName();
AttributeDescr ruleAttrDescr = ruleDescr.getAttributes().get(name);
if (ruleAttrDescr == null) {
ruleDescr.getAttributes().put(name,
attrDescr);
}
}
}
private ChangeSet parseChangeSet(Resource resource) throws IOException, SAXException {
XmlChangeSetReader reader = new XmlChangeSetReader(this.configuration.getSemanticModules());
if (resource instanceof ClassPathResource) {
reader.setClassLoader(((ClassPathResource) resource).getClassLoader(),
((ClassPathResource) resource).getClazz());
} else {
reader.setClassLoader(this.configuration.getClassLoader(),
null);
}
Reader resourceReader = null;
try {
resourceReader = resource.getReader();
return reader.read(resourceReader);
} finally {
if (resourceReader != null) {
resourceReader.close();
}
}
}
public void registerBuildResource(final Resource resource, ResourceType type) {
InternalResource ires = (InternalResource) resource;
if (ires.getResourceType() == null) {
ires.setResourceType(type);
} else if (ires.getResourceType() != type) {
addBuilderResult(new ResourceTypeDeclarationWarning(resource, ires.getResourceType(), type));
}
if (ResourceType.CHANGE_SET == type) {
try {
ChangeSet changeSet = parseChangeSet(resource);
List<Resource> resources = new ArrayList<Resource>();
resources.add(resource);
for (Resource addedRes : changeSet.getResourcesAdded()) {
resources.add(addedRes);
}
for (Resource modifiedRes : changeSet.getResourcesModified()) {
resources.add(modifiedRes);
}
for (Resource removedRes : changeSet.getResourcesRemoved()) {
resources.add(removedRes);
}
buildResources.push(resources);
} catch (Exception e) {
results.add(new DroolsError() {
public String getMessage() {
return "Unable to register changeset resource " + resource;
}
public int[] getLines() {
return new int[0];
}
});
}
} else {
buildResources.push( Collections.singletonList( resource ) );
}
}
public void registerBuildResources(List<Resource> resources) {
buildResources.push(resources);
}
public void undo() {
if (buildResources.isEmpty()) {
return;
}
for (Resource resource : buildResources.pop()) {
removeObjectsGeneratedFromResource(resource);
}
}
public boolean removeObjectsGeneratedFromResource(Resource resource) {
boolean modified = false;
if (pkgRegistryMap != null) {
for (PackageRegistry packageRegistry : pkgRegistryMap.values()) {
modified = packageRegistry.removeObjectsGeneratedFromResource(resource) || modified;
}
}
if (results != null) {
Iterator<KnowledgeBuilderResult> i = results.iterator();
while (i.hasNext()) {
if (resource.equals(i.next().getResource())) {
i.remove();
}
}
}
if (processBuilder != null && processBuilder.getErrors() != null) {
Iterator<? extends KnowledgeBuilderResult> i = processBuilder.getErrors().iterator();
while (i.hasNext()) {
if (resource.equals(i.next().getResource())) {
i.remove();
}
}
}
if (results.size() == 0) {
// TODO Error attribution might be bugged
for (PackageRegistry packageRegistry : pkgRegistryMap.values()) {
packageRegistry.getPackage().resetErrors();
}
}
typeBuilder.removeTypesGeneratedFromResource(resource);
for (List<PackageDescr> pkgDescrs : packages.values()) {
for (PackageDescr pkgDescr : pkgDescrs) {
pkgDescr.removeObjectsGeneratedFromResource(resource);
}
}
if (kBase != null) {
modified = kBase.removeObjectsGeneratedFromResource(resource) || modified;
}
return modified;
}
public void rewireAllClassObjectTypes() {
if (kBase != null) {
for (InternalKnowledgePackage pkg : kBase.getPackagesMap().values()) {
pkg.getDialectRuntimeRegistry().getDialectData("java").setDirty(true);
pkg.getClassFieldAccessorStore().wire();
}
}
}
public interface AssetFilter {
enum Action {
DO_NOTHING, ADD, REMOVE, UPDATE
}
Action accept(ResourceChange.Type type, String pkgName, String assetName);
}
AssetFilter getAssetFilter() {
return assetFilter;
}
public void setAssetFilter(AssetFilter assetFilter) {
this.assetFilter = assetFilter;
}
public void add(Resource resource, ResourceType type) {
ResourceConfiguration resourceConfiguration = resource instanceof BaseResource ? resource.getConfiguration() : null;
add(resource, type, resourceConfiguration) ;
}
public CompositeKnowledgeBuilder batch() {
return new CompositeKnowledgeBuilderImpl(this);
}
public void add(Resource resource,
ResourceType type,
ResourceConfiguration configuration) {
registerBuildResource(resource, type);
addKnowledgeResource(resource, type, configuration);
}
public Collection<KnowledgePackage> getKnowledgePackages() {
if ( hasErrors() ) {
return new ArrayList<KnowledgePackage>( 0 );
}
InternalKnowledgePackage[] pkgs = getPackages();
List<KnowledgePackage> list = new ArrayList<KnowledgePackage>( pkgs.length );
Collections.addAll(list, pkgs);
return list;
}
public KnowledgeBase newKnowledgeBase() {
return newKnowledgeBase(null);
}
public KnowledgeBase newKnowledgeBase(KieBaseConfiguration conf) {
KnowledgeBuilderErrors errors = getErrors();
if (errors.size() > 0) {
for (KnowledgeBuilderError error: errors) {
logger.error(error.toString());
}
throw new IllegalArgumentException("Could not parse knowledge.");
}
KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(conf);
kbase.addKnowledgePackages(getKnowledgePackages());
return kbase;
}
public TypeDeclaration getTypeDeclaration(Class<?> cls) {
return typeBuilder.getTypeDeclaration(cls);
}
public void normalizeTypeDeclarationAnnotations(PackageDescr packageDescr) {
TypeResolver typeResolver = pkgRegistryMap.get(packageDescr.getName()).getTypeResolver();
boolean isStrict = configuration.getLanguageLevel().useJavaAnnotations();
for (TypeDeclarationDescr typeDeclarationDescr : packageDescr.getTypeDeclarations()) {
normalizeAnnotations(typeDeclarationDescr, typeResolver, isStrict);
for (TypeFieldDescr typeFieldDescr : typeDeclarationDescr.getFields().values()) {
normalizeAnnotations(typeFieldDescr, typeResolver, isStrict);
}
}
for (EnumDeclarationDescr enumDeclarationDescr : packageDescr.getEnumDeclarations()) {
normalizeAnnotations(enumDeclarationDescr, typeResolver, isStrict);
for (TypeFieldDescr typeFieldDescr : enumDeclarationDescr.getFields().values()) {
normalizeAnnotations(typeFieldDescr, typeResolver, isStrict);
}
}
}
public void normalizeRuleAnnotations(PackageDescr packageDescr) {
TypeResolver typeResolver = pkgRegistryMap.get(packageDescr.getName()).getTypeResolver();
boolean isStrict = configuration.getLanguageLevel().useJavaAnnotations();
for ( RuleDescr ruleDescr : packageDescr.getRules() ) {
normalizeAnnotations( ruleDescr, typeResolver, isStrict );
traverseAnnotations( ruleDescr.getLhs(), typeResolver, isStrict );
}
}
private void traverseAnnotations( BaseDescr descr, TypeResolver typeResolver, boolean isStrict ) {
if ( descr instanceof AnnotatedBaseDescr ) {
normalizeAnnotations( (AnnotatedBaseDescr) descr, typeResolver, isStrict );
}
if ( descr instanceof ConditionalElementDescr ) {
for ( BaseDescr baseDescr : ( (ConditionalElementDescr) descr ).getDescrs() ) {
traverseAnnotations( baseDescr, typeResolver, isStrict );
}
}
if ( descr instanceof PatternDescr && ( (PatternDescr) descr ).getSource() != null ) {
traverseAnnotations( ( (PatternDescr) descr ).getSource(), typeResolver, isStrict );
}
if ( descr instanceof PatternDestinationDescr ) {
traverseAnnotations( ( (PatternDestinationDescr) descr ).getInputPattern(), typeResolver, isStrict );
}
}
private void normalizeAnnotations(AnnotatedBaseDescr annotationsContainer, TypeResolver typeResolver, boolean isStrict) {
for (AnnotationDescr annotationDescr : annotationsContainer.getAnnotations()) {
annotationDescr.setResource(annotationsContainer.getResource());
annotationDescr.setStrict(isStrict);
if (annotationDescr.isDuplicated()) {
addBuilderResult(new AnnotationDeclarationError(annotationDescr,
"Duplicated annotation: " + annotationDescr.getName()));
}
if (isStrict) {
normalizeStrictAnnotation(typeResolver, annotationDescr);
} else {
normalizeAnnotation(typeResolver, annotationDescr);
}
}
annotationsContainer.indexByFQN(isStrict);
}
private AnnotationDescr normalizeAnnotation(TypeResolver typeResolver, AnnotationDescr annotationDescr) {
Class<?> annotationClass = null;
try {
annotationClass = typeResolver.resolveType(annotationDescr.getName(), TypeResolver.ONLY_ANNOTATION_CLASS_FILTER);
} catch (ClassNotFoundException e) {
String className = normalizeAnnotationNonStrictName(annotationDescr.getName());
try {
annotationClass = typeResolver.resolveType(className, TypeResolver.ONLY_ANNOTATION_CLASS_FILTER);
} catch (ClassNotFoundException e1) {
// non-strict annotation, ignore error
} catch (NoClassDefFoundError e1) {
// non-strict annotation, ignore error
}
} catch (NoClassDefFoundError e) {
String className = normalizeAnnotationNonStrictName(annotationDescr.getName());
try {
annotationClass = typeResolver.resolveType(className, TypeResolver.ONLY_ANNOTATION_CLASS_FILTER);
} catch (ClassNotFoundException e1) {
// non-strict annotation, ignore error
} catch (NoClassDefFoundError e1) {
// non-strict annotation, ignore error
}
}
if (annotationClass != null) {
annotationDescr.setFullyQualifiedName(annotationClass.getCanonicalName());
for ( String key : annotationDescr.getValueMap().keySet() ) {
try {
Method m = annotationClass.getMethod( key );
Object val = annotationDescr.getValue( key );
if ( val instanceof Object[] && ! m.getReturnType().isArray() ) {
addBuilderResult( new AnnotationDeclarationError( annotationDescr,
"Wrong cardinality on property " + key ) );
return annotationDescr;
}
if ( m.getReturnType().isArray() && ! (val instanceof Object[]) ) {
val = new Object[] { val };
annotationDescr.setKeyValue( key, val );
}
if ( m.getReturnType().isArray() ) {
int n = Array.getLength(val);
for ( int j = 0; j < n; j++ ) {
if ( Class.class.equals( m.getReturnType().getComponentType() ) ) {
String className = Array.get( val, j ).toString().replace( ".class", "" );
Array.set( val, j, typeResolver.resolveType( className ).getName() + ".class" );
} else if ( m.getReturnType().getComponentType().isAnnotation() ) {
Array.set( val, j, normalizeAnnotation( typeResolver,
(AnnotationDescr) Array.get( val, j ) ) );
}
}
} else {
if ( Class.class.equals( m.getReturnType() ) ) {
String className = annotationDescr.getValueAsString(key).replace( ".class", "" );
annotationDescr.setKeyValue( key, typeResolver.resolveType( className ).getName() + ".class" );
} else if ( m.getReturnType().isAnnotation() ) {
annotationDescr.setKeyValue( key,
normalizeAnnotation( typeResolver,
(AnnotationDescr) annotationDescr.getValue( key ) ) );
}
}
} catch ( NoSuchMethodException e ) {
addBuilderResult( new AnnotationDeclarationError( annotationDescr,
"Unknown annotation property " + key ) );
} catch ( ClassNotFoundException e ) {
addBuilderResult( new AnnotationDeclarationError( annotationDescr,
"Unknown class " + annotationDescr.getValue( key ) + " used in property " + key +
" of annotation " + annotationDescr.getName() ) );
} catch ( NoClassDefFoundError e ) {
addBuilderResult( new AnnotationDeclarationError( annotationDescr,
"Unknown class " + annotationDescr.getValue( key ) + " used in property " + key +
" of annotation " + annotationDescr.getName() ) );
}
}
}
return annotationDescr;
}
private String normalizeAnnotationNonStrictName(String name) {
if ("typesafe".equalsIgnoreCase(name)) {
return "TypeSafe";
}
return ucFirst(name);
}
private void normalizeStrictAnnotation(TypeResolver typeResolver, AnnotationDescr annotationDescr) {
try {
Class<?> annotationClass = typeResolver.resolveType(annotationDescr.getName(), TypeResolver.ONLY_ANNOTATION_CLASS_FILTER);
annotationDescr.setFullyQualifiedName(annotationClass.getCanonicalName());
} catch (ClassNotFoundException e) {
addBuilderResult(new AnnotationDeclarationError(annotationDescr,
"Unknown annotation: " + annotationDescr.getName()));
} catch (NoClassDefFoundError e) {
addBuilderResult(new AnnotationDeclarationError(annotationDescr,
"Unknown annotation: " + annotationDescr.getName()));
}
}
} | Allow external Assemblers to add KnowledgeBuilderResult in KnowledgeBuilder (#1083)
| drools-compiler/src/main/java/org/drools/compiler/builder/impl/KnowledgeBuilderImpl.java | Allow external Assemblers to add KnowledgeBuilderResult in KnowledgeBuilder (#1083) | <ide><path>rools-compiler/src/main/java/org/drools/compiler/builder/impl/KnowledgeBuilderImpl.java
<ide> }
<ide> }
<ide>
<del> void addBuilderResult(KnowledgeBuilderResult result) {
<add> public void addBuilderResult(KnowledgeBuilderResult result) {
<ide> this.results.add(result);
<ide> }
<ide> |
|
Java | apache-2.0 | 44f4e5884e3ee6f1a07cb3dd4e9c2d322a01c57d | 0 | markii96/GuardianesDeLaLuz | package com.mygdx.game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.Preferences;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.audio.Music;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.utils.viewport.StretchViewport;
import com.badlogic.gdx.utils.viewport.Viewport;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
public class PantallaJuego implements Screen, InputProcessor {
private final Juego juego;
private OrthographicCamera camara;
private Viewport vista;
private Texture texturaFondo;
private Texture texturaHeroe1;
private Texture texturaHeroe2;
private Texture texturaHeroe3;
private Music music;
private float[] posicion = new float[2];
private Texture texturaPerdiste;
Preferences validacion = Gdx.app.getPreferences("Validacion");
private SpriteBatch batch;
private Texto texto; //texto para mostrar el cd de las habilidades
private Fondo fondo;
private ArrayList<seudoSprite> ordenDibujar;
private Estado estado = Estado.JUGANDO;
private Nivel nivel;
private String[] heroesId = new String[3];
private Enemigo[] enemigos;
private float timerHeroes =0;
private float timerEnemigos =0;
float xInicial,yInicial;
private int cont =0;
private int limiteEnemigos =2;
private int enemigosEliminados =0;
private int heroesEliminados =0;
private Sprite btnAtras;
private Sprite btnPausa;
private Sprite btnSalir;
//habilidades
private Heroe heroeSel= null;
private ArrayList<Sprite> botonesHabilidades = new ArrayList<Sprite>();
private ArrayList<Habilidad> habilidadesUsadas = new ArrayList<Habilidad>();
private ArrayList<Heroe> heroeHabilidad = new ArrayList<Heroe>();
public PantallaJuego(Juego juego,String nivelId) {
this.juego = juego;
heroesId[0]="1";
heroesId[1]="2";
heroesId[2]="3";
this.nivel = new Nivel(nivelId,heroesId);
this.enemigos = new Enemigo[this.nivel.getCantEnemigos()];
int range = (nivel.getEnemigos().length-1) + 1;
int range2 = (401);
int ran = (int)(Math.random() * range);
int ran2 = (int)(Math.random() * range2);
int ran3 = (int)(Math.random() * nivel.getHeroes().size()+1);
Object objetivo = null;
switch(ran3){
case(0):
objetivo = nivel.getCristal();
break;
default:
objetivo = nivel.getHeroes().get(ran3-1);
break;
}
//Gdx.app.log("Create",ran3+"");
this.enemigos[0] = new Enemigo(nivel.getEnemigos()[ran], 900, ran2, objetivo);
cont+=1;
ordenDibujar = new ArrayList<seudoSprite>();
}
private int regresaEnemigos() {
int cont=0;
try {
for (int i = 0; i < enemigos.length; i++) {
if (enemigos[i]!= null)
cont+=1;
}
}
catch (Exception error){
return cont;
}
return cont;
}
@Override
public void show() {
inicializarCamara();
cargarTexturas();
crearEscena();
Gdx.input.setInputProcessor(this);
texto =new Texto();
music = Gdx.audio.newMusic(Gdx.files.internal("The_Trip_to_the_Market.mp3"));
music.setLooping(true);
music.play();
Gdx.input.setCatchBackKey(true);
if(validacion.getString("2").equals("0")) {
music.pause();
}
if(validacion.getString("2").equals("1")) {
music.play();
}
}
private void inicializarCamara() {
camara = new OrthographicCamera(1280,720);
camara.position.set(1280/2,720/2,0);
camara.update();
vista = new StretchViewport(1280,720,camara);
}
private void cargarTexturas() {
texturaFondo = this.nivel.getTextura();
texturaHeroe1 = this.nivel.getHeroes().get(0).getTextura();
texturaHeroe2 = this.nivel.getHeroes().get(1).getTextura();
texturaHeroe3 = this.nivel.getHeroes().get(2).getTextura();
btnPausa = new Sprite(new Texture("pausa.png"));
btnPausa.setX(1020);
btnPausa.setY(544);
btnSalir = new Sprite(new Texture("exit.png"));
btnSalir.setX(1280/2);
btnSalir.setY(800/2);
}
private void crearEscena() {
batch = new SpriteBatch();
fondo = new Fondo(texturaFondo);
}
@Override
public void render(float delta) {
Gdx.gl.glClearColor(1,1,1,1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
int range = (nivel.getEnemigos().length-1) + 1;
int range2 = (401);
if(estado == Estado.JUGANDO) {
int ran = (int) (Math.random() * range);
int ran2 = (int) (Math.random() * range2);
int bandera = 0;
if (enemigosEliminados >= nivel.getCantEnemigos()) {
estado = Estado.GANAR;
}
if (heroesEliminados >= 3 || nivel.getCristal().getVitalidad()<=0) {
estado = Estado.PERDER;
}
timerHeroes += Gdx.graphics.getDeltaTime();
timerEnemigos += Gdx.graphics.getDeltaTime();
for (int i = 0; i < cont; i++) {
for (int j = 0; j < nivel.getHeroes().size(); j++) {
if (nivel.getHeroes().get(j).contiene(enemigos[i].getSprite().getBoundingRectangle()) || enemigos[i].contiene(nivel.getHeroes().get(j).getSprite().getBoundingRectangle())) {
if (nivel.getHeroes().get(j).getEstado() == Heroe.Estado.PARADO) {
enemigos[i].setEstado(Enemigo.Estado.ATACANDO);
enemigos[i].setObjetivo(nivel.getHeroes().get(j));
if(enemigos[i].getSprite().getX()<nivel.getHeroes().get(j).getSprite().getX()){
enemigos[i].setDireccion(false);
}else{
enemigos[i].setDireccion(true);
}
if(nivel.getHeroes().get(j).getEstado()!=Heroe.Estado.SELECCIONADO){
nivel.getHeroes().get(j).setEstado(Heroe.Estado.ATACANDO);
nivel.getHeroes().get(j).setObjetivo(enemigos[i]);
}
}
if (timerHeroes >= 1 && nivel.getHeroes().get(j).getEstado()== Heroe.Estado.ATACANDO) {
if (enemigos[i].getVitalidad() > 0) {
nivel.getHeroes().get(j).getSoundAttack().play(.5f);
enemigos[i].setVitalidad(enemigos[i].getVitalidad() - nivel.getHeroes().get(j).getDanoFisico());
}
timerHeroes = 0;
}
if (timerEnemigos >= 1.3 && enemigos[i].getEstado() == Enemigo.Estado.ATACANDO) {
if (nivel.getHeroes().get(j).getVitalidad() > 0) {
enemigos[i].getSoundAttack().play(.5f);
nivel.getHeroes().get(j).setVitalidad(nivel.getHeroes().get(j).getVitalidad() - enemigos[i].getDanoFisico());
}
timerEnemigos = 0;
}
if (nivel.getHeroes().get(j).getVitalidad() <= 0) {
nivel.getHeroes().get(j).setEstado(Heroe.Estado.MORIR);
nivel.getHeroes().remove(j);
heroeSel=null;
heroesEliminados++;
//int ran3 = (int)(Math.random() * 4);
Object objetivo = nivel.getCristal();
// buscar entre los que siguen vivos
enemigos[i].setObjetivo(objetivo);
enemigos[i].setEstado(Enemigo.Estado.CAMINANDO);
}
if (enemigos[i].getVitalidad() <= 0) {
nivel.getHeroes().get(j).setObjetivo(null);
int ran3 = (int) (Math.random() * nivel.getHeroes().size() + 1);
Object objetivo = null;
switch (ran3) {
case (0):
objetivo = nivel.getCristal();
break;
default:
if (!nivel.getHeroes().isEmpty()) {
objetivo = nivel.getHeroes().get(ran3 - 1);
}
break;
}
enemigos[i].getSprite().setY(1000);
enemigos[i].setEstado(Enemigo.Estado.MORIR);
enemigos[i] = new Enemigo(nivel.getEnemigos()[ran], 1100, ran2, objetivo);
enemigosEliminados++;
nivel.getHeroes().get(j).setEstado(Heroe.Estado.PARADO);
}
bandera = 1;
}
if (bandera == 0) {
if (!enemigos[i].contiene(nivel.getHeroes().get(j).getSprite().getX(), nivel.getHeroes().get(j).getSprite().getY())) {
enemigos[i].setEstado(Enemigo.Estado.CAMINANDO);
}
if (!nivel.getHeroes().get(j).contiene(enemigos[i].getSprite().getX(), enemigos[i].getSprite().getY())) {
enemigos[i].setEstado(Enemigo.Estado.CAMINANDO);
}
}
}
}
batch.setProjectionMatrix(camara.combined);
batch.begin();
fondo.draw(batch);
btnPausa.draw(batch);
btnSalir.setScale(.01f,.01f);
btnSalir.draw(batch);
range = (nivel.getEnemigos().length - 1) + 1;
range2 = (401);
for (int i = 1; i < this.nivel.getCantEnemigos(); i++) {
ran = (int) (Math.random() * range);
ran2 = (int) (Math.random() * range2);
int ran3 = (int) (Math.random() * nivel.getHeroes().size() + 1);
Object objetivo = null;
switch (ran3) {
case (0):
objetivo = nivel.getCristal();
break;
default:
if (!nivel.getHeroes().isEmpty())
objetivo = nivel.getHeroes().get(ran3 - 1);
break;
}
if (cont < limiteEnemigos) {
this.enemigos[i] = new Enemigo(nivel.getEnemigos()[ran], 1100, ran2, objetivo);
cont += 1;
}
}
// pinta heroes
for (int i = 0; i < nivel.getHeroes().size(); i++) {
//nivel.getHeroes().get(i).draw(batch);
ordenDibujar.add(nivel.getHeroes().get(i));
}
// fin pinta heroes...
//nivel.getCristal().draw(batch);
ordenDibujar.add(nivel.getCristal());
for (int i = 0; i < regresaEnemigos(); i++) {
//enemigos[i].draw(batch);
ordenDibujar.add(enemigos[i]);
}
if (ordenDibujar.size()!=0) {
Collections.sort(ordenDibujar);
for (int l = 0; l < ordenDibujar.size(); l++) {
if( ordenDibujar.get(l) instanceof Heroe){
((Heroe) ordenDibujar.get(l)).draw(batch);
}else if( ordenDibujar.get(l) instanceof Enemigo){
((Enemigo) ordenDibujar.get(l)).draw(batch);
}else {
((Cristal)ordenDibujar.get(l)).draw(batch);
}
}
}
ordenDibujar.clear();
//pintar botones Habilidades
if(heroeSel != null){
for(int k =1; k<=heroeSel.getHabilidades().size();k++){
botonesHabilidades.get(k-1).setPosition(((k-1)*288)+40,604);
botonesHabilidades.get(k-1).draw(batch);
}
}
if(!habilidadesUsadas.isEmpty()){
for (int k=0;k<habilidadesUsadas.size();k++){
habilidadesUsadas.get(k).getSprite().setPosition(heroeHabilidad.get(k).getObjetivo().getSprite().getX(),heroeHabilidad.get(k).getObjetivo().getSprite().getY());
habilidadesUsadas.get(k).draw(batch,habilidadesUsadas,heroeHabilidad,k);
}
}
//ends pintar...
batch.end();
}else if (estado == Estado.GANAR || estado == Estado.PERDER) {
batch.begin();
fondo.draw(batch);
if (estado == Estado.PERDER) {
texturaPerdiste = new Texture("perdiste.png");
batch.draw(texturaPerdiste, 400, 200);
}else{
texturaPerdiste = new Texture("ganaste.png");
batch.draw(texturaPerdiste, 400, 200);
}
Texture back = new Texture("atras.png");
btnAtras = new Sprite(back);
//btnAtras.setScale(1f);
btnAtras.setX(400);
btnAtras.setY(50);
btnAtras.draw(batch);
batch.end();
}else if(estado == Estado.PAUSA){
batch.begin();
fondo.draw(batch);
Texture back = new Texture("atras.png");
btnAtras = new Sprite(back);
//btnAtras.setScale(1f);
btnAtras.setX(400);
btnAtras.setY(50);
btnAtras.draw(batch);
btnSalir.draw(batch);
btnSalir.setScale(1);
batch.end();
}
}
public float[] getPosicion1() {
return posicion;
}
@Override
public void resize(int width, int height) {
vista.update(width,height);
}
@Override
public void pause() {
}
@Override
public void resume() {
}
@Override
public void hide() {
}
@Override
public void dispose() {
batch.dispose();
music.dispose();
texturaPerdiste.dispose();
texturaFondo.dispose();
texturaHeroe1.dispose();
texturaHeroe2.dispose();
texturaHeroe3.dispose();
}
@Override
public boolean keyDown(int keycode) {
return true;
}
@Override
public boolean keyUp(int keycode) {
return false;
}
@Override
public boolean keyTyped(char character) {
return false;
}
@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
//si toco alguna habilidad
Vector3 v = new Vector3(screenX,screenY,0);
int band = 0;
camara.unproject(v);
float x =v.x;
float y = v.y;
if(estado == Estado.PERDER || estado == Estado.GANAR) {
if (x <= btnAtras.getX() + btnAtras.getWidth() && x >= btnAtras.getX() && y <= btnAtras.getY() + btnAtras.getHeight() && y >= btnAtras.getY()) {
juego.setScreen(new PantallaMapa(juego));
return true;
}
}else{
if (btnPausa.getBoundingRectangle().contains(x,y)) {
band=1;
estado = Estado.PAUSA;
return true;
}
}
if(estado == Estado.PAUSA){
if(btnAtras.getBoundingRectangle().contains(x,y)){
band=1;
estado = Estado.JUGANDO;
return true;
}
if(btnSalir.getBoundingRectangle().contains(x,y)){
band=1;
juego.setScreen(new MenuPrincipal(juego));
}
}
for (int i=0; i< nivel.getHeroes().size();i++) {
if (nivel.getHeroes().get(i).getEstado() == Heroe.Estado.SELECCIONADO) {
nivel.getHeroes().get(i).setEstado(Heroe.Estado.DESELECCIONADO);
}
}
if (estado == Estado.JUGANDO) {
for (int i = 0; i < nivel.getHeroes().size(); i++) {
if (nivel.getHeroes().get(i).contiene(x, y)) {
heroeSel = nivel.getHeroes().get(i);
band=1;
xInicial = x;
yInicial = y;
heroeSel.setEstado(Heroe.Estado.SELECCIONADO);
botonesHabilidades.clear();
/*if(heroeSel != null){*/
for(int k =1; k<=heroeSel.getHabilidades().size();k++){
botonesHabilidades.add(heroeSel.getHabilidades().get(k-1).getSprite());
}
//}
break;
}
}
}
for (int i =0; i<botonesHabilidades.size();i++){
if(botonesHabilidades.get(i).getBoundingRectangle().contains(x,y)){
band=1;
switch (Integer.parseInt(heroeSel.getHabilidades().get(i).getId())){
case 4:
case 1://bolas de fuego
if(heroeSel.getObjetivo()!=null){
heroeSel.getObjetivo().setVitalidad(heroeSel.getObjetivo().getVitalidad()-heroeSel.getHabilidades().get(i).getIndice());
System.out.println("WTF");
habilidadesUsadas.add(heroeSel.getHabilidades().get(i));
heroeHabilidad.add(heroeSel);
}
break;
}
}
}
if (band ==0){
heroeSel= null;
}
return true;
}
@Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
Vector3 v = new Vector3(screenX, screenY, 0);
camara.unproject(v);
float x = v.x;
float y = v.y;
for (int i = 0; i < nivel.getHeroes().size(); i++){
if (nivel.getHeroes().get(i).getEstado() == Heroe.Estado.SELECCIONADO || nivel.getHeroes().get(i).getEstado() == Heroe.Estado.ATACANDO) {
//para saber si picamos cerca o lejos
if (x >= xInicial + 5 || x <= xInicial - 5 && y >= yInicial + 5 || y <= yInicial - 5) {
nivel.getHeroes().get(i).setEstado(Heroe.Estado.CAMINANDO);
nivel.getHeroes().get(i).setxFinal(x - nivel.getHeroes().get(0).getMedidax() / 6);
nivel.getHeroes().get(i).setyFinal(y);
for(int z=0;z<regresaEnemigos();z++) {
if (enemigos[z].getSprite().getBoundingRectangle().contains(x, y)) {
nivel.getHeroes().get(i).setObjetivo(enemigos[z]);
break;
}
//setear x para saber de que lado llegar
}
}
if (xInicial < x) {
nivel.getHeroes().get(i).setDireccion(true);
} else {
nivel.getHeroes().get(i).setDireccion(false);
}
}
}
return true;
}
@Override
public boolean touchDragged(int screenX, int screenY, int pointer) {
return true;
}
@Override
public boolean mouseMoved(int screenX, int screenY) {
return false;
}
@Override
public boolean scrolled(int amount) {
return false;
}
public enum Estado{
JUGANDO,
GANAR,
PERDER,
PAUSA
}
}
| core/src/com/mygdx/game/PantallaJuego.java | package com.mygdx.game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.Preferences;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.audio.Music;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.utils.viewport.StretchViewport;
import com.badlogic.gdx.utils.viewport.Viewport;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
public class PantallaJuego implements Screen, InputProcessor {
private final Juego juego;
private OrthographicCamera camara;
private Viewport vista;
private Texture texturaFondo;
private Texture texturaHeroe1;
private Texture texturaHeroe2;
private Texture texturaHeroe3;
private Music music;
private float[] posicion = new float[2];
private Texture texturaPerdiste;
Preferences validacion = Gdx.app.getPreferences("Validacion");
private SpriteBatch batch;
private Texto texto; //texto para mostrar el cd de las habilidades
private Fondo fondo;
private ArrayList<seudoSprite> ordenDibujar;
private Estado estado = Estado.JUGANDO;
private Nivel nivel;
private String[] heroesId = new String[3];
private Enemigo[] enemigos;
private float timerHeroes =0;
private float timerEnemigos =0;
float xInicial,yInicial;
private int cont =0;
private int limiteEnemigos =2;
private int enemigosEliminados =0;
private int heroesEliminados =0;
private Sprite btnAtras;
private Sprite btnPausa;
private Sprite btnSalir;
//habilidades
private Heroe heroeSel= null;
private ArrayList<Sprite> botonesHabilidades = new ArrayList<Sprite>();
private ArrayList<Habilidad> habilidadesUsadas = new ArrayList<Habilidad>();
private ArrayList<Heroe> heroeHabilidad = new ArrayList<Heroe>();
public PantallaJuego(Juego juego,String nivelId) {
this.juego = juego;
heroesId[0]="1";
heroesId[1]="2";
heroesId[2]="3";
this.nivel = new Nivel(nivelId,heroesId);
this.enemigos = new Enemigo[this.nivel.getCantEnemigos()];
int range = (nivel.getEnemigos().length-1) + 1;
int range2 = (401);
int ran = (int)(Math.random() * range);
int ran2 = (int)(Math.random() * range2);
int ran3 = (int)(Math.random() * nivel.getHeroes().size()+1);
Object objetivo = null;
switch(ran3){
case(0):
objetivo = nivel.getCristal();
break;
default:
objetivo = nivel.getHeroes().get(ran3-1);
break;
}
//Gdx.app.log("Create",ran3+"");
this.enemigos[0] = new Enemigo(nivel.getEnemigos()[ran], 900, ran2, objetivo);
cont+=1;
ordenDibujar = new ArrayList<seudoSprite>();
}
private int regresaEnemigos() {
int cont=0;
try {
for (int i = 0; i < enemigos.length; i++) {
if (enemigos[i]!= null)
cont+=1;
}
}
catch (Exception error){
return cont;
}
return cont;
}
@Override
public void show() {
inicializarCamara();
cargarTexturas();
crearEscena();
Gdx.input.setInputProcessor(this);
texto =new Texto();
music = Gdx.audio.newMusic(Gdx.files.internal("The_Trip_to_the_Market.mp3"));
music.setLooping(true);
music.play();
Gdx.input.setCatchBackKey(true);
if(validacion.getString("2").equals("0")) {
music.pause();
}
if(validacion.getString("2").equals("1")) {
music.play();
}
}
private void inicializarCamara() {
camara = new OrthographicCamera(1280,720);
camara.position.set(1280/2,720/2,0);
camara.update();
vista = new StretchViewport(1280,720,camara);
}
private void cargarTexturas() {
texturaFondo = this.nivel.getTextura();
texturaHeroe1 = this.nivel.getHeroes().get(0).getTextura();
texturaHeroe2 = this.nivel.getHeroes().get(1).getTextura();
texturaHeroe3 = this.nivel.getHeroes().get(2).getTextura();
btnPausa = new Sprite(new Texture("pausa.png"));
btnPausa.setX(1020);
btnPausa.setY(544);
btnSalir = new Sprite(new Texture("exit.png"));
btnSalir.setX(1280/2);
btnSalir.setY(800/2);
}
private void crearEscena() {
batch = new SpriteBatch();
fondo = new Fondo(texturaFondo);
}
@Override
public void render(float delta) {
Gdx.gl.glClearColor(1,1,1,1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
int range = (nivel.getEnemigos().length-1) + 1;
int range2 = (401);
if(estado == Estado.JUGANDO) {
int ran = (int) (Math.random() * range);
int ran2 = (int) (Math.random() * range2);
int bandera = 0;
if (enemigosEliminados >= nivel.getCantEnemigos()) {
estado = Estado.GANAR;
}
if (heroesEliminados >= 3 || nivel.getCristal().getVitalidad()<=0) {
estado = Estado.PERDER;
}
timerHeroes += Gdx.graphics.getDeltaTime();
timerEnemigos += Gdx.graphics.getDeltaTime();
for (int i = 0; i < cont; i++) {
for (int j = 0; j < nivel.getHeroes().size(); j++) {
if (nivel.getHeroes().get(j).contiene(enemigos[i].getSprite().getBoundingRectangle()) || enemigos[i].contiene(nivel.getHeroes().get(j).getSprite().getBoundingRectangle())) {
if (nivel.getHeroes().get(j).getEstado() == Heroe.Estado.PARADO) {
enemigos[i].setEstado(Enemigo.Estado.ATACANDO);
enemigos[i].setObjetivo(nivel.getHeroes().get(j));
if(enemigos[i].getSprite().getX()<nivel.getHeroes().get(j).getSprite().getX()){
enemigos[i].setDireccion(false);
}else{
enemigos[i].setDireccion(true);
}
if(nivel.getHeroes().get(j).getEstado()!=Heroe.Estado.SELECCIONADO){
nivel.getHeroes().get(j).setEstado(Heroe.Estado.ATACANDO);
nivel.getHeroes().get(j).setObjetivo(enemigos[i]);
}
}
if (timerHeroes >= 1 && nivel.getHeroes().get(j).getEstado()== Heroe.Estado.ATACANDO) {
if (enemigos[i].getVitalidad() > 0) {
nivel.getHeroes().get(j).getSoundAttack().play(.5f);
enemigos[i].setVitalidad(enemigos[i].getVitalidad() - nivel.getHeroes().get(j).getDanoFisico());
}
timerHeroes = 0;
}
if (timerEnemigos >= 1.3 && enemigos[i].getEstado() == Enemigo.Estado.ATACANDO) {
if (nivel.getHeroes().get(j).getVitalidad() > 0) {
enemigos[i].getSoundAttack().play(.5f);
nivel.getHeroes().get(j).setVitalidad(nivel.getHeroes().get(j).getVitalidad() - enemigos[i].getDanoFisico());
}
timerEnemigos = 0;
}
if (nivel.getHeroes().get(j).getVitalidad() <= 0) {
nivel.getHeroes().get(j).setEstado(Heroe.Estado.MORIR);
nivel.getHeroes().remove(j);
heroeSel=null;
heroesEliminados++;
//int ran3 = (int)(Math.random() * 4);
Object objetivo = nivel.getCristal();
// buscar entre los que siguen vivos
enemigos[i].setObjetivo(objetivo);
enemigos[i].setEstado(Enemigo.Estado.CAMINANDO);
}
if (enemigos[i].getVitalidad() <= 0) {
nivel.getHeroes().get(j).setObjetivo(null);
int ran3 = (int) (Math.random() * nivel.getHeroes().size() + 1);
Object objetivo = null;
switch (ran3) {
case (0):
objetivo = nivel.getCristal();
break;
default:
if (!nivel.getHeroes().isEmpty()) {
objetivo = nivel.getHeroes().get(ran3 - 1);
}
break;
}
enemigos[i].getSprite().setY(1000);
enemigos[i].setEstado(Enemigo.Estado.MORIR);
enemigos[i] = new Enemigo(nivel.getEnemigos()[ran], 1100, ran2, objetivo);
enemigosEliminados++;
nivel.getHeroes().get(j).setEstado(Heroe.Estado.PARADO);
}
bandera = 1;
}
if (bandera == 0) {
if (!enemigos[i].contiene(nivel.getHeroes().get(j).getSprite().getX(), nivel.getHeroes().get(j).getSprite().getY())) {
enemigos[i].setEstado(Enemigo.Estado.CAMINANDO);
}
if (!nivel.getHeroes().get(j).contiene(enemigos[i].getSprite().getX(), enemigos[i].getSprite().getY())) {
enemigos[i].setEstado(Enemigo.Estado.CAMINANDO);
}
}
}
}
batch.setProjectionMatrix(camara.combined);
batch.begin();
fondo.draw(batch);
btnPausa.draw(batch);
btnSalir.setScale(.01f,.01f);
btnSalir.draw(batch);
range = (nivel.getEnemigos().length - 1) + 1;
range2 = (401);
for (int i = 1; i < this.nivel.getCantEnemigos(); i++) {
ran = (int) (Math.random() * range);
ran2 = (int) (Math.random() * range2);
int ran3 = (int) (Math.random() * nivel.getHeroes().size() + 1);
Object objetivo = null;
switch (ran3) {
case (0):
objetivo = nivel.getCristal();
break;
default:
if (!nivel.getHeroes().isEmpty())
objetivo = nivel.getHeroes().get(ran3 - 1);
break;
}
if (cont < limiteEnemigos) {
this.enemigos[i] = new Enemigo(nivel.getEnemigos()[ran], 1100, ran2, objetivo);
cont += 1;
}
}
// pinta heroes
for (int i = 0; i < nivel.getHeroes().size(); i++) {
//nivel.getHeroes().get(i).draw(batch);
ordenDibujar.add(nivel.getHeroes().get(i));
}
// fin pinta heroes...
//nivel.getCristal().draw(batch);
ordenDibujar.add(nivel.getCristal());
for (int i = 0; i < regresaEnemigos(); i++) {
//enemigos[i].draw(batch);
ordenDibujar.add(enemigos[i]);
}
if (ordenDibujar.size()!=0) {
Collections.sort(ordenDibujar);
for (int l = 0; l < ordenDibujar.size(); l++) {
if( ordenDibujar.get(l) instanceof Heroe){
((Heroe) ordenDibujar.get(l)).draw(batch);
}else if( ordenDibujar.get(l) instanceof Enemigo){
((Enemigo) ordenDibujar.get(l)).draw(batch);
}else {
((Cristal)ordenDibujar.get(l)).draw(batch);
}
}
}
ordenDibujar.clear();
//pintar botones Habilidades
if(heroeSel != null){
for(int k =1; k<=heroeSel.getHabilidades().size();k++){
botonesHabilidades.get(k-1).setPosition(((k-1)*288)+40,604);
botonesHabilidades.get(k-1).draw(batch);
}
}
if(!habilidadesUsadas.isEmpty()){
for (int k=0;k<habilidadesUsadas.size();k++){
habilidadesUsadas.get(k).getSprite().setPosition(heroeHabilidad.get(k).getObjetivo().getSprite().getX(),heroeHabilidad.get(k).getObjetivo().getSprite().getY());
habilidadesUsadas.get(k).draw(batch,habilidadesUsadas,heroeHabilidad,k);
}
}
//ends pintar...
batch.end();
}else if (estado == Estado.GANAR || estado == Estado.PERDER) {
batch.begin();
fondo.draw(batch);
if (estado == Estado.PERDER) {
texturaPerdiste = new Texture("perdiste.png");
batch.draw(texturaPerdiste, 400, 200);
}else{
texturaPerdiste = new Texture("ganaste.png");
batch.draw(texturaPerdiste, 400, 200);
}
Texture back = new Texture("atras.png");
btnAtras = new Sprite(back);
//btnAtras.setScale(1f);
btnAtras.setX(400);
btnAtras.setY(50);
btnAtras.draw(batch);
batch.end();
}else if(estado == Estado.PAUSA){
batch.begin();
fondo.draw(batch);
Texture back = new Texture("atras.png");
btnAtras = new Sprite(back);
//btnAtras.setScale(1f);
btnAtras.setX(400);
btnAtras.setY(50);
btnAtras.draw(batch);
btnSalir.draw(batch);
btnSalir.setScale(1);
batch.end();
}
}
public float[] getPosicion1() {
return posicion;
}
@Override
public void resize(int width, int height) {
vista.update(width,height);
}
@Override
public void pause() {
}
@Override
public void resume() {
}
@Override
public void hide() {
}
@Override
public void dispose() {
batch.dispose();
music.dispose();
texturaPerdiste.dispose();
texturaFondo.dispose();
texturaHeroe1.dispose();
texturaHeroe2.dispose();
texturaHeroe3.dispose();
}
@Override
public boolean keyDown(int keycode) {
return true;
}
@Override
public boolean keyUp(int keycode) {
return false;
}
@Override
public boolean keyTyped(char character) {
return false;
}
@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
//si toco alguna habilidad
Vector3 v = new Vector3(screenX,screenY,0);
int band = 0;
camara.unproject(v);
float x =v.x;
float y = v.y;
if(estado == Estado.PERDER || estado == Estado.GANAR) {
if (x <= btnAtras.getX() + btnAtras.getWidth() && x >= btnAtras.getX() && y <= btnAtras.getY() + btnAtras.getHeight() && y >= btnAtras.getY()) {
juego.setScreen(new PantallaMapa(juego));
return true;
}
}else{
if (btnPausa.getBoundingRectangle().contains(x,y)) {
band=1;
estado = Estado.PAUSA;
return true;
}
}
if(estado == Estado.PAUSA){
if(btnAtras.getBoundingRectangle().contains(x,y)){
band=1;
estado = Estado.JUGANDO;
return true;
}
if(btnSalir.getBoundingRectangle().contains(x,y)){
band=1;
juego.setScreen(new MenuPrincipal(juego));
}
}
for (int i=0; i< nivel.getHeroes().size();i++) {
if (nivel.getHeroes().get(i).getEstado() == Heroe.Estado.SELECCIONADO) {
nivel.getHeroes().get(i).setEstado(Heroe.Estado.DESELECCIONADO);
}
}
if (estado == Estado.JUGANDO) {
for (int i = 0; i < nivel.getHeroes().size(); i++) {
if (nivel.getHeroes().get(i).contiene(x, y)) {
heroeSel = nivel.getHeroes().get(i);
band=1;
xInicial = x;
yInicial = y;
heroeSel.setEstado(Heroe.Estado.SELECCIONADO);
botonesHabilidades.clear();
/*if(heroeSel != null){*/
for(int k =1; k<=heroeSel.getHabilidades().size();k++){
botonesHabilidades.add(heroeSel.getHabilidades().get(k-1).getSprite());
}
//}
break;
}
}
}
for (int i =0; i<botonesHabilidades.size();i++){
if(botonesHabilidades.get(i).getBoundingRectangle().contains(x,y)){
band=1;
switch (Integer.parseInt(heroeSel.getHabilidades().get(i).getId())){
case 4:
case 1://bolas de fuego
if(heroeSel.getObjetivo()!=null){
heroeSel.getObjetivo().setVitalidad(heroeSel.getObjetivo().getVitalidad()-heroeSel.getHabilidades().get(i).getIndice());
System.out.println("WTF");
habilidadesUsadas.add(heroeSel.getHabilidades().get(i));
heroeHabilidad.add(heroeSel);
}
break;
}
}
}
if (band ==0){
heroeSel= null;
}
return true;
}
@Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
Vector3 v = new Vector3(screenX, screenY, 0);
camara.unproject(v);
float x = v.x;
float y = v.y;
for (int i = 0; i < nivel.getHeroes().size(); i++){
if (nivel.getHeroes().get(i).getEstado() == Heroe.Estado.SELECCIONADO) {
//para saber si picamos cerca o lejos
if (x >= xInicial + 5 || x <= xInicial - 5 && y >= yInicial + 5 || y <= yInicial - 5) {
nivel.getHeroes().get(i).setEstado(Heroe.Estado.CAMINANDO);
nivel.getHeroes().get(i).setxFinal(x - nivel.getHeroes().get(0).getMedidax() / 6);
nivel.getHeroes().get(i).setyFinal(y);
for(int z=0;z<regresaEnemigos();z++) {
if (enemigos[z].getSprite().getBoundingRectangle().contains(x, y)) {
nivel.getHeroes().get(i).setObjetivo(enemigos[z]);
break;
}
//setear x para saber de que lado llegar
}
}
if (xInicial < x) {
nivel.getHeroes().get(i).setDireccion(true);
} else {
nivel.getHeroes().get(i).setDireccion(false);
}
}
}
return true;
}
@Override
public boolean touchDragged(int screenX, int screenY, int pointer) {
return true;
}
@Override
public boolean mouseMoved(int screenX, int screenY) {
return false;
}
@Override
public boolean scrolled(int amount) {
return false;
}
public enum Estado{
JUGANDO,
GANAR,
PERDER,
PAUSA
}
}
| habilidades
| core/src/com/mygdx/game/PantallaJuego.java | habilidades | <ide><path>ore/src/com/mygdx/game/PantallaJuego.java
<ide> float y = v.y;
<ide>
<ide> for (int i = 0; i < nivel.getHeroes().size(); i++){
<del> if (nivel.getHeroes().get(i).getEstado() == Heroe.Estado.SELECCIONADO) {
<add> if (nivel.getHeroes().get(i).getEstado() == Heroe.Estado.SELECCIONADO || nivel.getHeroes().get(i).getEstado() == Heroe.Estado.ATACANDO) {
<ide> //para saber si picamos cerca o lejos
<ide> if (x >= xInicial + 5 || x <= xInicial - 5 && y >= yInicial + 5 || y <= yInicial - 5) {
<ide> nivel.getHeroes().get(i).setEstado(Heroe.Estado.CAMINANDO); |
|
Java | apache-2.0 | 75ebabde2d7e0f1a4c09f8099057bbf974da376e | 0 | StefanLiebenberg/closure-stylesheets,mahieddine/closure-stylesheets,knutwalker/google-closure-stylesheets,iwatchallit/closure-stylesheets,jDramaix/closure-stylesheet-gss,google/postcss-rename,varshluck/closure-stylesheets,smennetrier/closure-stylesheets,buntarb/closure-stylesheets,Dj-Corps/closure-stylesheets,buttflattery/closure-stylesheets,KodkodGates/closure-stylesheets,sloflin72/closure-stylesheets,google/closure-stylesheets,google/postcss-rename | /*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.css.compiler.ast;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.collect.BiMap;
import com.google.common.collect.ImmutableBiMap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.css.Vendor;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.Nullable;
/**
* An object that represents a CSS property. Although this class contains a
* large set of built-in properties (see {@link #allRecognizedProperties()}), it
* is a class rather than an enum so that it is possible to create properties
* that are not built-in. User agents will likely add support for new properties
* faster than we can add them to this list.
*
* @author [email protected] (Michael Bolin)
*/
public final class Property {
/**
* The CSS properties recognized by default by the CSS Compiler, indexed by
* name. Note that this includes non-standard properties, such as
* "-webkit-border-radius".
*/
private static final BiMap<String, Property> NAME_TO_PROPERTY_MAP;
static {
List<Builder> recognizedProperties = ImmutableList.of(
builder("alignment-baseline").isSvgOnly(),
builder("animation"),
builder("animation-delay"),
builder("animation-direction"),
builder("animation-duration"),
builder("animation-iteration-count"),
builder("animation-name"),
builder("animation-play-state"),
builder("animation-timing-function"),
builder("azimuth"),
builder("background-attachment"),
builder("background-clip"),
builder("background-color"),
builder("background-image"),
builder("background-origin"),
builder("background-position"),
builder("background-position-x"),
builder("background-position-y"),
builder("background-repeat"),
builder("background-size"),
builder("background"),
builder("baseline-shift").isSvgOnly(),
builder("border-collapse"),
builder("border-color").setHasPositionalParameters(true),
builder("border-spacing"),
builder("border-style").setHasPositionalParameters(true),
builder("border-top"),
builder("border-right"),
builder("border-bottom"),
builder("border-left"),
builder("border-top-color"),
builder("border-right-color"),
builder("border-bottom-color"),
builder("border-left-color"),
builder("border-top-style"),
builder("border-right-style"),
builder("border-bottom-style"),
builder("border-left-style"),
builder("border-top-width"),
builder("border-right-width"),
builder("border-bottom-width"),
builder("border-left-width"),
builder("border-width").setHasPositionalParameters(true),
builder("border-image"),
// None of border-radius, -webkit-border-radius, and -moz-border-radius
// have setHasPositionalParameters(true) because each can take up to 8
// values according to the spec, as it is possible to specify the length
// of the horizontal and vertical radii independently for each corner:
//
// http://www.w3.org/TR/css3-background/#the-border-radius
//
// TODO(bolinfest): This is going to require special handling when it
// comes to RTL flipping, which the current
// "setHasPositionalParameters()" does not take into account.
builder("border-radius"),
builder("border-top-left-radius"),
builder("border-top-right-radius"),
builder("border-bottom-right-radius"),
builder("border-bottom-left-radius"),
builder("border"),
builder("bottom"),
builder("box-align").warn(
"Spec'd but not supported yet."),
builder("box-flex"),
builder("box-orient"),
builder("box-pack").warn(
"Spec'd but not supported yet."),
builder("box-shadow"),
builder("box-sizing"),
builder("caption-side"),
builder("clear"),
builder("clip"),
builder("clip-path").isSvgOnly(),
builder("clip-rule").isSvgOnly(),
builder("color"),
builder("color-interpolation").isSvgOnly(),
builder("color-interpolation-filters").isSvgOnly(),
builder("color-profile").isSvgOnly(),
builder("color-rendering").isSvgOnly(),
builder("content"),
builder("counter-increment"),
builder("counter-reset"),
builder("cue-after"),
builder("cue-before"),
builder("cue"),
builder("cursor"),
builder("direction"),
builder("display"),
builder("dominant-baseline").isSvgOnly(),
builder("elevation"),
builder("empty-cells"),
builder("enable-background").isSvgOnly(),
builder("-epub-caption-side"),
builder("-epub-hyphens"),
builder("-epub-text-combine"),
builder("-epub-text-emphasis"),
builder("-epub-text-emphasis-color"),
builder("-epub-text-emphasis-style"),
builder("-epub-text-orientation"),
builder("-epub-text-transform"),
builder("-epub-word-break"),
builder("-epub-writing-mode"),
builder("fill").isSvgOnly(),
builder("fill-opacity").isSvgOnly(),
builder("fill-rule").isSvgOnly(),
// This is not a MICROSOFT-specific property because it is also an SVG
// property: http://www.w3.org/TR/SVG/styling.html
builder("filter"),
builder("flex"),
builder("float"),
builder("flood-color").isSvgOnly(),
builder("flood-opacity").isSvgOnly(),
builder("font"),
builder("font-family"),
builder("font-size"),
builder("font-size-adjust"),
builder("font-stretch"),
builder("font-style"),
builder("font-variant"),
builder("font-weight"),
builder("glyph-orientation-horizontal").isSvgOnly(),
builder("glyph-orientation-vertical").isSvgOnly(),
builder("height"),
builder("image-rendering").isSvgOnly(),
builder("kerning").isSvgOnly(),
builder("-khtml-user-select"),
builder("left"),
builder("letter-spacing"),
builder("lighting-color").isSvgOnly(),
builder("line-height"),
builder("list-style-image"),
builder("list-style-position"),
builder("list-style-type"),
builder("list-style"),
builder("margin-right"),
builder("margin-left"),
builder("margin-top"),
builder("margin-bottom"),
builder("margin").setHasPositionalParameters(true),
builder("marker").isSvgOnly(),
builder("marker-end").isSvgOnly(),
builder("marker-mid").isSvgOnly(),
builder("marker-start").isSvgOnly(),
builder("mask").isSvgOnly(),
builder("max-height"),
builder("max-width"),
builder("min-height"),
builder("min-width"),
builder("-moz-animation"),
builder("-moz-animation-delay"),
builder("-moz-animation-direction"),
builder("-moz-animation-duration"),
builder("-moz-animation-fill-mode"),
builder("-moz-animation-iteration-count"),
builder("-moz-animation-name"),
builder("-moz-animation-play-state"),
builder("-moz-animation-timing-function"),
builder("-moz-appearance"),
builder("-moz-backface-visibility"),
builder("-moz-background-clip"),
builder("-moz-background-inline-policy"),
builder("-moz-background-origin"),
builder("-moz-background-size"),
builder("-moz-binding"),
builder("-moz-border-bottom-colors"),
builder("-moz-border-end"),
builder("-moz-border-end-color"),
builder("-moz-border-end-style"),
builder("-moz-border-end-width"),
builder("-moz-border-image"),
builder("-moz-border-left-colors"),
builder("-moz-border-radius"),
builder("-moz-border-radius-topleft"),
builder("-moz-border-radius-topright"),
builder("-moz-border-radius-bottomright"),
builder("-moz-border-radius-bottomleft"),
builder("-moz-border-right-colors"),
builder("-moz-border-start"),
builder("-moz-border-start-color"),
builder("-moz-border-start-style"),
builder("-moz-border-start-width"),
builder("-moz-border-top-colors"),
builder("-moz-box-align"),
builder("-moz-box-direction"),
builder("-moz-box-flex"),
builder("-moz-box-ordinal-group"),
builder("-moz-box-orient"),
builder("-moz-box-pack"),
builder("-moz-box-shadow"),
builder("-moz-box-sizing"),
builder("-moz-column-count"),
builder("-moz-column-gap"),
builder("-moz-column-rule"),
builder("-moz-column-rule-color"),
builder("-moz-column-rule-style"),
builder("-moz-column-rule-width"),
builder("-moz-column-width"),
builder("-moz-columns"),
builder("-moz-flex"),
builder("-moz-float-edge"),
builder("-moz-font-feature-settings"),
builder("-moz-font-language-override"),
builder("-moz-force-broken-image-icon"),
builder("-moz-hyphens"),
builder("-moz-image-region"),
builder("-moz-margin-end"),
builder("-moz-margin-start"),
builder("-moz-opacity"),
builder("-moz-orient"),
builder("-moz-outline-radius"),
builder("-moz-outline-radius-bottomleft"),
builder("-moz-outline-radius-bottomright"),
builder("-moz-outline-radius-topleft"),
builder("-moz-outline-radius-topright"),
builder("-moz-padding-end"),
builder("-moz-padding-start"),
builder("-moz-perspective"),
builder("-moz-perspective-origin"),
builder("-moz-script-level"),
builder("-moz-script-min-size"),
builder("-moz-script-size-multiplier"),
builder("-moz-stack-sizing"),
builder("-moz-tab-size"),
builder("-moz-text-blink"),
builder("-moz-text-decoration-color"),
builder("-moz-text-decoration-line"),
builder("-moz-text-decoration-style"),
builder("-moz-text-size-adjust"),
builder("-moz-transform"),
builder("-moz-transform-origin"),
builder("-moz-transform-style"),
builder("-moz-transition"),
builder("-moz-transition-delay"),
builder("-moz-transition-duration"),
builder("-moz-transition-property"),
builder("-moz-transition-timing-function"),
builder("-moz-user-focus"),
builder("-moz-user-input"),
builder("-moz-user-modify"),
builder("-moz-user-select"),
builder("-moz-window-shadow"),
builder("-ms-accelerator"),
builder("-ms-animation"),
builder("-ms-animation-delay"),
builder("-ms-animation-direction"),
builder("-ms-animation-duration"),
builder("-ms-animation-fill-mode"),
builder("-ms-animation-iteration-count"),
builder("-ms-animation-name"),
builder("-ms-animation-play-state"),
builder("-ms-animation-timing-function"),
builder("-ms-background-position-x"),
builder("-ms-background-position-y"),
builder("-ms-behavior"),
builder("-ms-block-progression"),
builder("-ms-box-align"),
builder("-ms-box-direction"),
builder("-ms-box-flex"),
builder("-ms-box-line-progression"),
builder("-ms-box-lines"),
builder("-ms-box-ordinal-group"),
builder("-ms-box-orient"),
builder("-ms-box-pack"),
builder("-ms-box-shadow"),
builder("-ms-box-sizing"),
builder("-ms-filter"),
builder("-ms-flex"),
builder("-ms-grid-column"),
builder("-ms-grid-column-align"),
builder("-ms-grid-column-span"),
builder("-ms-grid-columns"),
builder("-ms-grid-layer"),
builder("-ms-grid-row"),
builder("-ms-grid-row-align"),
builder("-ms-grid-row-span"),
builder("-ms-grid-rows"),
builder("-ms-ime-mode"),
builder("-ms-interpolation-mode"),
builder("-ms-layout-flow"),
builder("-ms-layout-grid"),
builder("-ms-layout-grid-char"),
builder("-ms-layout-grid-line"),
builder("-ms-layout-grid-mode"),
builder("-ms-layout-grid-type"),
builder("-ms-line-break"),
builder("-ms-line-grid-mode"),
builder("-ms-overflow-x"),
builder("-ms-overflow-y"),
builder("-ms-scrollbar-arrow-color"),
builder("-ms-scrollbar-base-color"),
builder("-ms-scrollbar-darkshadow-color"),
builder("-ms-scrollbar-face-color"),
builder("-ms-scrollbar-highlight-color"),
builder("-ms-scrollbar-shadow-color"),
builder("-ms-scrollbar-track-color"),
builder("-ms-text-align-last"),
builder("-ms-text-autospace"),
builder("-ms-text-justify"),
builder("-ms-text-kashida-space"),
builder("-ms-text-overflow"),
builder("-ms-text-size-adjust"),
builder("-ms-text-underline-position"),
builder("-ms-transform"),
builder("-ms-transform-origin"),
builder("-ms-transition"),
builder("-ms-transition-delay"),
builder("-ms-transition-duration"),
builder("-ms-transition-property"),
builder("-ms-transition-timing-function"),
builder("-ms-user-select"),
builder("-ms-word-break"),
builder("-ms-word-wrap"),
builder("-ms-writing-mode"),
builder("-ms-zoom"),
builder("-o-animation"),
builder("-o-animation-delay"),
builder("-o-animation-direction"),
builder("-o-animation-duration"),
builder("-o-animation-fill-mode"),
builder("-o-animation-iteration-count"),
builder("-o-animation-name"),
builder("-o-animation-play-state"),
builder("-o-animation-timing-function"),
builder("-o-background-size"),
builder("-o-text-overflow"),
builder("-o-transform"),
builder("-o-transform-origin"),
builder("-o-transition"),
builder("-o-transition-delay"),
builder("-o-transition-duration"),
builder("-o-transition-property"),
builder("-o-transition-timing-function"),
builder("opacity"),
builder("orphans"),
builder("outline-color"),
builder("outline-offset"),
builder("outline-style"),
builder("outline-width"),
builder("outline"),
builder("overflow"),
builder("overflow-x"),
builder("overflow-y"),
builder("padding-top"),
builder("padding-right"),
builder("padding-bottom"),
builder("padding-left"),
builder("padding").setHasPositionalParameters(true),
builder("page-break-after"),
builder("page-break-before"),
builder("page-break-inside"),
builder("pause-after"),
builder("pause-before"),
builder("pause"),
builder("pitch-range"),
builder("pitch"),
builder("play-during"),
builder("pointer-events"),
builder("position"),
builder("quotes"),
builder("resize"),
builder("richness"),
builder("right"),
builder("scrollbar-3dlight-color"),
builder("scrollbar-arrow-color"),
builder("scrollbar-base-color"),
builder("scrollbar-darkshadow-color"),
builder("scrollbar-face-color"),
builder("scrollbar-highlight-color"),
builder("scrollbar-shadow-color"),
builder("scrollbar-track-color"),
builder("shape-rendering").isSvgOnly(),
builder("size"),
builder("speak-header"),
builder("speak-numeral"),
builder("speak-punctuation"),
builder("speak"),
builder("speech-rate"),
builder("src"), // Only for use within @font-face
builder("stop-color").isSvgOnly(),
builder("stop-opacity").isSvgOnly(),
builder("stress"),
builder("stroke").isSvgOnly(),
builder("stroke-dasharray").isSvgOnly(),
builder("stroke-dashoffset").isSvgOnly(),
builder("stroke-linecap").isSvgOnly(),
builder("stroke-linejoin").isSvgOnly(),
builder("stroke-miterlimit").isSvgOnly(),
builder("stroke-opacity").isSvgOnly(),
builder("stroke-width").isSvgOnly(),
builder("table-layout"),
builder("text-align"),
builder("text-anchor").isSvgOnly(),
builder("text-decoration"),
builder("text-indent"),
builder("text-overflow"),
builder("text-rendering").isSvgOnly(),
builder("text-shadow"),
builder("text-transform"),
builder("transform"),
builder("transform-origin"),
builder("transition-delay"),
builder("transition-duration"),
builder("transition-property"),
builder("transition-timing-function"),
builder("top"),
builder("transition"),
builder("unicode-bidi"),
builder("vertical-align"),
builder("visibility"),
builder("voice-family"),
builder("volume"),
builder("-webkit-align-items"),
builder("-webkit-align-self"),
builder("-webkit-animation"),
builder("-webkit-animation-delay"),
builder("-webkit-animation-direction"),
builder("-webkit-animation-duration"),
builder("-webkit-animation-fill-mode"),
builder("-webkit-animation-iteration-count"),
builder("-webkit-animation-name"),
builder("-webkit-animation-play-state"),
builder("-webkit-animation-timing-function"),
builder("-webkit-appearance"),
builder("-webkit-aspect-ratio"),
builder("-webkit-backface-visibility"),
builder("-webkit-background-clip"),
builder("-webkit-background-composite"),
builder("-webkit-background-origin"),
builder("-webkit-background-size"),
builder("-webkit-border-after"),
builder("-webkit-border-after-color"),
builder("-webkit-border-after-style"),
builder("-webkit-border-after-width"),
builder("-webkit-border-before"),
builder("-webkit-border-before-color"),
builder("-webkit-border-before-style"),
builder("-webkit-border-before-width"),
builder("-webkit-border-bottom-left-radius"),
builder("-webkit-border-bottom-right-radius"),
builder("-webkit-border-end"),
builder("-webkit-border-end-color"),
builder("-webkit-border-end-style"),
builder("-webkit-border-end-width"),
builder("-webkit-border-fit"),
builder("-webkit-border-horizontal-spacing"),
builder("-webkit-border-image"),
builder("-webkit-border-radius"),
builder("-webkit-border-start"),
builder("-webkit-border-start-color"),
builder("-webkit-border-start-style"),
builder("-webkit-border-start-width"),
builder("-webkit-border-top-left-radius"),
builder("-webkit-border-top-right-radius"),
builder("-webkit-border-vertical-spacing"),
builder("-webkit-box-align"),
builder("-webkit-box-direction"),
builder("-webkit-box-flex"),
builder("-webkit-box-flex-group"),
builder("-webkit-box-lines"),
builder("-webkit-box-ordinal-group"),
builder("-webkit-box-orient"),
builder("-webkit-box-pack"),
builder("-webkit-box-reflect"),
builder("-webkit-box-shadow"),
builder("-webkit-box-sizing"),
builder("-webkit-color-correction"),
builder("-webkit-column-axis"),
builder("-webkit-column-break-after"),
builder("-webkit-column-break-before"),
builder("-webkit-column-break-inside"),
builder("-webkit-column-count"),
builder("-webkit-column-gap"),
builder("-webkit-column-rule"),
builder("-webkit-column-rule-color"),
builder("-webkit-column-rule-style"),
builder("-webkit-column-rule-width"),
builder("-webkit-column-span"),
builder("-webkit-column-width"),
builder("-webkit-columns"),
builder("-webkit-dashboard-region"),
builder("-webkit-filter"),
builder("-webkit-flex"),
builder("-webkit-flex-align"),
builder("-webkit-flex-direction"),
builder("-webkit-flex-flow"),
builder("-webkit-flex-order"),
builder("-webkit-flex-pack"),
builder("-webkit-flex-wrap"),
builder("-webkit-flow-from"),
builder("-webkit-flow-into"),
builder("-webkit-font-feature-settings"),
builder("-webkit-font-size-delta"),
builder("-webkit-font-smoothing"),
builder("-webkit-grid-columns"),
builder("-webkit-grid-rows"),
builder("-webkit-highlight"),
builder("-webkit-hyphenate-character"),
builder("-webkit-hyphenate-limit-after"),
builder("-webkit-hyphenate-limit-before"),
builder("-webkit-hyphenate-limit-lines"),
builder("-webkit-line-box-contain"),
builder("-webkit-line-break"),
builder("-webkit-line-clamp"),
builder("-webkit-line-grid"),
builder("-webkit-line-grid-snap"),
builder("-webkit-locale"),
builder("-webkit-logical-height"),
builder("-webkit-logical-width"),
builder("-webkit-margin-after"),
builder("-webkit-margin-after-collapse"),
builder("-webkit-margin-before"),
builder("-webkit-margin-before-collapse"),
builder("-webkit-margin-bottom-collapse"),
builder("-webkit-margin-collapse"),
builder("-webkit-margin-end"),
builder("-webkit-margin-start"),
builder("-webkit-margin-top-collapse"),
builder("-webkit-marquee"),
builder("-webkit-marquee-direction"),
builder("-webkit-marquee-increment"),
builder("-webkit-marquee-repetition"),
builder("-webkit-marquee-speed"),
builder("-webkit-marquee-style"),
builder("-webkit-mask"),
builder("-webkit-mask-attachment"),
builder("-webkit-mask-box-image"),
builder("-webkit-mask-box-image-outset"),
builder("-webkit-mask-box-image-repeat"),
builder("-webkit-mask-box-image-slice"),
builder("-webkit-mask-box-image-source"),
builder("-webkit-mask-box-image-width"),
builder("-webkit-mask-clip"),
builder("-webkit-mask-composite"),
builder("-webkit-mask-image"),
builder("-webkit-mask-origin"),
builder("-webkit-mask-position"),
builder("-webkit-mask-position-x"),
builder("-webkit-mask-position-y"),
builder("-webkit-mask-repeat"),
builder("-webkit-mask-repeat-x"),
builder("-webkit-mask-repeat-y"),
builder("-webkit-mask-size"),
builder("-webkit-match-nearest-mail-blockquote-color"),
builder("-webkit-max-logical-height"),
builder("-webkit-max-logical-width"),
builder("-webkit-min-logical-height"),
builder("-webkit-min-logical-width"),
builder("-webkit-nbsp-mode"),
builder("-webkit-opacity"),
builder("-webkit-overflow-scrolling"),
builder("-webkit-padding-after"),
builder("-webkit-padding-before"),
builder("-webkit-padding-end"),
builder("-webkit-padding-start"),
builder("-webkit-perspective"),
builder("-webkit-perspective-origin"),
builder("-webkit-perspective-origin-x"),
builder("-webkit-perspective-origin-y"),
builder("-webkit-print-color-adjust"),
builder("-webkit-region-break-after"),
builder("-webkit-region-break-before"),
builder("-webkit-region-break-inside"),
builder("-webkit-region-overflow"),
builder("-webkit-rtl-ordering"),
builder("-webkit-svg-shadow"),
builder("-webkit-tap-highlight-color"),
builder("-webkit-text-decorations-in-effect"),
builder("-webkit-text-emphasis-position"),
builder("-webkit-text-fill-color"),
builder("-webkit-text-security"),
builder("-webkit-text-size-adjust"),
builder("-webkit-text-stroke"),
builder("-webkit-text-stroke-color"),
builder("-webkit-text-stroke-width"),
builder("-webkit-touch-callout"),
builder("-webkit-transform"),
builder("-webkit-transform-origin"),
builder("-webkit-transform-origin-x"),
builder("-webkit-transform-origin-y"),
builder("-webkit-transform-origin-z"),
builder("-webkit-transform-style"),
builder("-webkit-transition"),
builder("-webkit-transition-delay"),
builder("-webkit-transition-duration"),
builder("-webkit-transition-function"),
builder("-webkit-transition-property"),
builder("-webkit-transition-timing-function"),
builder("-webkit-user-drag"),
builder("-webkit-user-modify"),
builder("-webkit-user-select"),
builder("-webkit-wrap"),
builder("-webkit-wrap-flow"),
builder("-webkit-wrap-margin"),
builder("-webkit-wrap-padding"),
builder("-webkit-wrap-shape-inside"),
builder("-webkit-wrap-shape-outside"),
builder("-webkit-wrap-through"),
builder("white-space"),
builder("windows"),
builder("width"),
builder("word-break"),
builder("word-spacing"),
builder("word-wrap"),
builder("writing-mode").isSvgOnly(),
builder("z-index"),
builder("zoom").setVendor(Vendor.MICROSOFT)
);
ImmutableBiMap.Builder<String, Property> allProperies =
ImmutableBiMap.builder();
for (Builder builder : recognizedProperties) {
Property property = builder.build();
allProperies.put(property.getName(), property);
}
NAME_TO_PROPERTY_MAP = allProperies.build();
}
private final String name;
private final Set<String> shorthands;
private final String partition;
@Nullable
private final Vendor vendor;
private final boolean hasPositionalParameters;
private final boolean isSvgOnly;
private final String warning;
private Property(String name,
Set<String> shorthands,
String partition,
@Nullable Vendor vendor,
boolean hasPositionDependentValues,
boolean isSvgOnly,
@Nullable String warning) {
Preconditions.checkArgument(name.equals(name.toLowerCase()),
"property name should be all lowercase: %s", name);
this.name = name;
this.shorthands = shorthands;
this.partition = partition;
this.vendor = vendor;
this.hasPositionalParameters = hasPositionDependentValues;
this.isSvgOnly = isSvgOnly;
this.warning = warning;
}
private static Property createUserDefinedProperty(String name) {
Preconditions.checkArgument(!NAME_TO_PROPERTY_MAP.containsKey(name));
Builder builder = builder(name);
return builder.build();
}
/**
* @return a {@code Property} with the specified {@code name}. If {@code name}
* corresponds to a recognized property, then the corresponding
* {@code Property} will be returned; otherwise, a new {@code Property}
* with the specified {@code name} will be created.
*/
public static Property byName(String name) {
Property property = NAME_TO_PROPERTY_MAP.get(name);
if (property != null) {
return property;
} else {
return Property.createUserDefinedProperty(name);
}
}
/**
* @return the name of this CSS property as it appears in a stylesheet, such
* as "z-index"
*/
public String getName() {
return name;
}
/**
* @return whether this Property is recognized by default by the CSS Compiler.
* Note that this is not the same as a being a "standard" CSS property
* because the CSS Compiler recognizes non-standard CSS properties such as
* "-webkit-border-radius", among others.
*/
public boolean isRecognizedProperty() {
return NAME_TO_PROPERTY_MAP.containsKey(name);
}
/**
* Returns the set of shorthand properties related to this property, or the
* empty set if this property is not standard.
*
* <p>For example, {@code border-left-style} has {@code border},
* {@code border-left} and {@code border-style} as shorthands.
*/
public Set<String> getShorthands() {
return shorthands;
}
/**
* Gets the partition of this property. All properties with the same partition
* share a common shorthand. A non-standard property is its own single
* partition.
* <p>
* For example, {@code padding}, {@code padding-bottom}, {@code padding-left},
* {@code padding-right}, {@code padding-top} are all in the {@code padding}
* partition. As another example, {@code z-index} is its own single partition.
*
* @return a string representing the partition
*/
public String getPartition() {
return partition;
}
/**
* @return whether this Property is a vendor-specific CSS property, such as
* "-webkit-border-radius"
*/
public boolean isVendorSpecific() {
return vendor != null;
}
/**
* @return the corresponding {@link Vendor} if {@link #isVendorSpecific()}
* returns {@code true}; otherwise, returns {@code null}
*/
public @Nullable Vendor getVendor() {
return vendor;
}
/**
* @return whether this property can take positional parameters, such as
* "margin", where the parameters "1px 2px 3px" imply "1px 2px 3px 2px"
*/
public boolean hasPositionalParameters() {
return hasPositionalParameters;
}
public boolean isSvgOnly() {
return isSvgOnly;
}
public boolean hasWarning() {
return warning != null;
}
public String getWarning() {
return warning;
}
/**
* @return an immutable set of CSS properties recognized by default by the CSS
* Compiler
*/
public static Set<String> allRecognizedPropertyNames() {
return NAME_TO_PROPERTY_MAP.keySet();
}
/**
* @return an immutable set of {@link Property} instances recognized by default by the
* CSS Compiler
*/
public static Set<Property> allRecognizedProperties() {
return NAME_TO_PROPERTY_MAP.values();
}
private static Builder builder(String name) {
return new Builder(name);
}
/**
* For now, this class is private. If it turns out there is a legitimate need
* to create properties through a public builder (a need that cannot be met
* by {@link Property#byName(String)}), then this class should be changed so
* that it is public.
*/
@VisibleForTesting
static final class Builder {
private final String name;
private final Set<String> shorthands;
private final String partition;
private Vendor vendor;
private boolean hasPositionalParameters;
private boolean isSvgOnly;
private String warning;
private Builder(String name) {
Preconditions.checkNotNull(name);
this.name = name;
this.shorthands = computeShorthandPropertiesFor(name);
this.partition = Iterables.getFirst(this.shorthands, name);
this.vendor = Vendor.parseProperty(name);
this.hasPositionalParameters = false;
this.isSvgOnly = false;
this.warning = null;
}
public Property build() {
return new Property(
this.name,
this.shorthands,
this.partition,
this.vendor,
this.hasPositionalParameters,
this.isSvgOnly,
this.warning);
}
public Builder setVendor(Vendor vendor) {
this.vendor = vendor;
return this;
}
public Builder setHasPositionalParameters(boolean hasPositionalParameters) {
this.hasPositionalParameters = hasPositionalParameters;
return this;
}
/**
* Indicates that the property is relevant only when styling SVG, but not
* HTML.
*/
public Builder isSvgOnly() {
this.isSvgOnly = true;
return this;
}
/**
* @param warning to display when this property is referenced
*/
public Builder warn(String warning) {
this.warning = warning;
return this;
}
/**
* The set of all standard shorthand properties.
*/
private static final Set<String> SHORTHAND_PROPERTIES = ImmutableSet.of(
"background",
"border",
"border-bottom",
"border-color",
"border-left",
"border-right",
"border-style",
"border-top",
"border-width",
"font",
"list-style",
"margin",
"outline",
"padding",
"pause");
/**
* The set of standard properties that seem to have shorthands as defined by
* {@link #computeShorthandPropertiesFor}, but don't.
*/
private static final Set<String> NO_SHORTHAND = ImmutableSet.of(
"border-collapse",
"border-spacing");
private static final Map<String, String> BORDER_RADIUS_PROPERTIES =
ImmutableMap.<String, String>builder()
.put("border-radius", "border-radius")
.put("border-top-left-radius", "border-radius")
.put("border-top-right-radius", "border-radius")
.put("border-bottom-right-radius", "border-radius")
.put("border-bottom-left-radius", "border-radius")
.put("-webkit-border-radius", "-webkit-border-radius")
.put("-webkit-border-top-left-radius", "-webkit-border-radius")
.put("-webkit-border-top-right-radius", "-webkit-border-radius")
.put("-webkit-border-bottom-right-radius", "-webkit-border-radius")
.put("-webkit-border-bottom-left-radius", "-webkit-border-radius")
.put("-moz-border-radius", "-moz-border-radius")
.put("-moz-border-radius-topleft", "-moz-border-radius")
.put("-moz-border-radius-topright", "-moz-border-radius")
.put("-moz-border-radius-bottomright", "-moz-border-radius")
.put("-moz-border-radius-bottomleft", "-moz-border-radius")
.build();
/**
* Computes the set of shorthand properties for a given standard property.
*
* <p>As a first approximation, property 'x-y' would have 'x' as a
* shorthand, and property 'x-y-z' would have 'x', 'x-y' and 'x-z' as
* shorthands. However, at each stage , we also check that the shorthands
* computed as above are actually part of the given standard shorthand
* properties. If not, then we return without including them. Note that
* since we assume that the given shorthand properties are standard, only a
* border-related shorthand such as 'border-left-color' can have three
* shorthands. All other properties have either zero or one shorthand.
*
* @param property the given standard property
* @return the set of shorthands of the given property (not including the
* property itself if it is a shorthand), a subset of the given set of
* standard shorthand properties
*/
private static ImmutableSet<String> computeShorthandPropertiesFor(
String property) {
if (NO_SHORTHAND.contains(property)) {
return ImmutableSet.of();
}
int lastHyphenIndex = property.lastIndexOf('-');
if (lastHyphenIndex == -1) {
return ImmutableSet.of();
}
// Special-case border-radius properties because they are particularly
// odd.
if (BORDER_RADIUS_PROPERTIES.keySet().contains(property)) {
return ImmutableSet.of(BORDER_RADIUS_PROPERTIES.get(property));
}
String possibleShorthand = property.substring(0, lastHyphenIndex);
if (!SHORTHAND_PROPERTIES.contains(possibleShorthand)) {
return ImmutableSet.of();
}
int butlastHyphenIndex = possibleShorthand.lastIndexOf('-');
if (butlastHyphenIndex == -1) {
return ImmutableSet.of(possibleShorthand);
}
String smallestShorthand = property.substring(0, butlastHyphenIndex);
if (!SHORTHAND_PROPERTIES.contains(smallestShorthand)) {
return ImmutableSet.of(possibleShorthand);
}
// Only border-related properties may have more than one shorthand,
// in which case they will have three shorthands.
Preconditions.checkArgument(smallestShorthand.equals("border"));
String otherShorthand =
smallestShorthand + property.substring(lastHyphenIndex);
Preconditions.checkArgument(SHORTHAND_PROPERTIES.contains(
otherShorthand), "%s is not a shorthand property for %s",
otherShorthand, property);
return ImmutableSet.of(
smallestShorthand, possibleShorthand, otherShorthand);
}
}
}
| src/com/google/common/css/compiler/ast/Property.java | /*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.css.compiler.ast;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.common.collect.BiMap;
import com.google.common.collect.ImmutableBiMap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.css.Vendor;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.annotation.Nullable;
/**
* An object that represents a CSS property. Although this class contains a
* large set of built-in properties (see {@link #allRecognizedProperties()}), it
* is a class rather than an enum so that it is possible to create properties
* that are not built-in. User agents will likely add support for new properties
* faster than we can add them to this list.
*
* @author [email protected] (Michael Bolin)
*/
public final class Property {
/**
* The CSS properties recognized by default by the CSS Compiler, indexed by
* name. Note that this includes non-standard properties, such as
* "-webkit-border-radius".
*/
private static final BiMap<String, Property> NAME_TO_PROPERTY_MAP;
static {
List<Builder> recognizedProperties = ImmutableList.of(
builder("alignment-baseline").isSvgOnly(),
builder("animation"),
builder("animation-delay"),
builder("animation-direction"),
builder("animation-duration"),
builder("animation-iteration-count"),
builder("animation-name"),
builder("animation-play-state"),
builder("animation-timing-function"),
builder("azimuth"),
builder("background-attachment"),
builder("background-clip"),
builder("background-color"),
builder("background-image"),
builder("background-origin"),
builder("background-position"),
builder("background-position-x"),
builder("background-position-y"),
builder("background-repeat"),
builder("background-size"),
builder("background"),
builder("baseline-shift").isSvgOnly(),
builder("border-collapse"),
builder("border-color").setHasPositionalParameters(true),
builder("border-spacing"),
builder("border-style").setHasPositionalParameters(true),
builder("border-top"),
builder("border-right"),
builder("border-bottom"),
builder("border-left"),
builder("border-top-color"),
builder("border-right-color"),
builder("border-bottom-color"),
builder("border-left-color"),
builder("border-top-style"),
builder("border-right-style"),
builder("border-bottom-style"),
builder("border-left-style"),
builder("border-top-width"),
builder("border-right-width"),
builder("border-bottom-width"),
builder("border-left-width"),
builder("border-width").setHasPositionalParameters(true),
builder("border-image"),
// None of border-radius, -webkit-border-radius, and -moz-border-radius
// have setHasPositionalParameters(true) because each can take up to 8
// values according to the spec, as it is possible to specify the length
// of the horizontal and vertical radii independently for each corner:
//
// http://www.w3.org/TR/css3-background/#the-border-radius
//
// TODO(bolinfest): This is going to require special handling when it
// comes to RTL flipping, which the current
// "setHasPositionalParameters()" does not take into account.
builder("border-radius"),
builder("border-top-left-radius"),
builder("border-top-right-radius"),
builder("border-bottom-right-radius"),
builder("border-bottom-left-radius"),
builder("border"),
builder("bottom"),
builder("box-align").warn(
"Spec'd but not supported yet."),
builder("box-flex"),
builder("box-orient"),
builder("box-pack").warn(
"Spec'd but not supported yet."),
builder("box-shadow"),
builder("box-sizing"),
builder("caption-side"),
builder("clear"),
builder("clip"),
builder("clip-path").isSvgOnly(),
builder("clip-rule").isSvgOnly(),
builder("color"),
builder("color-interpolation").isSvgOnly(),
builder("color-interpolation-filters").isSvgOnly(),
builder("color-profile").isSvgOnly(),
builder("color-rendering").isSvgOnly(),
builder("content"),
builder("counter-increment"),
builder("counter-reset"),
builder("cue-after"),
builder("cue-before"),
builder("cue"),
builder("cursor"),
builder("direction"),
builder("display"),
builder("dominant-baseline").isSvgOnly(),
builder("elevation"),
builder("empty-cells"),
builder("enable-background").isSvgOnly(),
builder("-epub-caption-side"),
builder("-epub-hyphens"),
builder("-epub-text-combine"),
builder("-epub-text-emphasis"),
builder("-epub-text-emphasis-color"),
builder("-epub-text-emphasis-style"),
builder("-epub-text-orientation"),
builder("-epub-text-transform"),
builder("-epub-word-break"),
builder("-epub-writing-mode"),
builder("fill").isSvgOnly(),
builder("fill-opacity").isSvgOnly(),
builder("fill-rule").isSvgOnly(),
// This is not a MICROSOFT-specific property because it is also an SVG
// property: http://www.w3.org/TR/SVG/styling.html
builder("filter"),
builder("flex"),
builder("float"),
builder("flood-color").isSvgOnly(),
builder("flood-opacity").isSvgOnly(),
builder("font"),
builder("font-family"),
builder("font-size"),
builder("font-size-adjust"),
builder("font-stretch"),
builder("font-style"),
builder("font-variant"),
builder("font-weight"),
builder("glyph-orientation-horizontal").isSvgOnly(),
builder("glyph-orientation-vertical").isSvgOnly(),
builder("height"),
builder("image-rendering").isSvgOnly(),
builder("kerning").isSvgOnly(),
builder("-khtml-user-select"),
builder("left"),
builder("letter-spacing"),
builder("lighting-color").isSvgOnly(),
builder("line-height"),
builder("list-style-image"),
builder("list-style-position"),
builder("list-style-type"),
builder("list-style"),
builder("margin-right"),
builder("margin-left"),
builder("margin-top"),
builder("margin-bottom"),
builder("margin").setHasPositionalParameters(true),
builder("marker").isSvgOnly(),
builder("marker-end").isSvgOnly(),
builder("marker-mid").isSvgOnly(),
builder("marker-start").isSvgOnly(),
builder("mask").isSvgOnly(),
builder("max-height"),
builder("max-width"),
builder("min-height"),
builder("min-width"),
builder("-moz-animation"),
builder("-moz-animation-delay"),
builder("-moz-animation-direction"),
builder("-moz-animation-duration"),
builder("-moz-animation-fill-mode"),
builder("-moz-animation-iteration-count"),
builder("-moz-animation-name"),
builder("-moz-animation-play-state"),
builder("-moz-animation-timing-function"),
builder("-moz-appearance"),
builder("-moz-backface-visibility"),
builder("-moz-background-clip"),
builder("-moz-background-inline-policy"),
builder("-moz-background-origin"),
builder("-moz-background-size"),
builder("-moz-binding"),
builder("-moz-border-bottom-colors"),
builder("-moz-border-end"),
builder("-moz-border-end-color"),
builder("-moz-border-end-style"),
builder("-moz-border-end-width"),
builder("-moz-border-image"),
builder("-moz-border-left-colors"),
builder("-moz-border-radius"),
builder("-moz-border-radius-topleft"),
builder("-moz-border-radius-topright"),
builder("-moz-border-radius-bottomright"),
builder("-moz-border-radius-bottomleft"),
builder("-moz-border-right-colors"),
builder("-moz-border-start"),
builder("-moz-border-start-color"),
builder("-moz-border-start-style"),
builder("-moz-border-start-width"),
builder("-moz-border-top-colors"),
builder("-moz-box-align"),
builder("-moz-box-direction"),
builder("-moz-box-flex"),
builder("-moz-box-ordinal-group"),
builder("-moz-box-orient"),
builder("-moz-box-pack"),
builder("-moz-box-shadow"),
builder("-moz-box-sizing"),
builder("-moz-column-count"),
builder("-moz-column-gap"),
builder("-moz-column-rule"),
builder("-moz-column-rule-color"),
builder("-moz-column-rule-style"),
builder("-moz-column-rule-width"),
builder("-moz-column-width"),
builder("-moz-columns"),
builder("-moz-flex"),
builder("-moz-float-edge"),
builder("-moz-font-feature-settings"),
builder("-moz-font-language-override"),
builder("-moz-force-broken-image-icon"),
builder("-moz-hyphens"),
builder("-moz-image-region"),
builder("-moz-margin-end"),
builder("-moz-margin-start"),
builder("-moz-opacity"),
builder("-moz-orient"),
builder("-moz-outline-radius"),
builder("-moz-outline-radius-bottomleft"),
builder("-moz-outline-radius-bottomright"),
builder("-moz-outline-radius-topleft"),
builder("-moz-outline-radius-topright"),
builder("-moz-padding-end"),
builder("-moz-padding-start"),
builder("-moz-perspective"),
builder("-moz-perspective-origin"),
builder("-moz-script-level"),
builder("-moz-script-min-size"),
builder("-moz-script-size-multiplier"),
builder("-moz-stack-sizing"),
builder("-moz-tab-size"),
builder("-moz-text-blink"),
builder("-moz-text-decoration-color"),
builder("-moz-text-decoration-line"),
builder("-moz-text-decoration-style"),
builder("-moz-text-size-adjust"),
builder("-moz-transform"),
builder("-moz-transform-origin"),
builder("-moz-transform-style"),
builder("-moz-transition"),
builder("-moz-transition-delay"),
builder("-moz-transition-duration"),
builder("-moz-transition-property"),
builder("-moz-transition-timing-function"),
builder("-moz-user-focus"),
builder("-moz-user-input"),
builder("-moz-user-modify"),
builder("-moz-user-select"),
builder("-moz-window-shadow"),
builder("-ms-accelerator"),
builder("-ms-animation"),
builder("-ms-animation-delay"),
builder("-ms-animation-direction"),
builder("-ms-animation-duration"),
builder("-ms-animation-fill-mode"),
builder("-ms-animation-iteration-count"),
builder("-ms-animation-name"),
builder("-ms-animation-play-state"),
builder("-ms-animation-timing-function"),
builder("-ms-background-position-x"),
builder("-ms-background-position-y"),
builder("-ms-behavior"),
builder("-ms-block-progression"),
builder("-ms-box-align"),
builder("-ms-box-direction"),
builder("-ms-box-flex"),
builder("-ms-box-line-progression"),
builder("-ms-box-lines"),
builder("-ms-box-ordinal-group"),
builder("-ms-box-orient"),
builder("-ms-box-pack"),
builder("-ms-box-shadow"),
builder("-ms-box-sizing"),
builder("-ms-filter"),
builder("-ms-flex"),
builder("-ms-grid-column"),
builder("-ms-grid-column-align"),
builder("-ms-grid-column-span"),
builder("-ms-grid-columns"),
builder("-ms-grid-layer"),
builder("-ms-grid-row"),
builder("-ms-grid-row-align"),
builder("-ms-grid-row-span"),
builder("-ms-grid-rows"),
builder("-ms-ime-mode"),
builder("-ms-interpolation-mode"),
builder("-ms-layout-flow"),
builder("-ms-layout-grid"),
builder("-ms-layout-grid-char"),
builder("-ms-layout-grid-line"),
builder("-ms-layout-grid-mode"),
builder("-ms-layout-grid-type"),
builder("-ms-line-break"),
builder("-ms-line-grid-mode"),
builder("-ms-overflow-x"),
builder("-ms-overflow-y"),
builder("-ms-scrollbar-arrow-color"),
builder("-ms-scrollbar-base-color"),
builder("-ms-scrollbar-darkshadow-color"),
builder("-ms-scrollbar-face-color"),
builder("-ms-scrollbar-highlight-color"),
builder("-ms-scrollbar-shadow-color"),
builder("-ms-scrollbar-track-color"),
builder("-ms-text-align-last"),
builder("-ms-text-autospace"),
builder("-ms-text-justify"),
builder("-ms-text-kashida-space"),
builder("-ms-text-overflow"),
builder("-ms-text-size-adjust"),
builder("-ms-text-underline-position"),
builder("-ms-transform"),
builder("-ms-transform-origin"),
builder("-ms-transition"),
builder("-ms-transition-delay"),
builder("-ms-transition-duration"),
builder("-ms-transition-property"),
builder("-ms-transition-timing-function"),
builder("-ms-user-select"),
builder("-ms-word-break"),
builder("-ms-word-wrap"),
builder("-ms-writing-mode"),
builder("-ms-zoom"),
builder("-o-animation"),
builder("-o-animation-delay"),
builder("-o-animation-direction"),
builder("-o-animation-duration"),
builder("-o-animation-fill-mode"),
builder("-o-animation-iteration-count"),
builder("-o-animation-name"),
builder("-o-animation-play-state"),
builder("-o-animation-timing-function"),
builder("-o-background-size"),
builder("-o-text-overflow"),
builder("-o-transform"),
builder("-o-transform-origin"),
builder("-o-transition"),
builder("-o-transition-delay"),
builder("-o-transition-duration"),
builder("-o-transition-property"),
builder("-o-transition-timing-function"),
builder("opacity"),
builder("orphans"),
builder("outline-color"),
builder("outline-offset"),
builder("outline-style"),
builder("outline-width"),
builder("outline"),
builder("overflow"),
builder("overflow-x"),
builder("overflow-y"),
builder("padding-top"),
builder("padding-right"),
builder("padding-bottom"),
builder("padding-left"),
builder("padding").setHasPositionalParameters(true),
builder("page-break-after"),
builder("page-break-before"),
builder("page-break-inside"),
builder("pause-after"),
builder("pause-before"),
builder("pause"),
builder("pitch-range"),
builder("pitch"),
builder("play-during"),
builder("pointer-events"),
builder("position"),
builder("quotes"),
builder("resize"),
builder("richness"),
builder("right"),
builder("scrollbar-3dlight-color"),
builder("scrollbar-arrow-color"),
builder("scrollbar-base-color"),
builder("scrollbar-darkshadow-color"),
builder("scrollbar-face-color"),
builder("scrollbar-highlight-color"),
builder("scrollbar-shadow-color"),
builder("scrollbar-track-color"),
builder("shape-rendering").isSvgOnly(),
builder("size"),
builder("speak-header"),
builder("speak-numeral"),
builder("speak-punctuation"),
builder("speak"),
builder("speech-rate"),
builder("src"), // Only for use within @font-face
builder("stop-color").isSvgOnly(),
builder("stop-opacity").isSvgOnly(),
builder("stress"),
builder("stroke").isSvgOnly(),
builder("stroke-dasharray").isSvgOnly(),
builder("stroke-dashoffset").isSvgOnly(),
builder("stroke-linecap").isSvgOnly(),
builder("stroke-linejoin").isSvgOnly(),
builder("stroke-miterlimit").isSvgOnly(),
builder("stroke-opacity").isSvgOnly(),
builder("stroke-width").isSvgOnly(),
builder("table-layout"),
builder("text-align"),
builder("text-anchor").isSvgOnly(),
builder("text-decoration"),
builder("text-indent"),
builder("text-overflow"),
builder("text-rendering").isSvgOnly(),
builder("text-shadow"),
builder("text-transform"),
builder("transform"),
builder("transform-origin"),
builder("transition-delay"),
builder("transition-duration"),
builder("transition-property"),
builder("transition-timing-function"),
builder("top"),
builder("transition"),
builder("unicode-bidi"),
builder("vertical-align"),
builder("visibility"),
builder("voice-family"),
builder("volume"),
builder("-webkit-animation"),
builder("-webkit-animation-delay"),
builder("-webkit-animation-direction"),
builder("-webkit-animation-duration"),
builder("-webkit-animation-fill-mode"),
builder("-webkit-animation-iteration-count"),
builder("-webkit-animation-name"),
builder("-webkit-animation-play-state"),
builder("-webkit-animation-timing-function"),
builder("-webkit-appearance"),
builder("-webkit-aspect-ratio"),
builder("-webkit-backface-visibility"),
builder("-webkit-background-clip"),
builder("-webkit-background-composite"),
builder("-webkit-background-origin"),
builder("-webkit-background-size"),
builder("-webkit-border-after"),
builder("-webkit-border-after-color"),
builder("-webkit-border-after-style"),
builder("-webkit-border-after-width"),
builder("-webkit-border-before"),
builder("-webkit-border-before-color"),
builder("-webkit-border-before-style"),
builder("-webkit-border-before-width"),
builder("-webkit-border-bottom-left-radius"),
builder("-webkit-border-bottom-right-radius"),
builder("-webkit-border-end"),
builder("-webkit-border-end-color"),
builder("-webkit-border-end-style"),
builder("-webkit-border-end-width"),
builder("-webkit-border-fit"),
builder("-webkit-border-horizontal-spacing"),
builder("-webkit-border-image"),
builder("-webkit-border-radius"),
builder("-webkit-border-start"),
builder("-webkit-border-start-color"),
builder("-webkit-border-start-style"),
builder("-webkit-border-start-width"),
builder("-webkit-border-top-left-radius"),
builder("-webkit-border-top-right-radius"),
builder("-webkit-border-vertical-spacing"),
builder("-webkit-box-align"),
builder("-webkit-box-direction"),
builder("-webkit-box-flex"),
builder("-webkit-box-flex-group"),
builder("-webkit-box-lines"),
builder("-webkit-box-ordinal-group"),
builder("-webkit-box-orient"),
builder("-webkit-box-pack"),
builder("-webkit-box-reflect"),
builder("-webkit-box-shadow"),
builder("-webkit-box-sizing"),
builder("-webkit-color-correction"),
builder("-webkit-column-axis"),
builder("-webkit-column-break-after"),
builder("-webkit-column-break-before"),
builder("-webkit-column-break-inside"),
builder("-webkit-column-count"),
builder("-webkit-column-gap"),
builder("-webkit-column-rule"),
builder("-webkit-column-rule-color"),
builder("-webkit-column-rule-style"),
builder("-webkit-column-rule-width"),
builder("-webkit-column-span"),
builder("-webkit-column-width"),
builder("-webkit-columns"),
builder("-webkit-dashboard-region"),
builder("-webkit-filter"),
builder("-webkit-flex"),
builder("-webkit-flex-align"),
builder("-webkit-flex-direction"),
builder("-webkit-flex-flow"),
builder("-webkit-flex-order"),
builder("-webkit-flex-pack"),
builder("-webkit-flex-wrap"),
builder("-webkit-flow-from"),
builder("-webkit-flow-into"),
builder("-webkit-font-feature-settings"),
builder("-webkit-font-size-delta"),
builder("-webkit-font-smoothing"),
builder("-webkit-grid-columns"),
builder("-webkit-grid-rows"),
builder("-webkit-highlight"),
builder("-webkit-hyphenate-character"),
builder("-webkit-hyphenate-limit-after"),
builder("-webkit-hyphenate-limit-before"),
builder("-webkit-hyphenate-limit-lines"),
builder("-webkit-line-box-contain"),
builder("-webkit-line-break"),
builder("-webkit-line-clamp"),
builder("-webkit-line-grid"),
builder("-webkit-line-grid-snap"),
builder("-webkit-locale"),
builder("-webkit-logical-height"),
builder("-webkit-logical-width"),
builder("-webkit-margin-after"),
builder("-webkit-margin-after-collapse"),
builder("-webkit-margin-before"),
builder("-webkit-margin-before-collapse"),
builder("-webkit-margin-bottom-collapse"),
builder("-webkit-margin-collapse"),
builder("-webkit-margin-end"),
builder("-webkit-margin-start"),
builder("-webkit-margin-top-collapse"),
builder("-webkit-marquee"),
builder("-webkit-marquee-direction"),
builder("-webkit-marquee-increment"),
builder("-webkit-marquee-repetition"),
builder("-webkit-marquee-speed"),
builder("-webkit-marquee-style"),
builder("-webkit-mask"),
builder("-webkit-mask-attachment"),
builder("-webkit-mask-box-image"),
builder("-webkit-mask-box-image-outset"),
builder("-webkit-mask-box-image-repeat"),
builder("-webkit-mask-box-image-slice"),
builder("-webkit-mask-box-image-source"),
builder("-webkit-mask-box-image-width"),
builder("-webkit-mask-clip"),
builder("-webkit-mask-composite"),
builder("-webkit-mask-image"),
builder("-webkit-mask-origin"),
builder("-webkit-mask-position"),
builder("-webkit-mask-position-x"),
builder("-webkit-mask-position-y"),
builder("-webkit-mask-repeat"),
builder("-webkit-mask-repeat-x"),
builder("-webkit-mask-repeat-y"),
builder("-webkit-mask-size"),
builder("-webkit-match-nearest-mail-blockquote-color"),
builder("-webkit-max-logical-height"),
builder("-webkit-max-logical-width"),
builder("-webkit-min-logical-height"),
builder("-webkit-min-logical-width"),
builder("-webkit-nbsp-mode"),
builder("-webkit-opacity"),
builder("-webkit-overflow-scrolling"),
builder("-webkit-padding-after"),
builder("-webkit-padding-before"),
builder("-webkit-padding-end"),
builder("-webkit-padding-start"),
builder("-webkit-perspective"),
builder("-webkit-perspective-origin"),
builder("-webkit-perspective-origin-x"),
builder("-webkit-perspective-origin-y"),
builder("-webkit-print-color-adjust"),
builder("-webkit-region-break-after"),
builder("-webkit-region-break-before"),
builder("-webkit-region-break-inside"),
builder("-webkit-region-overflow"),
builder("-webkit-rtl-ordering"),
builder("-webkit-svg-shadow"),
builder("-webkit-tap-highlight-color"),
builder("-webkit-text-decorations-in-effect"),
builder("-webkit-text-emphasis-position"),
builder("-webkit-text-fill-color"),
builder("-webkit-text-security"),
builder("-webkit-text-size-adjust"),
builder("-webkit-text-stroke"),
builder("-webkit-text-stroke-color"),
builder("-webkit-text-stroke-width"),
builder("-webkit-touch-callout"),
builder("-webkit-transform"),
builder("-webkit-transform-origin"),
builder("-webkit-transform-origin-x"),
builder("-webkit-transform-origin-y"),
builder("-webkit-transform-origin-z"),
builder("-webkit-transform-style"),
builder("-webkit-transition"),
builder("-webkit-transition-delay"),
builder("-webkit-transition-duration"),
builder("-webkit-transition-function"),
builder("-webkit-transition-property"),
builder("-webkit-transition-timing-function"),
builder("-webkit-user-drag"),
builder("-webkit-user-modify"),
builder("-webkit-user-select"),
builder("-webkit-wrap"),
builder("-webkit-wrap-flow"),
builder("-webkit-wrap-margin"),
builder("-webkit-wrap-padding"),
builder("-webkit-wrap-shape-inside"),
builder("-webkit-wrap-shape-outside"),
builder("-webkit-wrap-through"),
builder("white-space"),
builder("windows"),
builder("width"),
builder("word-break"),
builder("word-spacing"),
builder("word-wrap"),
builder("writing-mode").isSvgOnly(),
builder("z-index"),
builder("zoom").setVendor(Vendor.MICROSOFT)
);
ImmutableBiMap.Builder<String, Property> allProperies =
ImmutableBiMap.builder();
for (Builder builder : recognizedProperties) {
Property property = builder.build();
allProperies.put(property.getName(), property);
}
NAME_TO_PROPERTY_MAP = allProperies.build();
}
private final String name;
private final Set<String> shorthands;
private final String partition;
@Nullable
private final Vendor vendor;
private final boolean hasPositionalParameters;
private final boolean isSvgOnly;
private final String warning;
private Property(String name,
Set<String> shorthands,
String partition,
@Nullable Vendor vendor,
boolean hasPositionDependentValues,
boolean isSvgOnly,
@Nullable String warning) {
Preconditions.checkArgument(name.equals(name.toLowerCase()),
"property name should be all lowercase: %s", name);
this.name = name;
this.shorthands = shorthands;
this.partition = partition;
this.vendor = vendor;
this.hasPositionalParameters = hasPositionDependentValues;
this.isSvgOnly = isSvgOnly;
this.warning = warning;
}
private static Property createUserDefinedProperty(String name) {
Preconditions.checkArgument(!NAME_TO_PROPERTY_MAP.containsKey(name));
Builder builder = builder(name);
return builder.build();
}
/**
* @return a {@code Property} with the specified {@code name}. If {@code name}
* corresponds to a recognized property, then the corresponding
* {@code Property} will be returned; otherwise, a new {@code Property}
* with the specified {@code name} will be created.
*/
public static Property byName(String name) {
Property property = NAME_TO_PROPERTY_MAP.get(name);
if (property != null) {
return property;
} else {
return Property.createUserDefinedProperty(name);
}
}
/**
* @return the name of this CSS property as it appears in a stylesheet, such
* as "z-index"
*/
public String getName() {
return name;
}
/**
* @return whether this Property is recognized by default by the CSS Compiler.
* Note that this is not the same as a being a "standard" CSS property
* because the CSS Compiler recognizes non-standard CSS properties such as
* "-webkit-border-radius", among others.
*/
public boolean isRecognizedProperty() {
return NAME_TO_PROPERTY_MAP.containsKey(name);
}
/**
* Returns the set of shorthand properties related to this property, or the
* empty set if this property is not standard.
*
* <p>For example, {@code border-left-style} has {@code border},
* {@code border-left} and {@code border-style} as shorthands.
*/
public Set<String> getShorthands() {
return shorthands;
}
/**
* Gets the partition of this property. All properties with the same partition
* share a common shorthand. A non-standard property is its own single
* partition.
* <p>
* For example, {@code padding}, {@code padding-bottom}, {@code padding-left},
* {@code padding-right}, {@code padding-top} are all in the {@code padding}
* partition. As another example, {@code z-index} is its own single partition.
*
* @return a string representing the partition
*/
public String getPartition() {
return partition;
}
/**
* @return whether this Property is a vendor-specific CSS property, such as
* "-webkit-border-radius"
*/
public boolean isVendorSpecific() {
return vendor != null;
}
/**
* @return the corresponding {@link Vendor} if {@link #isVendorSpecific()}
* returns {@code true}; otherwise, returns {@code null}
*/
public @Nullable Vendor getVendor() {
return vendor;
}
/**
* @return whether this property can take positional parameters, such as
* "margin", where the parameters "1px 2px 3px" imply "1px 2px 3px 2px"
*/
public boolean hasPositionalParameters() {
return hasPositionalParameters;
}
public boolean isSvgOnly() {
return isSvgOnly;
}
public boolean hasWarning() {
return warning != null;
}
public String getWarning() {
return warning;
}
/**
* @return an immutable set of CSS properties recognized by default by the CSS
* Compiler
*/
public static Set<String> allRecognizedPropertyNames() {
return NAME_TO_PROPERTY_MAP.keySet();
}
/**
* @return an immutable set of {@link Property} instances recognized by default by the
* CSS Compiler
*/
public static Set<Property> allRecognizedProperties() {
return NAME_TO_PROPERTY_MAP.values();
}
private static Builder builder(String name) {
return new Builder(name);
}
/**
* For now, this class is private. If it turns out there is a legitimate need
* to create properties through a public builder (a need that cannot be met
* by {@link Property#byName(String)}), then this class should be changed so
* that it is public.
*/
@VisibleForTesting
static final class Builder {
private final String name;
private final Set<String> shorthands;
private final String partition;
private Vendor vendor;
private boolean hasPositionalParameters;
private boolean isSvgOnly;
private String warning;
private Builder(String name) {
Preconditions.checkNotNull(name);
this.name = name;
this.shorthands = computeShorthandPropertiesFor(name);
this.partition = Iterables.getFirst(this.shorthands, name);
this.vendor = Vendor.parseProperty(name);
this.hasPositionalParameters = false;
this.isSvgOnly = false;
this.warning = null;
}
public Property build() {
return new Property(
this.name,
this.shorthands,
this.partition,
this.vendor,
this.hasPositionalParameters,
this.isSvgOnly,
this.warning);
}
public Builder setVendor(Vendor vendor) {
this.vendor = vendor;
return this;
}
public Builder setHasPositionalParameters(boolean hasPositionalParameters) {
this.hasPositionalParameters = hasPositionalParameters;
return this;
}
/**
* Indicates that the property is relevant only when styling SVG, but not
* HTML.
*/
public Builder isSvgOnly() {
this.isSvgOnly = true;
return this;
}
/**
* @param warning to display when this property is referenced
*/
public Builder warn(String warning) {
this.warning = warning;
return this;
}
/**
* The set of all standard shorthand properties.
*/
private static final Set<String> SHORTHAND_PROPERTIES = ImmutableSet.of(
"background",
"border",
"border-bottom",
"border-color",
"border-left",
"border-right",
"border-style",
"border-top",
"border-width",
"font",
"list-style",
"margin",
"outline",
"padding",
"pause");
/**
* The set of standard properties that seem to have shorthands as defined by
* {@link #computeShorthandPropertiesFor}, but don't.
*/
private static final Set<String> NO_SHORTHAND = ImmutableSet.of(
"border-collapse",
"border-spacing");
private static final Map<String, String> BORDER_RADIUS_PROPERTIES =
ImmutableMap.<String, String>builder()
.put("border-radius", "border-radius")
.put("border-top-left-radius", "border-radius")
.put("border-top-right-radius", "border-radius")
.put("border-bottom-right-radius", "border-radius")
.put("border-bottom-left-radius", "border-radius")
.put("-webkit-border-radius", "-webkit-border-radius")
.put("-webkit-border-top-left-radius", "-webkit-border-radius")
.put("-webkit-border-top-right-radius", "-webkit-border-radius")
.put("-webkit-border-bottom-right-radius", "-webkit-border-radius")
.put("-webkit-border-bottom-left-radius", "-webkit-border-radius")
.put("-moz-border-radius", "-moz-border-radius")
.put("-moz-border-radius-topleft", "-moz-border-radius")
.put("-moz-border-radius-topright", "-moz-border-radius")
.put("-moz-border-radius-bottomright", "-moz-border-radius")
.put("-moz-border-radius-bottomleft", "-moz-border-radius")
.build();
/**
* Computes the set of shorthand properties for a given standard property.
*
* <p>As a first approximation, property 'x-y' would have 'x' as a
* shorthand, and property 'x-y-z' would have 'x', 'x-y' and 'x-z' as
* shorthands. However, at each stage , we also check that the shorthands
* computed as above are actually part of the given standard shorthand
* properties. If not, then we return without including them. Note that
* since we assume that the given shorthand properties are standard, only a
* border-related shorthand such as 'border-left-color' can have three
* shorthands. All other properties have either zero or one shorthand.
*
* @param property the given standard property
* @return the set of shorthands of the given property (not including the
* property itself if it is a shorthand), a subset of the given set of
* standard shorthand properties
*/
private static ImmutableSet<String> computeShorthandPropertiesFor(
String property) {
if (NO_SHORTHAND.contains(property)) {
return ImmutableSet.of();
}
int lastHyphenIndex = property.lastIndexOf('-');
if (lastHyphenIndex == -1) {
return ImmutableSet.of();
}
// Special-case border-radius properties because they are particularly
// odd.
if (BORDER_RADIUS_PROPERTIES.keySet().contains(property)) {
return ImmutableSet.of(BORDER_RADIUS_PROPERTIES.get(property));
}
String possibleShorthand = property.substring(0, lastHyphenIndex);
if (!SHORTHAND_PROPERTIES.contains(possibleShorthand)) {
return ImmutableSet.of();
}
int butlastHyphenIndex = possibleShorthand.lastIndexOf('-');
if (butlastHyphenIndex == -1) {
return ImmutableSet.of(possibleShorthand);
}
String smallestShorthand = property.substring(0, butlastHyphenIndex);
if (!SHORTHAND_PROPERTIES.contains(smallestShorthand)) {
return ImmutableSet.of(possibleShorthand);
}
// Only border-related properties may have more than one shorthand,
// in which case they will have three shorthands.
Preconditions.checkArgument(smallestShorthand.equals("border"));
String otherShorthand =
smallestShorthand + property.substring(lastHyphenIndex);
Preconditions.checkArgument(SHORTHAND_PROPERTIES.contains(
otherShorthand), "%s is not a shorthand property for %s",
otherShorthand, property);
return ImmutableSet.of(
smallestShorthand, possibleShorthand, otherShorthand);
}
}
}
| Add two Webkit pseudo-properties to the property whitelist.
-------------
Created by MOE: http://code.google.com/p/moe-java
MOE_MIGRATED_REVID=42145918
| src/com/google/common/css/compiler/ast/Property.java | Add two Webkit pseudo-properties to the property whitelist. ------------- Created by MOE: http://code.google.com/p/moe-java MOE_MIGRATED_REVID=42145918 | <ide><path>rc/com/google/common/css/compiler/ast/Property.java
<ide> builder("visibility"),
<ide> builder("voice-family"),
<ide> builder("volume"),
<add> builder("-webkit-align-items"),
<add> builder("-webkit-align-self"),
<ide> builder("-webkit-animation"),
<ide> builder("-webkit-animation-delay"),
<ide> builder("-webkit-animation-direction"), |
|
JavaScript | mit | 4ef03fb2d8659489a325621ab73ed3195c34ee13 | 0 | draringi/codejam2013,draringi/codejam2013,draringi/codejam2013 | function updateChart (data) {
console.log(data);
var list = [];
var records = data.responseJSON.Records;
var len = records;
for (var i = 0; i < len; i++) {
list.push([records[i].Date, records[i].Power])
}
$.jqplot('futureplot', [list], {
title:'Predicted Power Usage for the next 24 Hours',
axes:{xaxis:{renderer:$.jqplot.DateAxisRenderer}},
series:[{lineWidth:4, markerOptions:{style:'square'}}]
});
}
function getData () {
$.getJSON("/data", updateChart);
}
| static/js/predictions.js | function updateChart (data) {
var list = [];
var records = data.responseJSON.Records;
var len = records;
for (var i = 0; i < len; i++) {
list.push([records[i].Date, records[i].Power])
}
$.jqplot('futureplot', [list], {
title:'Predicted Power Usage for the next 24 Hours',
axes:{xaxis:{renderer:$.jqplot.DateAxisRenderer}},
series:[{lineWidth:4, markerOptions:{style:'square'}}]
});
}
function getData () {
$.getJSON("/data", updateChart);
}
| js fixes
| static/js/predictions.js | js fixes | <ide><path>tatic/js/predictions.js
<ide> function updateChart (data) {
<add> console.log(data);
<ide> var list = [];
<ide> var records = data.responseJSON.Records;
<ide> var len = records; |
|
Java | apache-2.0 | error: pathspec 'src/org/ensembl/healthcheck/testcase/generic/CanonicalTranscriptCoding.java' did not match any file(s) known to git
| e89ce551ad18fd6754ece4fb4761b17375e04217 | 1 | Ensembl/ensj-healthcheck,thomasmaurel/ensj-healthcheck,thomasmaurel/ensj-healthcheck,thomasmaurel/ensj-healthcheck,Ensembl/ensj-healthcheck,thomasmaurel/ensj-healthcheck,Ensembl/ensj-healthcheck,Ensembl/ensj-healthcheck | /*
Copyright (C) 2004 EBI, GRL
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.ensembl.healthcheck.testcase.generic;
import java.sql.Connection;
import org.ensembl.healthcheck.DatabaseRegistryEntry;
import org.ensembl.healthcheck.ReportManager;
import org.ensembl.healthcheck.testcase.SingleDatabaseTestCase;
/**
* Check if protein_coding genes have a canonical transcript that has a valid translation. See also canonical_transcript checks in
* CoreForeignKeys.
*/
public class CanonicalTranscriptCoding extends SingleDatabaseTestCase {
/**
* Create a new instance of CanonicalTranscriptCoding.
*/
public CanonicalTranscriptCoding() {
addToGroup("release");
addToGroup("post_genebuild");
setDescription("Check if protein_coding genes have a canonical transcript that has a valid translation. See also canonical_transcript checks in CoreForeignKeys.");
setTeamResponsible("compara");
}
/**
* Run the test.
*
* @param dbre
* The database to use.
* @return true if the test passed.
*
*/
public boolean run(DatabaseRegistryEntry dbre) {
boolean result = true;
Connection con = dbre.getConnection();
int rows = getRowCount(con, "SELECT COUNT(*) FROM gene g LEFT JOIN translation tr ON g.canonical_transcript_id=tr.transcript_id WHERE g.biotype='protein_coding' AND tr.transcript_id IS NULL");
if (rows > 0) {
result = false;
ReportManager.problem(this, con, rows + " protein_coding genes have canonical transcripts that do not have valid translations");
} else {
ReportManager.correct(this, con, "All protein_coding genes have canonical_transcripts that translate");
}
return result;
} // run
} // CanonicalTranscriptCoding
| src/org/ensembl/healthcheck/testcase/generic/CanonicalTranscriptCoding.java | Check for protein coding genes with invalid translations
| src/org/ensembl/healthcheck/testcase/generic/CanonicalTranscriptCoding.java | Check for protein coding genes with invalid translations | <ide><path>rc/org/ensembl/healthcheck/testcase/generic/CanonicalTranscriptCoding.java
<add>/*
<add> Copyright (C) 2004 EBI, GRL
<add>
<add> This library is free software; you can redistribute it and/or
<add> modify it under the terms of the GNU Lesser General Public
<add> License as published by the Free Software Foundation; either
<add> version 2.1 of the License, or (at your option) any later version.
<add>
<add> This library is distributed in the hope that it will be useful,
<add> but WITHOUT ANY WARRANTY; without even the implied warranty of
<add> MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
<add> Lesser General Public License for more details.
<add>
<add> You should have received a copy of the GNU Lesser General Public
<add> License along with this library; if not, write to the Free Software
<add> Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
<add> */
<add>
<add>package org.ensembl.healthcheck.testcase.generic;
<add>
<add>import java.sql.Connection;
<add>
<add>import org.ensembl.healthcheck.DatabaseRegistryEntry;
<add>import org.ensembl.healthcheck.ReportManager;
<add>import org.ensembl.healthcheck.testcase.SingleDatabaseTestCase;
<add>
<add>/**
<add> * Check if protein_coding genes have a canonical transcript that has a valid translation. See also canonical_transcript checks in
<add> * CoreForeignKeys.
<add> */
<add>public class CanonicalTranscriptCoding extends SingleDatabaseTestCase {
<add>
<add> /**
<add> * Create a new instance of CanonicalTranscriptCoding.
<add> */
<add> public CanonicalTranscriptCoding() {
<add>
<add> addToGroup("release");
<add> addToGroup("post_genebuild");
<add> setDescription("Check if protein_coding genes have a canonical transcript that has a valid translation. See also canonical_transcript checks in CoreForeignKeys.");
<add> setTeamResponsible("compara");
<add>
<add> }
<add>
<add> /**
<add> * Run the test.
<add> *
<add> * @param dbre
<add> * The database to use.
<add> * @return true if the test passed.
<add> *
<add> */
<add> public boolean run(DatabaseRegistryEntry dbre) {
<add>
<add> boolean result = true;
<add>
<add> Connection con = dbre.getConnection();
<add>
<add> int rows = getRowCount(con, "SELECT COUNT(*) FROM gene g LEFT JOIN translation tr ON g.canonical_transcript_id=tr.transcript_id WHERE g.biotype='protein_coding' AND tr.transcript_id IS NULL");
<add>
<add> if (rows > 0) {
<add>
<add> result = false;
<add> ReportManager.problem(this, con, rows + " protein_coding genes have canonical transcripts that do not have valid translations");
<add>
<add> } else {
<add>
<add> ReportManager.correct(this, con, "All protein_coding genes have canonical_transcripts that translate");
<add> }
<add>
<add> return result;
<add>
<add> } // run
<add>
<add>} // CanonicalTranscriptCoding |
|
Java | bsd-2-clause | 2a1c3b160202e7bcdf7e54c67847adbc9795e289 | 0 | clementval/claw-compiler,clementval/claw-compiler | /*
* This file is released under terms of BSD license
* See LICENSE file for more information
*/
package cx2x.translator.language;
import static org.junit.Assert.*;
import cx2x.translator.language.helper.accelerator.AcceleratorDirective;
import cx2x.translator.language.helper.accelerator.AcceleratorGenerator;
import cx2x.translator.language.helper.accelerator.AcceleratorHelper;
import cx2x.translator.language.helper.target.Target;
import cx2x.xcodeml.exception.IllegalDirectiveException;
import cx2x.xcodeml.xelement.Xpragma;
import helper.XmlHelper;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* JUnit test class for the CLAW language parser and information holding class.
*
* @author clementval
*/
public class ClawLanguageTest {
/**
* Test various input for the CLAW loop fusion directive.
*/
@Test
public void FusionTest(){
// Valid directives
analyzeValidClawLoopFusion("claw loop-fusion", null, false, 0);
analyzeValidClawLoopFusion("claw loop-fusion group(g1)", "g1", false, 0);
analyzeValidClawLoopFusion("claw loop-fusion group( g1 )", "g1", false, 0);
analyzeValidClawLoopFusion("claw loop-fusion group ( g1 ) ", "g1",
false, 0);
analyzeValidClawLoopFusion("claw loop-fusion group(g1) collapse(2)", "g1",
true, 2);
analyzeValidClawLoopFusion("claw loop-fusion group(g1) collapse(3)", "g1",
true, 3);
analyzeValidClawLoopFusion("claw loop-fusion collapse(2)", null,
true, 2);
analyzeValidClawLoopFusion("claw loop-fusion collapse(3)", null,
true, 3);
// Unvalid directives
analyzeUnvalidClawLanguage("claw loop-fusiongroup(g1)");
analyzeUnvalidClawLanguage("claw loop-fusion group");
analyzeUnvalidClawLanguage("claw loop-fusion (i,j,k)");
analyzeUnvalidClawLanguage("claw loop-fusion group()");
analyzeUnvalidClawLanguage("claw loop-fusion group( )");
}
/**
* Assert the result for valid loop fusion CLAW directive
* @param raw Raw string value of the CLAW directive to be analyzed.
* @param groupName Group name to be found if any.
*/
private void analyzeValidClawLoopFusion(String raw, String groupName,
boolean collapse, int n){
try {
Xpragma p = XmlHelper.createXpragma();
p.setValue(raw);
AcceleratorGenerator generator =
AcceleratorHelper.
createAcceleratorGenerator(AcceleratorDirective.OPENACC);
ClawLanguage l = ClawLanguage.analyze(p, generator, Target.GPU);
assertEquals(ClawDirective.LOOP_FUSION, l.getDirective());
if(groupName != null){
assertTrue(l.hasGroupClause());
assertEquals(groupName, l.getGroupValue());
} else {
assertFalse(l.hasGroupClause());
assertNull(l.getGroupValue());
}
if(collapse){
assertTrue(l.hasCollapseClause());
assertEquals(n, l.getCollapseValue());
} else {
assertFalse(l.hasCollapseClause());
}
} catch(IllegalDirectiveException idex){
fail();
}
}
/**
* Assert any unvalid claw raw input
* @param raw Raw string value of the CLAW directive to be analyzed.
*/
private void analyzeUnvalidClawLanguage(String raw){
try {
Xpragma p = XmlHelper.createXpragma();
p.setValue(raw);
AcceleratorGenerator generator =
AcceleratorHelper.
createAcceleratorGenerator(AcceleratorDirective.OPENACC);
ClawLanguage.analyze(p, generator, Target.GPU);
fail();
} catch (IllegalDirectiveException pex){
assertNotNull(pex);
assertNotNull(pex.getMessage());
}
}
/**
* Test various input for the CLAW loop interchange directive.
*/
@Test
public void InterchangeTest(){
// Valid directives
analyzeValidClawLoopInterchange("claw loop-interchange", null, false, null);
analyzeValidClawLoopInterchange("claw loop-interchange (i,j,k)",
Arrays.asList("i", "j", "k"), false, null);
analyzeValidClawLoopInterchange("claw loop-interchange ( i,j,k ) ",
Arrays.asList("i", "j", "k"), false, null);
analyzeValidClawLoopInterchange("claw loop-interchange parallel",
null, true, null);
analyzeValidClawLoopInterchange("claw loop-interchange parallel acc(loop)",
null, true, "loop");
analyzeValidClawLoopInterchange("claw loop-interchange acc(loop)", null,
false, "loop");
analyzeValidClawLoopInterchange("claw loop-interchange (j,k,i) parallel",
Arrays.asList("j", "k", "i"), true, null);
// Unvalid directives
analyzeUnvalidClawLanguage("claw loop-interchange ()");
analyzeUnvalidClawLanguage("claw loop-interchange (i,j,k) group");
}
/**
* Assert the result for valid loop interchange CLAW directive
* @param raw Raw string value of the CLAW directive to be analyzed.
* @param indexes List of indexes to be found if any.
*/
private void analyzeValidClawLoopInterchange(String raw,
List<String> indexes,
boolean parallel,
String acc)
{
try {
Xpragma p = XmlHelper.createXpragma();
p.setValue(raw);
AcceleratorGenerator generator =
AcceleratorHelper.
createAcceleratorGenerator(AcceleratorDirective.OPENACC);
ClawLanguage l = ClawLanguage.analyze(p, generator, Target.GPU);
assertEquals(ClawDirective.LOOP_INTERCHANGE, l.getDirective());
if(indexes != null){
assertTrue(l.hasIndexes());
assertEquals(indexes.size(), l.getIndexes().size());
} else {
assertFalse(l.hasIndexes());
assertNull(l.getIndexes());
}
if(parallel){
assertTrue(l.hasParallelClause());
} else {
assertFalse(l.hasParallelClause());
}
if(acc != null){
assertTrue(l.hasAcceleratorClause());
assertEquals(acc, l.getAcceleratorClauses());
} else {
assertFalse(l.hasAcceleratorClause());
assertNull(l.getAcceleratorClauses());
}
} catch(IllegalDirectiveException idex){
fail();
}
}
/**
* Test various input for the CLAW remove directive.
*/
@Test
public void RemoveTest(){
// Valid directives
analyzeValidSimpleClaw("claw remove", ClawDirective.REMOVE, false);
analyzeValidSimpleClaw("claw end remove", ClawDirective.REMOVE, true);
analyzeValidSimpleClaw("claw end remove ", ClawDirective.REMOVE, true);
// Unvalid directives
analyzeUnvalidClawLanguage("claw");
analyzeUnvalidClawLanguage("claw dummy");
analyzeUnvalidClawLanguage("claw end re move");
}
/**
* Assert the result for valid simple CLAW directive
* @param raw Raw string value of the CLAW directive to be analyzed.
* @param directive Directive to be match.
*/
private void analyzeValidSimpleClaw(String raw, ClawDirective directive,
boolean isEnd)
{
try {
Xpragma p = XmlHelper.createXpragma();
p.setValue(raw);
AcceleratorGenerator generator =
AcceleratorHelper.
createAcceleratorGenerator(AcceleratorDirective.OPENACC);
ClawLanguage l = ClawLanguage.analyze(p, generator, Target.GPU);
assertEquals(directive, l.getDirective());
if(isEnd){
assertTrue(l.isEndPragma());
} else {
assertFalse(l.isEndPragma());
}
} catch(IllegalDirectiveException idex){
fail();
}
}
/**
* Test various input for the CLAW loop extract directive.
*/
@Test
public void ExtractTest(){
// Valid directives
ClawLanguage l = analyzeValidClawLoopExtract(
"claw loop-extract range(i=istart,iend) map(i:j)", "i", "istart",
"iend", null);
assertNotNull(l);
assertEquals(1, l.getMappings().size());
assertNotNull(l.getMappings().get(0));
ClawMapping map = l.getMappings().get(0);
assertEquals(1, map.getMappedVariables().size());
assertEquals(1, map.getMappingVariables().size());
assertEquals("i", map.getMappedVariables().get(0).getArgMapping());
assertEquals("i", map.getMappedVariables().get(0).getFctMapping());
assertFalse(map.getMappedVariables().get(0).hasDifferentMappping());
assertEquals("j", map.getMappingVariables().get(0).getArgMapping());
assertEquals("j", map.getMappingVariables().get(0).getFctMapping());
assertFalse(map.getMappingVariables().get(0).hasDifferentMappping());
l = analyzeValidClawLoopExtract(
"claw loop-extract range(i=istart,iend,2) map(i:j)", "i", "istart",
"iend", "2");
assertNotNull(l);
map = l.getMappings().get(0);
assertEquals(1, map.getMappedVariables().size());
assertEquals(1, map.getMappingVariables().size());
assertEquals("i", map.getMappedVariables().get(0).getArgMapping());
assertEquals("i", map.getMappedVariables().get(0).getFctMapping());
assertFalse(map.getMappedVariables().get(0).hasDifferentMappping());
assertEquals("j", map.getMappingVariables().get(0).getArgMapping());
assertEquals("j", map.getMappingVariables().get(0).getFctMapping());
assertFalse(map.getMappingVariables().get(0).hasDifferentMappping());
l = analyzeValidClawLoopExtract("claw loop-extract range(i=1,10) map(i:j)",
"i", "1", "10", null);
assertNotNull(l);
map = l.getMappings().get(0);
assertEquals(1, map.getMappedVariables().size());
assertEquals(1, map.getMappingVariables().size());
assertEquals("i", map.getMappedVariables().get(0).getArgMapping());
assertEquals("i", map.getMappedVariables().get(0).getFctMapping());
assertFalse(map.getMappedVariables().get(0).hasDifferentMappping());
assertEquals("j", map.getMappingVariables().get(0).getArgMapping());
assertEquals("j", map.getMappingVariables().get(0).getFctMapping());
assertFalse(map.getMappingVariables().get(0).hasDifferentMappping());
l = analyzeValidClawLoopExtract(
"claw loop-extract range(i=1,10,2) map(i:j) parallel", "i", "1", "10", "2");
assertNotNull(l);
map = l.getMappings().get(0);
assertTrue(l.hasParallelClause());
assertEquals(1, map.getMappedVariables().size());
assertEquals(1, map.getMappingVariables().size());
assertEquals("i", map.getMappedVariables().get(0).getArgMapping());
assertEquals("i", map.getMappedVariables().get(0).getFctMapping());
assertFalse(map.getMappedVariables().get(0).hasDifferentMappping());
assertEquals("j", map.getMappingVariables().get(0).getArgMapping());
assertEquals("j", map.getMappingVariables().get(0).getFctMapping());
assertFalse(map.getMappingVariables().get(0).hasDifferentMappping());
l = analyzeValidClawLoopExtract(
"claw loop-extract range(i=istart,iend) map(i:j) fusion", "i", "istart",
"iend", null);
assertNotNull(l);
assertEquals(1, l.getMappings().size());
assertNotNull(l.getMappings().get(0));
assertTrue(l.hasFusionClause());
assertFalse(l.hasGroupClause());
assertFalse(l.hasParallelClause());
map = l.getMappings().get(0);
assertEquals(1, map.getMappedVariables().size());
assertEquals(1, map.getMappingVariables().size());
assertEquals("i", map.getMappedVariables().get(0).getArgMapping());
assertEquals("i", map.getMappedVariables().get(0).getFctMapping());
assertFalse(map.getMappedVariables().get(0).hasDifferentMappping());
assertEquals("j", map.getMappingVariables().get(0).getArgMapping());
assertEquals("j", map.getMappingVariables().get(0).getFctMapping());
assertFalse(map.getMappingVariables().get(0).hasDifferentMappping());
l = analyzeValidClawLoopExtract(
"claw loop-extract range(i=istart,iend) map(i:j) fusion group(j1)",
"i", "istart", "iend", null);
assertNotNull(l);
assertEquals(1, l.getMappings().size());
assertNotNull(l.getMappings().get(0));
assertTrue(l.hasFusionClause());
assertTrue(l.hasGroupClause());
assertEquals("j1", l.getGroupValue());
map = l.getMappings().get(0);
assertEquals(1, map.getMappedVariables().size());
assertEquals(1, map.getMappingVariables().size());
assertEquals("i", map.getMappedVariables().get(0).getArgMapping());
assertEquals("i", map.getMappedVariables().get(0).getFctMapping());
assertFalse(map.getMappedVariables().get(0).hasDifferentMappping());
assertEquals("j", map.getMappingVariables().get(0).getArgMapping());
assertEquals("j", map.getMappingVariables().get(0).getFctMapping());
assertFalse(map.getMappingVariables().get(0).hasDifferentMappping());
l = analyzeValidClawLoopExtract(
"claw loop-extract range(i=istart,iend) map(i:j) fusion group(j1) " +
"acc(loop gang vector)", "i", "istart", "iend", null);
assertNotNull(l);
assertEquals(1, l.getMappings().size());
assertNotNull(l.getMappings().get(0));
assertTrue(l.hasFusionClause());
assertTrue(l.hasGroupClause());
assertTrue(l.hasAcceleratorClause());
assertEquals("loop gang vector", l.getAcceleratorClauses());
assertEquals("j1", l.getGroupValue());
map = l.getMappings().get(0);
assertEquals(1, map.getMappedVariables().size());
assertEquals(1, map.getMappingVariables().size());
assertEquals("i", map.getMappedVariables().get(0).getArgMapping());
assertEquals("i", map.getMappedVariables().get(0).getFctMapping());
assertFalse(map.getMappedVariables().get(0).hasDifferentMappping());
assertEquals("j", map.getMappingVariables().get(0).getArgMapping());
assertEquals("j", map.getMappingVariables().get(0).getFctMapping());
assertFalse(map.getMappingVariables().get(0).hasDifferentMappping());
l = analyzeValidClawLoopExtract(
"claw loop-extract range(j1=ki1sc,ki1ec) " +
"map(pduh2oc,pduh2of:j1,ki3sc/j3) " +
"map(pduco2,pduo3,palogp,palogt,podsc,podsf,podac,podaf:j1,ki3sc/j3) " +
"map(pbsff,pbsfc:j1,ki3sc/j3) map(pa1c,pa1f,pa2c,pa2f,pa3c,pa3f:j1) " +
"fusion group(coeth-j1) parallel acc(loop gang vector)",
"j1", "ki1sc", "ki1ec", null);
assertNotNull(l);
assertEquals(4, l.getMappings().size());
ClawMapping map1 = l.getMappings().get(0);
assertNotNull(map1);
assertEquals(2, map1.getMappedVariables().size());
assertEquals(2, map1.getMappingVariables().size());
assertEquals("pduh2oc", map1.getMappedVariables().get(0).getArgMapping());
assertEquals("pduh2oc", map1.getMappedVariables().get(0).getFctMapping());
assertEquals("pduh2of", map1.getMappedVariables().get(1).getArgMapping());
assertEquals("pduh2of", map1.getMappedVariables().get(1).getFctMapping());
assertEquals("j1", map1.getMappingVariables().get(0).getArgMapping());
assertEquals("j1", map1.getMappingVariables().get(0).getFctMapping());
assertEquals("ki3sc", map1.getMappingVariables().get(1).getArgMapping());
assertEquals("j3", map1.getMappingVariables().get(1).getFctMapping());
ClawMapping map2 = l.getMappings().get(1);
assertNotNull(map2);
assertEquals(8, map2.getMappedVariables().size());
assertEquals(2, map2.getMappingVariables().size());
assertEquals("pduco2", map2.getMappedVariables().get(0).getArgMapping());
assertEquals("pduco2", map2.getMappedVariables().get(0).getFctMapping());
assertEquals("pduo3", map2.getMappedVariables().get(1).getArgMapping());
assertEquals("pduo3", map2.getMappedVariables().get(1).getFctMapping());
assertEquals("palogp", map2.getMappedVariables().get(2).getArgMapping());
assertEquals("palogp", map2.getMappedVariables().get(2).getFctMapping());
assertEquals("palogt", map2.getMappedVariables().get(3).getArgMapping());
assertEquals("palogt", map2.getMappedVariables().get(3).getFctMapping());
assertEquals("podsc", map2.getMappedVariables().get(4).getArgMapping());
assertEquals("podsc", map2.getMappedVariables().get(4).getFctMapping());
assertEquals("podsf", map2.getMappedVariables().get(5).getArgMapping());
assertEquals("podsf", map2.getMappedVariables().get(5).getFctMapping());
assertEquals("podac", map2.getMappedVariables().get(6).getArgMapping());
assertEquals("podac", map2.getMappedVariables().get(6).getFctMapping());
assertEquals("podaf", map2.getMappedVariables().get(7).getArgMapping());
assertEquals("podaf", map2.getMappedVariables().get(7).getFctMapping());
assertEquals("j1", map2.getMappingVariables().get(0).getArgMapping());
assertEquals("j1", map2.getMappingVariables().get(0).getFctMapping());
assertEquals("ki3sc", map2.getMappingVariables().get(1).getArgMapping());
assertEquals("j3", map2.getMappingVariables().get(1).getFctMapping());
ClawMapping map3 = l.getMappings().get(2);
assertNotNull(map3);
assertEquals(2, map3.getMappedVariables().size());
assertEquals(2, map3.getMappingVariables().size());
assertEquals("pbsff", map3.getMappedVariables().get(0).getArgMapping());
assertEquals("pbsff", map3.getMappedVariables().get(0).getFctMapping());
assertEquals("pbsfc", map3.getMappedVariables().get(1).getArgMapping());
assertEquals("pbsfc", map3.getMappedVariables().get(1).getFctMapping());
assertEquals("j1", map3.getMappingVariables().get(0).getArgMapping());
assertEquals("j1", map3.getMappingVariables().get(0).getFctMapping());
assertEquals("ki3sc", map3.getMappingVariables().get(1).getArgMapping());
assertEquals("j3", map3.getMappingVariables().get(1).getFctMapping());
ClawMapping map4 = l.getMappings().get(3);
assertNotNull(map4);
assertEquals(6, map4.getMappedVariables().size());
assertEquals(1, map4.getMappingVariables().size());
assertEquals("pa1c", map4.getMappedVariables().get(0).getArgMapping());
assertEquals("pa1c", map4.getMappedVariables().get(0).getFctMapping());
assertEquals("pa1f", map4.getMappedVariables().get(1).getArgMapping());
assertEquals("pa1f", map4.getMappedVariables().get(1).getFctMapping());
assertEquals("pa2c", map4.getMappedVariables().get(2).getArgMapping());
assertEquals("pa2c", map4.getMappedVariables().get(2).getFctMapping());
assertEquals("pa2f", map4.getMappedVariables().get(3).getArgMapping());
assertEquals("pa2f", map4.getMappedVariables().get(3).getFctMapping());
assertEquals("pa3c", map4.getMappedVariables().get(4).getArgMapping());
assertEquals("pa3c", map4.getMappedVariables().get(4).getFctMapping());
assertEquals("pa3f", map4.getMappedVariables().get(5).getArgMapping());
assertEquals("pa3f", map4.getMappedVariables().get(5).getFctMapping());
assertEquals("j1", map4.getMappingVariables().get(0).getArgMapping());
assertEquals("j1", map4.getMappingVariables().get(0).getFctMapping());
assertTrue(l.hasFusionClause());
assertTrue(l.hasGroupClause());
assertEquals("coeth-j1", l.getGroupValue());
assertTrue(l.hasAcceleratorClause());
assertEquals("loop gang vector", l.getAcceleratorClauses());
// Unvalid directives
analyzeUnvalidClawLanguage("claw loop-extract");
analyzeUnvalidClawLanguage("claw loop - extract ");
}
/**
* Assert the result for valid loop extract CLAW directive
* @param raw Raw string value of the CLAW directive to be analyzed.
* @param induction Induction var to be found.
* @param lower Lower bound value to be found.
* @param upper Upper bound value to be found.
* @param step Step valu to be found if any.
*/
private ClawLanguage analyzeValidClawLoopExtract(String raw, String induction,
String lower, String upper,
String step)
{
try {
Xpragma p = XmlHelper.createXpragma();
p.setValue(raw);
AcceleratorGenerator generator =
AcceleratorHelper.
createAcceleratorGenerator(AcceleratorDirective.OPENACC);
ClawLanguage l = ClawLanguage.analyze(p, generator, Target.GPU);
assertEquals(ClawDirective.LOOP_EXTRACT, l.getDirective());
assertEquals(induction, l.getRange().getInductionVar());
assertEquals(lower, l.getRange().getLowerBound());
assertEquals(upper, l.getRange().getUpperBound());
if(step != null){
assertEquals(step, l.getRange().getStep());
}
return l;
} catch(IllegalDirectiveException idex){
System.err.println(idex.getMessage());
fail();
return null;
}
}
/**
* Test various input for the CLAW kcache directive.
*/
@Test
public void KcacheTest(){
// data clause + offsets
analyzeValidKcache("claw kcache data(var1,var2) offset(0,1)",
Arrays.asList("var1", "var2"), Arrays.asList(0, 1), false, false);
analyzeValidKcache("claw kcache data(var1,var2) offset(0,-1,0)",
Arrays.asList("var1", "var2"), Arrays.asList(0, -1, 0), false, false);
analyzeValidKcache("claw kcache data(var1,var2) offset(+1,-1,0)",
Arrays.asList("var1", "var2"), Arrays.asList(1, -1, 0), false, false);
analyzeValidKcache("claw kcache data(var1,var2) offset(+1,-1,0) private",
Arrays.asList("var1", "var2"), Arrays.asList(1, -1, 0), false, true);
analyzeValidKcache("claw kcache data(var1,var2) private",
Arrays.asList("var1", "var2"), null, false, true);
// offset + init clause
analyzeValidKcache("claw kcache data(var1,var2) offset(0,1) init",
Arrays.asList("var1", "var2"), Arrays.asList(0, 1), true, false);
analyzeValidKcache("claw kcache data(var1,var2) offset(0,-1,0) init",
Arrays.asList("var1", "var2"), Arrays.asList(0, -1, 0), true, false);
analyzeValidKcache("claw kcache data(var1,var2) offset(+1,-1,0) init",
Arrays.asList("var1", "var2"), Arrays.asList(1, -1, 0), true, false);
analyzeValidKcache("claw kcache data(var1,var2) offset(+1,-1,0) init private",
Arrays.asList("var1", "var2"), Arrays.asList(1, -1, 0), true, true);
analyzeValidKcache("claw kcache data(var1,var2) init private",
Arrays.asList("var1", "var2"), null, true, true);
// Unvalid directives
analyzeUnvalidClawLanguage("claw k cache ");
analyzeUnvalidClawLanguage("claw k-cache");
}
/**
* Assert the result for valid CLAW kcache directive
* @param raw Raw string value of the CLAW directive to be analyzed.
* @param data List of identifiers to be checked.
* @param offsets List of offsets to be checked.
* @param init If true, check that ClawLanguage object has init clause
* enabled.
*/
private void analyzeValidKcache(String raw, List<String> data,
List<Integer> offsets, boolean init,
boolean hasPrivate)
{
try {
Xpragma p = XmlHelper.createXpragma();
p.setValue(raw);
AcceleratorGenerator generator =
AcceleratorHelper.
createAcceleratorGenerator(AcceleratorDirective.OPENACC);
ClawLanguage l = ClawLanguage.analyze(p, generator, Target.GPU);
assertEquals(ClawDirective.KCACHE, l.getDirective());
if(data != null){
assertTrue(l.hasDataClause());
assertEquals(data.size(), l.getDataClauseValues().size());
for(int i = 0; i < data.size(); ++i){
assertEquals(data.get(i), l.getDataClauseValues().get(i));
}
} else {
assertFalse(l.hasDataClause());
}
if(offsets != null){
assertEquals(offsets.size(), l.getOffsets().size());
for(int i = 0; i < offsets.size(); ++i){
assertEquals(offsets.get(i), l.getOffsets().get(i));
}
}
if(init){
assertTrue(l.hasInitClause());
} else {
assertFalse(l.hasInitClause());
}
if(hasPrivate){
assertTrue(l.hasPrivateClause());
} else {
assertFalse(l.hasPrivateClause());
}
} catch(IllegalDirectiveException idex){
System.err.print(idex.getMessage());
fail();
}
}
/**
* Test various input for the CLAW array-transform directive.
*/
@Test
public void ArrayTransformTest(){
// Valid directives
analyzeValidArrayTransform("claw array-transform", false, null, false,
null, null);
analyzeValidArrayTransform("claw array-transform fusion", true, null, false,
null, null);
analyzeValidArrayTransform("claw array-transform fusion group(j1)", true,
"j1", false, null, null);
analyzeValidArrayTransform("claw array-transform fusion parallel", true,
null, true, null, null);
analyzeValidArrayTransform("claw array-transform fusion parallel acc(loop)",
true, null, true, "loop", null);
analyzeValidArrayTransform("claw array-transform fusion acc(loop)", true,
null, false, "loop", null);
analyzeValidArrayTransform(
"claw array-transform fusion parallel acc(loop gang vector)", true,
null, true, "loop gang vector", null);
analyzeValidArrayTransform(
"claw array-transform fusion group(j1) parallel acc(loop gang vector)",
true, "j1", true, "loop gang vector", null);
analyzeValidArrayTransform(
"claw array-transform parallel acc(loop gang vector)",
false, null, true, "loop gang vector", null);
analyzeValidArrayTransform("claw array-transform parallel", false, null,
true, null, null);
analyzeValidArrayTransform("claw array-transform acc(loop gang vector)",
false, null, false, "loop gang vector", null);
analyzeValidArrayTransform("claw array-transform induction(j1,j3)",
false, null, false, null, Arrays.asList("j1","j3"));
analyzeValidArrayTransform("claw array-transform induction(j1)",
false, null, false, null, Collections.singletonList("j1"));
analyzeValidArrayTransform("claw array-transform induction(i,j,k)",
false, null, false, null, Arrays.asList("i", "j", "k"));
analyzeUnvalidClawLanguage("claw array-transform induction()");
analyzeUnvalidClawLanguage("claw array-transform induction");
analyzeValidSimpleClaw("claw end array-transform",
ClawDirective.ARRAY_TRANSFORM, true);
analyzeValidSimpleClaw("claw end array-transform ",
ClawDirective.ARRAY_TRANSFORM, true);
}
/**
* Assert the result for valid CLAW array-transform directive
* @param raw Raw string value of the CLAW directive to be analyzed.
* @param fusion Set to true if the extracted option should be present.
* @param fusionGroup Name of the group in the extracted fusion option.
* @param parallel Set to true if the extracted option should be present.
* @param acc String of acc clauses that should be present.
*/
private void analyzeValidArrayTransform(String raw, boolean fusion,
String fusionGroup, boolean parallel,
String acc, List<String> inducNames)
{
try {
Xpragma p = XmlHelper.createXpragma();
p.setValue(raw);
AcceleratorGenerator generator =
AcceleratorHelper.
createAcceleratorGenerator(AcceleratorDirective.OPENACC);
ClawLanguage l = ClawLanguage.analyze(p, generator, Target.GPU);
assertEquals(ClawDirective.ARRAY_TRANSFORM, l.getDirective());
if(fusion){
assertTrue(l.hasFusionClause());
assertEquals(fusionGroup, l.getGroupValue());
} else {
assertFalse(l.hasFusionClause());
assertNull(l.getGroupValue());
}
if(parallel){
assertTrue(l.hasParallelClause());
} else {
assertFalse(l.hasParallelClause());
}
if(acc != null){
assertTrue(l.hasAcceleratorClause());
assertEquals(acc, l.getAcceleratorClauses());
} else {
assertFalse(l.hasAcceleratorClause());
}
if(inducNames != null){
assertTrue(l.hasInductionClause());
assertEquals(inducNames.size(), l.getInductionValues().size());
for(int i = 0; i < inducNames.size(); ++ i){
assertEquals(inducNames.get(i), l.getInductionValues().get(i));
}
} else {
assertFalse(l.hasInductionClause());
}
} catch(IllegalDirectiveException idex){
System.err.print(idex.getMessage());
fail();
}
}
/**
* Test various input for the CLAW loop-hoist directive.
*/
@Test
public void LoopHoistTest(){
// Valid directives
analyzeValidLoopHoist("claw loop-hoist(i,j)",
Arrays.asList("i", "j"), false, null, false, null);
analyzeValidLoopHoist("claw loop-hoist(i,j) interchange",
Arrays.asList("i", "j"), true, null, false, null);
analyzeValidLoopHoist("claw loop-hoist(i,j) interchange(j,i)",
Arrays.asList("i", "j"), true, Arrays.asList("j", "i"), false, null);
ClawReshapeInfo info1 = new ClawReshapeInfo("zmd", 0,
new ArrayList<Integer>());
ClawReshapeInfo info2 =
new ClawReshapeInfo("zsediflux", 1, Collections.singletonList(2));
analyzeValidLoopHoist("claw loop-hoist(i,j) reshape(zmd(0), zsediflux(1,2))",
Arrays.asList("i", "j"), false, null, true,
Arrays.asList(info1, info2));
// Unvalid directives
analyzeUnvalidClawLanguage("claw loop-hoist");
analyzeUnvalidClawLanguage("claw loop-hoist()");
analyzeUnvalidClawLanguage("claw loop-hoist(i,j) interchange()");
analyzeValidSimpleClaw("claw end loop-hoist",
ClawDirective.LOOP_HOIST, true);
analyzeValidSimpleClaw("claw end loop-hoist ",
ClawDirective.LOOP_HOIST, true);
}
/**
* Assert the result for valid CLAW loop-hoist directive
* @param raw Raw string value of the CLAW directive to be analyzed.
* @param inductions List of induction variables to be checked.
*/
private void analyzeValidLoopHoist(String raw, List<String> inductions,
boolean interchange, List<String> indexes,
boolean reshape,
List<ClawReshapeInfo> infos)
{
try {
Xpragma p = XmlHelper.createXpragma();
p.setValue(raw);
AcceleratorGenerator generator =
AcceleratorHelper.
createAcceleratorGenerator(AcceleratorDirective.OPENACC);
ClawLanguage l = ClawLanguage.analyze(p, generator, Target.GPU);
assertEquals(ClawDirective.LOOP_HOIST, l.getDirective());
assertEquals(inductions.size(), l.getHoistInductionVars().size());
for(int i = 0; i < inductions.size(); ++i){
assertEquals(inductions.get(i), l.getHoistInductionVars().get(i));
}
if(interchange){
assertTrue(l.hasInterchangeClause());
} else {
assertFalse(l.hasInterchangeClause());
}
if(indexes != null){
for(int i = 0; i < indexes.size(); ++i){
assertEquals(indexes.get(i), l.getIndexes().get(i));
}
}
if(reshape){
assertTrue(l.hasReshapeClause());
assertEquals(infos.size(), l.getReshapeClauseValues().size());
for(int i = 0; i < infos.size(); ++i){
assertEquals(infos.get(i).getArrayName(),
l.getReshapeClauseValues().get(i).getArrayName());
assertEquals(infos.get(i).getTargetDimension(),
l.getReshapeClauseValues().get(i).getTargetDimension());
List<Integer> expected = infos.get(i).getKeptDimensions();
List<Integer> actual =
l.getReshapeClauseValues().get(i).getKeptDimensions();
assertEquals(expected.size(), actual.size());
for(int j=0; j < expected.size(); ++j){
assertEquals(expected.get(j), actual.get(j));
}
}
} else {
assertFalse(l.hasReshapeClause());
}
} catch(IllegalDirectiveException idex){
System.err.print(idex.getMessage());
fail();
}
}
/**
* Test various input for the CLAW call directive.
*/
@Test
public void ArrayToFctCallTest(){
// Valid directives
analyzeValidArrayToFctCall("claw call var1=f_var1(i,j)", "var1", "f_var1",
Arrays.asList("i", "j"));
analyzeValidArrayToFctCall("claw call var1=f_var1(i)", "var1", "f_var1",
Collections.singletonList("i"));
analyzeValidArrayToFctCall("claw call v=f(i,j)", "v", "f",
Arrays.asList("i", "j"));
// Unvalid directives
analyzeUnvalidClawLanguage("claw call ");
analyzeUnvalidClawLanguage("claw call v=");
analyzeUnvalidClawLanguage("claw call v=()");
}
/**
* Assert the result for valid CLAW call directive
* @param raw Raw string value of the CLAW directive to be analyzed.
* @param arrayName Array name to be checked.
* @param fctName Function name to be checked.
* @param params List of parameters identifier to be checked.
*/
private void analyzeValidArrayToFctCall(String raw, String arrayName,
String fctName, List<String> params)
{
try {
Xpragma p = XmlHelper.createXpragma();
p.setValue(raw);
AcceleratorGenerator generator =
AcceleratorHelper.
createAcceleratorGenerator(AcceleratorDirective.OPENACC);
ClawLanguage l = ClawLanguage.analyze(p, generator, Target.GPU);
assertEquals(ClawDirective.ARRAY_TO_CALL, l.getDirective());
assertEquals(params.size(), l.getFctParams().size());
for(int i = 0; i < params.size(); ++i){
assertEquals(params.get(i), l.getFctParams().get(i));
}
assertEquals(arrayName, l.getArrayName());
assertEquals(fctName, l.getFctName());
} catch(IllegalDirectiveException idex){
System.err.print(idex.getMessage());
fail();
}
}
/**
* Test various input for the CLAW parallelize directive.
*/
@Test
public void parallelizeTest(){
// Valid directives
ClawDimension d1 = new ClawDimension("i", "1", "nx");
analyzeValidParallelize("claw define dimension i(1,nx)" +
" parallelize data(t,qc,qv) over (i,j,:)",
Arrays.asList("t", "qc", "qv"), Arrays.asList("i", "j", ":"),
Collections.singletonList(d1));
ClawDimension d2 = new ClawDimension("j", "1", "ny");
analyzeValidParallelize("claw define dimension j(1,ny)" +
"parallelize data(t,qc,qv) over (i,j,:)",
Arrays.asList("t", "qc", "qv"), Arrays.asList("i", "j", ":"),
Collections.singletonList(d2));
ClawDimension d3 = new ClawDimension("j", "1", "10");
analyzeValidParallelize("claw define dimension j(1,10) " +
"parallelize data(t,qc,qv) over (i,j,:)",
Arrays.asList("t", "qc", "qv"), Arrays.asList("i", "j", ":"),
Collections.singletonList(d3));
ClawDimension d4 = new ClawDimension("j", "jstart", "10");
analyzeValidParallelize("claw define dimension j(jstart,10) " +
"parallelize data(t,qc,qv) over (i,j,:)",
Arrays.asList("t", "qc", "qv"), Arrays.asList("i", "j", ":"),
Collections.singletonList(d4));
ClawDimension d5 = new ClawDimension("j", "jstart", "ny");
analyzeValidParallelize("claw define dimension j(jstart,ny) " +
"parallelize data(t,qc,qv) over (i,j,:)",
Arrays.asList("t", "qc", "qv"), Arrays.asList("i", "j", ":"),
Collections.singletonList(d5));
analyzeValidParallelize("claw parallelize data(t,qc,qv) over (i,j,:)",
Arrays.asList("t", "qc", "qv"), Arrays.asList("i", "j", ":"), null);
analyzeValidParallelize("claw parallelize data(t,qc,qv) over (:,i,j)",
Arrays.asList("t", "qc", "qv"), Arrays.asList(":", "i", "j"), null);
analyzeValidParallelize("claw parallelize data(t,qc,qv) over (i,:,j)",
Arrays.asList("t", "qc", "qv"), Arrays.asList("i", ":", "j"), null);
// Unvalid directives
analyzeUnvalidClawLanguage("claw parallelize over ");
analyzeUnvalidClawLanguage("claw parallelite data() over ()");
}
/**
* Assert the result for valid CLAW parallelize directive
* @param raw Raw string value of the CLAW directive to be analyzed.
* @param data Reference list for the data clause values.
* @param over Reference list for the over clause values.
* @param dimensions Reference list of dimensions.
*/
private void analyzeValidParallelize(String raw, List<String> data,
List<String> over,
List<ClawDimension> dimensions)
{
try {
Xpragma p = XmlHelper.createXpragma();
p.setValue(raw);
AcceleratorGenerator generator =
AcceleratorHelper.
createAcceleratorGenerator(AcceleratorDirective.OPENACC);
ClawLanguage l = ClawLanguage.analyze(p, generator, Target.GPU);
assertEquals(ClawDirective.PARALLELIZE, l.getDirective());
assertEquals(data.size(), l.getDataClauseValues().size());
assertEquals(over.size(), l.getOverClauseValues().size());
assertTrue(l.hasDataClause());
for(int i = 0; i < data.size(); ++i){
assertEquals(data.get(i), l.getDataClauseValues().get(i));
}
assertTrue(l.hasOverClause());
for(int i = 0; i < over.size(); ++i){
assertEquals(over.get(i), l.getOverClauseValues().get(i));
}
if(dimensions != null){
assertEquals(dimensions.size(), l.getDimesionValues().size());
for(int i = 0; i < dimensions.size(); ++i){
assertEquals(dimensions.get(i).getIdentifier(),
l.getDimesionValues().get(i).getIdentifier());
assertEquals(dimensions.get(i).lowerBoundIsVar(),
l.getDimesionValues().get(i).lowerBoundIsVar());
assertEquals(dimensions.get(i).upperBoundIsVar(),
l.getDimesionValues().get(i).upperBoundIsVar());
assertEquals(dimensions.get(i).getLowerBoundInt(),
l.getDimesionValues().get(i).getLowerBoundInt());
assertEquals(dimensions.get(i).getUpperBoundInt(),
l.getDimesionValues().get(i).getUpperBoundInt());
assertEquals(dimensions.get(i).getLowerBoundId(),
l.getDimesionValues().get(i).getLowerBoundId());
assertEquals(dimensions.get(i).getUpperBoundId(),
l.getDimesionValues().get(i).getUpperBoundId());
}
}
} catch(IllegalDirectiveException idex){
System.err.print(idex.getMessage());
fail();
}
}
@Test
public void ContinuationTest(){
String continuedPragma = "claw loop-fusion claw collapse(2)";
analyzeValidClawLoopFusion(continuedPragma, null, true, 2);
}
}
| omni-cx2x/unittest/cx2x/translator/language/ClawLanguageTest.java | /*
* This file is released under terms of BSD license
* See LICENSE file for more information
*/
package cx2x.translator.language;
import static org.junit.Assert.*;
import cx2x.translator.language.helper.accelerator.AcceleratorDirective;
import cx2x.translator.language.helper.accelerator.AcceleratorGenerator;
import cx2x.translator.language.helper.accelerator.AcceleratorHelper;
import cx2x.translator.language.helper.target.Target;
import cx2x.xcodeml.exception.IllegalDirectiveException;
import cx2x.xcodeml.xelement.Xpragma;
import helper.XmlHelper;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* JUnit test class for the CLAW language parser and information holding class.
*
* @author clementval
*/
public class ClawLanguageTest {
/**
* Test various input for the CLAW loop fusion directive.
*/
@Test
public void FusionTest(){
// Valid directives
analyzeValidClawLoopFusion("claw loop-fusion", null, false, 0);
analyzeValidClawLoopFusion("claw loop-fusion group(g1)", "g1", false, 0);
analyzeValidClawLoopFusion("claw loop-fusion group( g1 )", "g1", false, 0);
analyzeValidClawLoopFusion("claw loop-fusion group ( g1 ) ", "g1",
false, 0);
analyzeValidClawLoopFusion("claw loop-fusion group(g1) collapse(2)", "g1",
true, 2);
analyzeValidClawLoopFusion("claw loop-fusion group(g1) collapse(3)", "g1",
true, 3);
analyzeValidClawLoopFusion("claw loop-fusion collapse(2)", null,
true, 2);
analyzeValidClawLoopFusion("claw loop-fusion collapse(3)", null,
true, 3);
// Unvalid directives
analyzeUnvalidClawLanguage("claw loop-fusiongroup(g1)");
analyzeUnvalidClawLanguage("claw loop-fusion group");
analyzeUnvalidClawLanguage("claw loop-fusion (i,j,k)");
analyzeUnvalidClawLanguage("claw loop-fusion group()");
analyzeUnvalidClawLanguage("claw loop-fusion group( )");
}
/**
* Assert the result for valid loop fusion CLAW directive
* @param raw Raw string value of the CLAW directive to be analyzed.
* @param groupName Group name to be found if any.
*/
private void analyzeValidClawLoopFusion(String raw, String groupName,
boolean collapse, int n){
try {
Xpragma p = XmlHelper.createXpragma();
p.setValue(raw);
AcceleratorGenerator generator =
AcceleratorHelper.
createAcceleratorGenerator(AcceleratorDirective.OPENACC);
ClawLanguage l = ClawLanguage.analyze(p, generator, Target.GPU);
assertEquals(ClawDirective.LOOP_FUSION, l.getDirective());
if(groupName != null){
assertTrue(l.hasGroupClause());
assertEquals(groupName, l.getGroupValue());
} else {
assertFalse(l.hasGroupClause());
assertNull(l.getGroupValue());
}
if(collapse){
assertTrue(l.hasCollapseClause());
assertEquals(n, l.getCollapseValue());
} else {
assertFalse(l.hasCollapseClause());
}
} catch(IllegalDirectiveException idex){
fail();
}
}
/**
* Assert any unvalid claw raw input
* @param raw Raw string value of the CLAW directive to be analyzed.
*/
private void analyzeUnvalidClawLanguage(String raw){
try {
Xpragma p = XmlHelper.createXpragma();
p.setValue(raw);
AcceleratorGenerator generator =
AcceleratorHelper.
createAcceleratorGenerator(AcceleratorDirective.OPENACC);
ClawLanguage.analyze(p, generator, Target.GPU);
fail();
} catch (IllegalDirectiveException pex){
assertNotNull(pex);
assertNotNull(pex.getMessage());
}
}
/**
* Test various input for the CLAW loop interchange directive.
*/
@Test
public void InterchangeTest(){
// Valid directives
analyzeValidClawLoopInterchange("claw loop-interchange", null, false, null);
analyzeValidClawLoopInterchange("claw loop-interchange (i,j,k)",
Arrays.asList("i", "j", "k"), false, null);
analyzeValidClawLoopInterchange("claw loop-interchange ( i,j,k ) ",
Arrays.asList("i", "j", "k"), false, null);
analyzeValidClawLoopInterchange("claw loop-interchange parallel",
null, true, null);
analyzeValidClawLoopInterchange("claw loop-interchange parallel acc(loop)",
null, true, "loop");
analyzeValidClawLoopInterchange("claw loop-interchange acc(loop)", null,
false, "loop");
analyzeValidClawLoopInterchange("claw loop-interchange (j,k,i) parallel",
Arrays.asList("j", "k", "i"), true, null);
// Unvalid directives
analyzeUnvalidClawLanguage("claw loop-interchange ()");
analyzeUnvalidClawLanguage("claw loop-interchange (i,j,k) group");
}
/**
* Assert the result for valid loop interchange CLAW directive
* @param raw Raw string value of the CLAW directive to be analyzed.
* @param indexes List of indexes to be found if any.
*/
private void analyzeValidClawLoopInterchange(String raw,
List<String> indexes,
boolean parallel,
String acc)
{
try {
Xpragma p = XmlHelper.createXpragma();
p.setValue(raw);
AcceleratorGenerator generator =
AcceleratorHelper.
createAcceleratorGenerator(AcceleratorDirective.OPENACC);
ClawLanguage l = ClawLanguage.analyze(p, generator, Target.GPU);
assertEquals(ClawDirective.LOOP_INTERCHANGE, l.getDirective());
if(indexes != null){
assertTrue(l.hasIndexes());
assertEquals(indexes.size(), l.getIndexes().size());
} else {
assertFalse(l.hasIndexes());
assertNull(l.getIndexes());
}
if(parallel){
assertTrue(l.hasParallelClause());
} else {
assertFalse(l.hasParallelClause());
}
if(acc != null){
assertTrue(l.hasAcceleratorClause());
assertEquals(acc, l.getAcceleratorClauses());
} else {
assertFalse(l.hasAcceleratorClause());
assertNull(l.getAcceleratorClauses());
}
} catch(IllegalDirectiveException idex){
fail();
}
}
/**
* Test various input for the CLAW remove directive.
*/
@Test
public void RemoveTest(){
// Valid directives
analyzeValidSimpleClaw("claw remove", ClawDirective.REMOVE, false);
analyzeValidSimpleClaw("claw end remove", ClawDirective.REMOVE, true);
analyzeValidSimpleClaw("claw end remove ", ClawDirective.REMOVE, true);
// Unvalid directives
analyzeUnvalidClawLanguage("claw");
analyzeUnvalidClawLanguage("claw dummy");
analyzeUnvalidClawLanguage("claw end re move");
}
/**
* Assert the result for valid simple CLAW directive
* @param raw Raw string value of the CLAW directive to be analyzed.
* @param directive Directive to be match.
*/
private void analyzeValidSimpleClaw(String raw, ClawDirective directive,
boolean isEnd)
{
try {
Xpragma p = XmlHelper.createXpragma();
p.setValue(raw);
AcceleratorGenerator generator =
AcceleratorHelper.
createAcceleratorGenerator(AcceleratorDirective.OPENACC);
ClawLanguage l = ClawLanguage.analyze(p, generator, Target.GPU);
assertEquals(directive, l.getDirective());
if(isEnd){
assertTrue(l.isEndPragma());
} else {
assertFalse(l.isEndPragma());
}
} catch(IllegalDirectiveException idex){
fail();
}
}
/**
* Test various input for the CLAW loop extract directive.
*/
@Test
public void ExtractTest(){
// Valid directives
ClawLanguage l = analyzeValidClawLoopExtract(
"claw loop-extract range(i=istart,iend) map(i:j)", "i", "istart",
"iend", null);
assertNotNull(l);
assertEquals(1, l.getMappings().size());
assertNotNull(l.getMappings().get(0));
ClawMapping map = l.getMappings().get(0);
assertEquals(1, map.getMappedVariables().size());
assertEquals(1, map.getMappingVariables().size());
assertEquals("i", map.getMappedVariables().get(0).getArgMapping());
assertEquals("i", map.getMappedVariables().get(0).getFctMapping());
assertFalse(map.getMappedVariables().get(0).hasDifferentMappping());
assertEquals("j", map.getMappingVariables().get(0).getArgMapping());
assertEquals("j", map.getMappingVariables().get(0).getFctMapping());
assertFalse(map.getMappingVariables().get(0).hasDifferentMappping());
l = analyzeValidClawLoopExtract(
"claw loop-extract range(i=istart,iend,2) map(i:j)", "i", "istart",
"iend", "2");
assertNotNull(l);
map = l.getMappings().get(0);
assertEquals(1, map.getMappedVariables().size());
assertEquals(1, map.getMappingVariables().size());
assertEquals("i", map.getMappedVariables().get(0).getArgMapping());
assertEquals("i", map.getMappedVariables().get(0).getFctMapping());
assertFalse(map.getMappedVariables().get(0).hasDifferentMappping());
assertEquals("j", map.getMappingVariables().get(0).getArgMapping());
assertEquals("j", map.getMappingVariables().get(0).getFctMapping());
assertFalse(map.getMappingVariables().get(0).hasDifferentMappping());
l = analyzeValidClawLoopExtract("claw loop-extract range(i=1,10) map(i:j)",
"i", "1", "10", null);
assertNotNull(l);
map = l.getMappings().get(0);
assertEquals(1, map.getMappedVariables().size());
assertEquals(1, map.getMappingVariables().size());
assertEquals("i", map.getMappedVariables().get(0).getArgMapping());
assertEquals("i", map.getMappedVariables().get(0).getFctMapping());
assertFalse(map.getMappedVariables().get(0).hasDifferentMappping());
assertEquals("j", map.getMappingVariables().get(0).getArgMapping());
assertEquals("j", map.getMappingVariables().get(0).getFctMapping());
assertFalse(map.getMappingVariables().get(0).hasDifferentMappping());
l = analyzeValidClawLoopExtract(
"claw loop-extract range(i=1,10,2) map(i:j) parallel", "i", "1", "10", "2");
assertNotNull(l);
map = l.getMappings().get(0);
assertTrue(l.hasParallelClause());
assertEquals(1, map.getMappedVariables().size());
assertEquals(1, map.getMappingVariables().size());
assertEquals("i", map.getMappedVariables().get(0).getArgMapping());
assertEquals("i", map.getMappedVariables().get(0).getFctMapping());
assertFalse(map.getMappedVariables().get(0).hasDifferentMappping());
assertEquals("j", map.getMappingVariables().get(0).getArgMapping());
assertEquals("j", map.getMappingVariables().get(0).getFctMapping());
assertFalse(map.getMappingVariables().get(0).hasDifferentMappping());
l = analyzeValidClawLoopExtract(
"claw loop-extract range(i=istart,iend) map(i:j) fusion", "i", "istart",
"iend", null);
assertNotNull(l);
assertEquals(1, l.getMappings().size());
assertNotNull(l.getMappings().get(0));
assertTrue(l.hasFusionClause());
assertFalse(l.hasGroupClause());
assertFalse(l.hasParallelClause());
map = l.getMappings().get(0);
assertEquals(1, map.getMappedVariables().size());
assertEquals(1, map.getMappingVariables().size());
assertEquals("i", map.getMappedVariables().get(0).getArgMapping());
assertEquals("i", map.getMappedVariables().get(0).getFctMapping());
assertFalse(map.getMappedVariables().get(0).hasDifferentMappping());
assertEquals("j", map.getMappingVariables().get(0).getArgMapping());
assertEquals("j", map.getMappingVariables().get(0).getFctMapping());
assertFalse(map.getMappingVariables().get(0).hasDifferentMappping());
l = analyzeValidClawLoopExtract(
"claw loop-extract range(i=istart,iend) map(i:j) fusion group(j1)",
"i", "istart", "iend", null);
assertNotNull(l);
assertEquals(1, l.getMappings().size());
assertNotNull(l.getMappings().get(0));
assertTrue(l.hasFusionClause());
assertTrue(l.hasGroupClause());
assertEquals("j1", l.getGroupValue());
map = l.getMappings().get(0);
assertEquals(1, map.getMappedVariables().size());
assertEquals(1, map.getMappingVariables().size());
assertEquals("i", map.getMappedVariables().get(0).getArgMapping());
assertEquals("i", map.getMappedVariables().get(0).getFctMapping());
assertFalse(map.getMappedVariables().get(0).hasDifferentMappping());
assertEquals("j", map.getMappingVariables().get(0).getArgMapping());
assertEquals("j", map.getMappingVariables().get(0).getFctMapping());
assertFalse(map.getMappingVariables().get(0).hasDifferentMappping());
l = analyzeValidClawLoopExtract(
"claw loop-extract range(i=istart,iend) map(i:j) fusion group(j1) " +
"acc(loop gang vector)", "i", "istart", "iend", null);
assertNotNull(l);
assertEquals(1, l.getMappings().size());
assertNotNull(l.getMappings().get(0));
assertTrue(l.hasFusionClause());
assertTrue(l.hasGroupClause());
assertTrue(l.hasAcceleratorClause());
assertEquals("loop gang vector", l.getAcceleratorClauses());
assertEquals("j1", l.getGroupValue());
map = l.getMappings().get(0);
assertEquals(1, map.getMappedVariables().size());
assertEquals(1, map.getMappingVariables().size());
assertEquals("i", map.getMappedVariables().get(0).getArgMapping());
assertEquals("i", map.getMappedVariables().get(0).getFctMapping());
assertFalse(map.getMappedVariables().get(0).hasDifferentMappping());
assertEquals("j", map.getMappingVariables().get(0).getArgMapping());
assertEquals("j", map.getMappingVariables().get(0).getFctMapping());
assertFalse(map.getMappingVariables().get(0).hasDifferentMappping());
l = analyzeValidClawLoopExtract(
"claw loop-extract range(j1=ki1sc,ki1ec) " +
"map(pduh2oc,pduh2of:j1,ki3sc/j3) " +
"map(pduco2,pduo3,palogp,palogt,podsc,podsf,podac,podaf:j1,ki3sc/j3) " +
"map(pbsff,pbsfc:j1,ki3sc/j3) map(pa1c,pa1f,pa2c,pa2f,pa3c,pa3f:j1) " +
"fusion group(coeth-j1) parallel acc(loop gang vector)",
"j1", "ki1sc", "ki1ec", null);
assertNotNull(l);
assertEquals(4, l.getMappings().size());
ClawMapping map1 = l.getMappings().get(0);
assertNotNull(map1);
assertEquals(2, map1.getMappedVariables().size());
assertEquals(2, map1.getMappingVariables().size());
assertEquals("pduh2oc", map1.getMappedVariables().get(0).getArgMapping());
assertEquals("pduh2oc", map1.getMappedVariables().get(0).getFctMapping());
assertEquals("pduh2of", map1.getMappedVariables().get(1).getArgMapping());
assertEquals("pduh2of", map1.getMappedVariables().get(1).getFctMapping());
assertEquals("j1", map1.getMappingVariables().get(0).getArgMapping());
assertEquals("j1", map1.getMappingVariables().get(0).getFctMapping());
assertEquals("ki3sc", map1.getMappingVariables().get(1).getArgMapping());
assertEquals("j3", map1.getMappingVariables().get(1).getFctMapping());
ClawMapping map2 = l.getMappings().get(1);
assertNotNull(map2);
assertEquals(8, map2.getMappedVariables().size());
assertEquals(2, map2.getMappingVariables().size());
assertEquals("pduco2", map2.getMappedVariables().get(0).getArgMapping());
assertEquals("pduco2", map2.getMappedVariables().get(0).getFctMapping());
assertEquals("pduo3", map2.getMappedVariables().get(1).getArgMapping());
assertEquals("pduo3", map2.getMappedVariables().get(1).getFctMapping());
assertEquals("palogp", map2.getMappedVariables().get(2).getArgMapping());
assertEquals("palogp", map2.getMappedVariables().get(2).getFctMapping());
assertEquals("palogt", map2.getMappedVariables().get(3).getArgMapping());
assertEquals("palogt", map2.getMappedVariables().get(3).getFctMapping());
assertEquals("podsc", map2.getMappedVariables().get(4).getArgMapping());
assertEquals("podsc", map2.getMappedVariables().get(4).getFctMapping());
assertEquals("podsf", map2.getMappedVariables().get(5).getArgMapping());
assertEquals("podsf", map2.getMappedVariables().get(5).getFctMapping());
assertEquals("podac", map2.getMappedVariables().get(6).getArgMapping());
assertEquals("podac", map2.getMappedVariables().get(6).getFctMapping());
assertEquals("podaf", map2.getMappedVariables().get(7).getArgMapping());
assertEquals("podaf", map2.getMappedVariables().get(7).getFctMapping());
assertEquals("j1", map2.getMappingVariables().get(0).getArgMapping());
assertEquals("j1", map2.getMappingVariables().get(0).getFctMapping());
assertEquals("ki3sc", map2.getMappingVariables().get(1).getArgMapping());
assertEquals("j3", map2.getMappingVariables().get(1).getFctMapping());
ClawMapping map3 = l.getMappings().get(2);
assertNotNull(map3);
assertEquals(2, map3.getMappedVariables().size());
assertEquals(2, map3.getMappingVariables().size());
assertEquals("pbsff", map3.getMappedVariables().get(0).getArgMapping());
assertEquals("pbsff", map3.getMappedVariables().get(0).getFctMapping());
assertEquals("pbsfc", map3.getMappedVariables().get(1).getArgMapping());
assertEquals("pbsfc", map3.getMappedVariables().get(1).getFctMapping());
assertEquals("j1", map3.getMappingVariables().get(0).getArgMapping());
assertEquals("j1", map3.getMappingVariables().get(0).getFctMapping());
assertEquals("ki3sc", map3.getMappingVariables().get(1).getArgMapping());
assertEquals("j3", map3.getMappingVariables().get(1).getFctMapping());
ClawMapping map4 = l.getMappings().get(3);
assertNotNull(map4);
assertEquals(6, map4.getMappedVariables().size());
assertEquals(1, map4.getMappingVariables().size());
assertEquals("pa1c", map4.getMappedVariables().get(0).getArgMapping());
assertEquals("pa1c", map4.getMappedVariables().get(0).getFctMapping());
assertEquals("pa1f", map4.getMappedVariables().get(1).getArgMapping());
assertEquals("pa1f", map4.getMappedVariables().get(1).getFctMapping());
assertEquals("pa2c", map4.getMappedVariables().get(2).getArgMapping());
assertEquals("pa2c", map4.getMappedVariables().get(2).getFctMapping());
assertEquals("pa2f", map4.getMappedVariables().get(3).getArgMapping());
assertEquals("pa2f", map4.getMappedVariables().get(3).getFctMapping());
assertEquals("pa3c", map4.getMappedVariables().get(4).getArgMapping());
assertEquals("pa3c", map4.getMappedVariables().get(4).getFctMapping());
assertEquals("pa3f", map4.getMappedVariables().get(5).getArgMapping());
assertEquals("pa3f", map4.getMappedVariables().get(5).getFctMapping());
assertEquals("j1", map4.getMappingVariables().get(0).getArgMapping());
assertEquals("j1", map4.getMappingVariables().get(0).getFctMapping());
assertTrue(l.hasFusionClause());
assertTrue(l.hasGroupClause());
assertEquals("coeth-j1", l.getGroupValue());
assertTrue(l.hasAcceleratorClause());
assertEquals("loop gang vector", l.getAcceleratorClauses());
// Unvalid directives
analyzeUnvalidClawLanguage("claw loop-extract");
analyzeUnvalidClawLanguage("claw loop - extract ");
}
/**
* Assert the result for valid loop extract CLAW directive
* @param raw Raw string value of the CLAW directive to be analyzed.
* @param induction Induction var to be found.
* @param lower Lower bound value to be found.
* @param upper Upper bound value to be found.
* @param step Step valu to be found if any.
*/
private ClawLanguage analyzeValidClawLoopExtract(String raw, String induction,
String lower, String upper,
String step)
{
try {
Xpragma p = XmlHelper.createXpragma();
p.setValue(raw);
AcceleratorGenerator generator =
AcceleratorHelper.
createAcceleratorGenerator(AcceleratorDirective.OPENACC);
ClawLanguage l = ClawLanguage.analyze(p, generator, Target.GPU);
assertEquals(ClawDirective.LOOP_EXTRACT, l.getDirective());
assertEquals(induction, l.getRange().getInductionVar());
assertEquals(lower, l.getRange().getLowerBound());
assertEquals(upper, l.getRange().getUpperBound());
if(step != null){
assertEquals(step, l.getRange().getStep());
}
return l;
} catch(IllegalDirectiveException idex){
System.err.println(idex.getMessage());
fail();
return null;
}
}
/**
* Test various input for the CLAW kcache directive.
*/
@Test
public void KcacheTest(){
// data clause + offsets
analyzeValidKcache("claw kcache data(var1,var2) offset(0,1)",
Arrays.asList("var1", "var2"), Arrays.asList(0, 1), false, false);
analyzeValidKcache("claw kcache data(var1,var2) offset(0,-1,0)",
Arrays.asList("var1", "var2"), Arrays.asList(0, -1, 0), false, false);
analyzeValidKcache("claw kcache data(var1,var2) offset(+1,-1,0)",
Arrays.asList("var1", "var2"), Arrays.asList(1, -1, 0), false, false);
analyzeValidKcache("claw kcache data(var1,var2) offset(+1,-1,0) private",
Arrays.asList("var1", "var2"), Arrays.asList(1, -1, 0), false, true);
analyzeValidKcache("claw kcache data(var1,var2) private",
Arrays.asList("var1", "var2"), null, false, true);
// offset + init clause
analyzeValidKcache("claw kcache data(var1,var2) offset(0,1) init",
Arrays.asList("var1", "var2"), Arrays.asList(0, 1), true, false);
analyzeValidKcache("claw kcache data(var1,var2) offset(0,-1,0) init",
Arrays.asList("var1", "var2"), Arrays.asList(0, -1, 0), true, false);
analyzeValidKcache("claw kcache data(var1,var2) offset(+1,-1,0) init",
Arrays.asList("var1", "var2"), Arrays.asList(1, -1, 0), true, false);
analyzeValidKcache("claw kcache data(var1,var2) offset(+1,-1,0) init private",
Arrays.asList("var1", "var2"), Arrays.asList(1, -1, 0), true, true);
analyzeValidKcache("claw kcache data(var1,var2) init private",
Arrays.asList("var1", "var2"), null, true, true);
// Unvalid directives
analyzeUnvalidClawLanguage("claw k cache ");
analyzeUnvalidClawLanguage("claw k-cache");
}
/**
* Assert the result for valid CLAW kcache directive
* @param raw Raw string value of the CLAW directive to be analyzed.
* @param data List of identifiers to be checked.
* @param offsets List of offsets to be checked.
* @param init If true, check that ClawLanguage object has init clause
* enabled.
*/
private void analyzeValidKcache(String raw, List<String> data,
List<Integer> offsets, boolean init,
boolean hasPrivate)
{
try {
Xpragma p = XmlHelper.createXpragma();
p.setValue(raw);
AcceleratorGenerator generator =
AcceleratorHelper.
createAcceleratorGenerator(AcceleratorDirective.OPENACC);
ClawLanguage l = ClawLanguage.analyze(p, generator, Target.GPU);
assertEquals(ClawDirective.KCACHE, l.getDirective());
if(data != null){
assertTrue(l.hasDataClause());
assertEquals(data.size(), l.getDataClauseValues().size());
for(int i = 0; i < data.size(); ++i){
assertEquals(data.get(i), l.getDataClauseValues().get(i));
}
} else {
assertFalse(l.hasDataClause());
}
if(offsets != null){
assertEquals(offsets.size(), l.getOffsets().size());
for(int i = 0; i < offsets.size(); ++i){
assertEquals(offsets.get(i), l.getOffsets().get(i));
}
}
if(init){
assertTrue(l.hasInitClause());
} else {
assertFalse(l.hasInitClause());
}
if(hasPrivate){
assertTrue(l.hasPrivateClause());
} else {
assertFalse(l.hasPrivateClause());
}
} catch(IllegalDirectiveException idex){
System.err.print(idex.getMessage());
fail();
}
}
/**
* Test various input for the CLAW array-transform directive.
*/
@Test
public void ArrayTransformTest(){
// Valid directives
analyzeValidArrayTransform("claw array-transform", false, null, false,
null, null);
analyzeValidArrayTransform("claw array-transform fusion", true, null, false,
null, null);
analyzeValidArrayTransform("claw array-transform fusion group(j1)", true,
"j1", false, null, null);
analyzeValidArrayTransform("claw array-transform fusion parallel", true,
null, true, null, null);
analyzeValidArrayTransform("claw array-transform fusion parallel acc(loop)",
true, null, true, "loop", null);
analyzeValidArrayTransform("claw array-transform fusion acc(loop)", true,
null, false, "loop", null);
analyzeValidArrayTransform(
"claw array-transform fusion parallel acc(loop gang vector)", true,
null, true, "loop gang vector", null);
analyzeValidArrayTransform(
"claw array-transform fusion group(j1) parallel acc(loop gang vector)",
true, "j1", true, "loop gang vector", null);
analyzeValidArrayTransform(
"claw array-transform parallel acc(loop gang vector)",
false, null, true, "loop gang vector", null);
analyzeValidArrayTransform("claw array-transform parallel", false, null,
true, null, null);
analyzeValidArrayTransform("claw array-transform acc(loop gang vector)",
false, null, false, "loop gang vector", null);
analyzeValidArrayTransform("claw array-transform induction(j1,j3)",
false, null, false, null, Arrays.asList("j1","j3"));
analyzeValidArrayTransform("claw array-transform induction(j1)",
false, null, false, null, Collections.singletonList("j1"));
analyzeValidArrayTransform("claw array-transform induction(i,j,k)",
false, null, false, null, Arrays.asList("i", "j", "k"));
analyzeUnvalidClawLanguage("claw array-transform induction()");
analyzeUnvalidClawLanguage("claw array-transform induction");
analyzeValidSimpleClaw("claw end array-transform",
ClawDirective.ARRAY_TRANSFORM, true);
analyzeValidSimpleClaw("claw end array-transform ",
ClawDirective.ARRAY_TRANSFORM, true);
}
/**
* Assert the result for valid CLAW array-transform directive
* @param raw Raw string value of the CLAW directive to be analyzed.
* @param fusion Set to true if the extracted option should be present.
* @param fusionGroup Name of the group in the extracted fusion option.
* @param parallel Set to true if the extracted option should be present.
* @param acc String of acc clauses that should be present.
*/
private void analyzeValidArrayTransform(String raw, boolean fusion,
String fusionGroup, boolean parallel,
String acc, List<String> inducNames)
{
try {
Xpragma p = XmlHelper.createXpragma();
p.setValue(raw);
AcceleratorGenerator generator =
AcceleratorHelper.
createAcceleratorGenerator(AcceleratorDirective.OPENACC);
ClawLanguage l = ClawLanguage.analyze(p, generator, Target.GPU);
assertEquals(ClawDirective.ARRAY_TRANSFORM, l.getDirective());
if(fusion){
assertTrue(l.hasFusionClause());
assertEquals(fusionGroup, l.getGroupValue());
} else {
assertFalse(l.hasFusionClause());
assertNull(l.getGroupValue());
}
if(parallel){
assertTrue(l.hasParallelClause());
} else {
assertFalse(l.hasParallelClause());
}
if(acc != null){
assertTrue(l.hasAcceleratorClause());
assertEquals(acc, l.getAcceleratorClauses());
} else {
assertFalse(l.hasAcceleratorClause());
}
if(inducNames != null){
assertTrue(l.hasInductionClause());
assertEquals(inducNames.size(), l.getInductionValues().size());
for(int i = 0; i < inducNames.size(); ++ i){
assertEquals(inducNames.get(i), l.getInductionValues().get(i));
}
} else {
assertFalse(l.hasInductionClause());
}
} catch(IllegalDirectiveException idex){
System.err.print(idex.getMessage());
fail();
}
}
/**
* Test various input for the CLAW loop-hoist directive.
*/
@Test
public void LoopHoistTest(){
// Valid directives
analyzeValidLoopHoist("claw loop-hoist(i,j)",
Arrays.asList("i", "j"), false, null, false, null);
analyzeValidLoopHoist("claw loop-hoist(i,j) interchange",
Arrays.asList("i", "j"), true, null, false, null);
analyzeValidLoopHoist("claw loop-hoist(i,j) interchange(j,i)",
Arrays.asList("i", "j"), true, Arrays.asList("j", "i"), false, null);
ClawReshapeInfo info1 = new ClawReshapeInfo("zmd", 0,
new ArrayList<Integer>());
ClawReshapeInfo info2 =
new ClawReshapeInfo("zsediflux", 1, Collections.singletonList(2));
analyzeValidLoopHoist("claw loop-hoist(i,j) reshape(zmd(0), zsediflux(1,2))",
Arrays.asList("i", "j"), false, null, true,
Arrays.asList(info1, info2));
// Unvalid directives
analyzeUnvalidClawLanguage("claw loop-hoist");
analyzeUnvalidClawLanguage("claw loop-hoist()");
analyzeUnvalidClawLanguage("claw loop-hoist(i,j) interchange()");
analyzeValidSimpleClaw("claw end loop-hoist",
ClawDirective.LOOP_HOIST, true);
analyzeValidSimpleClaw("claw end loop-hoist ",
ClawDirective.LOOP_HOIST, true);
}
/**
* Assert the result for valid CLAW loop-hoist directive
* @param raw Raw string value of the CLAW directive to be analyzed.
* @param inductions List of induction variables to be checked.
*/
private void analyzeValidLoopHoist(String raw, List<String> inductions,
boolean interchange, List<String> indexes,
boolean reshape,
List<ClawReshapeInfo> infos)
{
try {
Xpragma p = XmlHelper.createXpragma();
p.setValue(raw);
AcceleratorGenerator generator =
AcceleratorHelper.
createAcceleratorGenerator(AcceleratorDirective.OPENACC);
ClawLanguage l = ClawLanguage.analyze(p, generator, Target.GPU);
assertEquals(ClawDirective.LOOP_HOIST, l.getDirective());
assertEquals(inductions.size(), l.getHoistInductionVars().size());
for(int i = 0; i < inductions.size(); ++i){
assertEquals(inductions.get(i), l.getHoistInductionVars().get(i));
}
if(interchange){
assertTrue(l.hasInterchangeClause());
} else {
assertFalse(l.hasInterchangeClause());
}
if(indexes != null){
for(int i = 0; i < indexes.size(); ++i){
assertEquals(indexes.get(i), l.getIndexes().get(i));
}
}
if(reshape){
assertTrue(l.hasReshapeClause());
assertEquals(infos.size(), l.getReshapeClauseValues().size());
for(int i = 0; i < infos.size(); ++i){
assertEquals(infos.get(i).getArrayName(),
l.getReshapeClauseValues().get(i).getArrayName());
assertEquals(infos.get(i).getTargetDimension(),
l.getReshapeClauseValues().get(i).getTargetDimension());
List<Integer> expected = infos.get(i).getKeptDimensions();
List<Integer> actual =
l.getReshapeClauseValues().get(i).getKeptDimensions();
assertEquals(expected.size(), actual.size());
for(int j=0; j < expected.size(); ++j){
assertEquals(expected.get(j), actual.get(j));
}
}
} else {
assertFalse(l.hasReshapeClause());
}
} catch(IllegalDirectiveException idex){
System.err.print(idex.getMessage());
fail();
}
}
/**
* Test various input for the CLAW call directive.
*/
@Test
public void ArrayToFctCallTest(){
// Valid directives
analyzeValidArrayToFctCall("claw call var1=f_var1(i,j)", "var1", "f_var1",
Arrays.asList("i", "j"));
analyzeValidArrayToFctCall("claw call var1=f_var1(i)", "var1", "f_var1",
Collections.singletonList("i"));
analyzeValidArrayToFctCall("claw call v=f(i,j)", "v", "f",
Arrays.asList("i", "j"));
// Unvalid directives
analyzeUnvalidClawLanguage("claw call ");
analyzeUnvalidClawLanguage("claw call v=");
analyzeUnvalidClawLanguage("claw call v=()");
}
/**
* Assert the result for valid CLAW call directive
* @param raw Raw string value of the CLAW directive to be analyzed.
* @param arrayName Array name to be checked.
* @param fctName Function name to be checked.
* @param params List of parameters identifier to be checked.
*/
private void analyzeValidArrayToFctCall(String raw, String arrayName,
String fctName, List<String> params)
{
try {
Xpragma p = XmlHelper.createXpragma();
p.setValue(raw);
AcceleratorGenerator generator =
AcceleratorHelper.
createAcceleratorGenerator(AcceleratorDirective.OPENACC);
ClawLanguage l = ClawLanguage.analyze(p, generator, Target.GPU);
assertEquals(ClawDirective.ARRAY_TO_CALL, l.getDirective());
assertEquals(params.size(), l.getFctParams().size());
for(int i = 0; i < params.size(); ++i){
assertEquals(params.get(i), l.getFctParams().get(i));
}
assertEquals(arrayName, l.getArrayName());
assertEquals(fctName, l.getFctName());
} catch(IllegalDirectiveException idex){
System.err.print(idex.getMessage());
fail();
}
}
/**
* Test various input for the CLAW parallelize directive.
*/
@Test
public void parallelizeTest(){
// Valid directives
ClawDimension d1 = new ClawDimension("i", "1", "NX");
analyzeValidParallelize("claw define dimension i(1,NX)" +
" parallelize data(t,qc,qv) over (i,j,:)",
Arrays.asList("t", "qc", "qv"), Arrays.asList("i", "j", ":"),
Collections.singletonList(d1));
ClawDimension d2 = new ClawDimension("j", "1", "NY");
analyzeValidParallelize("claw define dimension j(1,NY)" +
"parallelize data(t,qc,qv) over (i,j,:)",
Arrays.asList("t", "qc", "qv"), Arrays.asList("i", "j", ":"),
Collections.singletonList(d2));
ClawDimension d3 = new ClawDimension("j", "1", "10");
analyzeValidParallelize("claw define dimension j(1,10) " +
"parallelize data(t,qc,qv) over (i,j,:)",
Arrays.asList("t", "qc", "qv"), Arrays.asList("i", "j", ":"),
Collections.singletonList(d3));
ClawDimension d4 = new ClawDimension("j", "jstart", "10");
analyzeValidParallelize("claw define dimension j(jstart,10) " +
"parallelize data(t,qc,qv) over (i,j,:)",
Arrays.asList("t", "qc", "qv"), Arrays.asList("i", "j", ":"),
Collections.singletonList(d4));
ClawDimension d5 = new ClawDimension("j", "jstart", "ny");
analyzeValidParallelize("claw define dimension j(jstart,ny) " +
"parallelize data(t,qc,qv) over (i,j,:)",
Arrays.asList("t", "qc", "qv"), Arrays.asList("i", "j", ":"),
Collections.singletonList(d5));
analyzeValidParallelize("claw parallelize data(t,qc,qv) over (i,j,:)",
Arrays.asList("t", "qc", "qv"), Arrays.asList("i", "j", ":"), null);
analyzeValidParallelize("claw parallelize data(t,qc,qv) over (:,i,j)",
Arrays.asList("t", "qc", "qv"), Arrays.asList(":", "i", "j"), null);
analyzeValidParallelize("claw parallelize data(t,qc,qv) over (i,:,j)",
Arrays.asList("t", "qc", "qv"), Arrays.asList("i", ":", "j"), null);
// Unvalid directives
analyzeUnvalidClawLanguage("claw parallelize over ");
analyzeUnvalidClawLanguage("claw parallelite data() over ()");
}
/**
* Assert the result for valid CLAW parallelize directive
* @param raw Raw string value of the CLAW directive to be analyzed.
* @param data Reference list for the data clause values.
* @param over Reference list for the over clause values.
* @param dimensions Reference list of dimensions.
*/
private void analyzeValidParallelize(String raw, List<String> data,
List<String> over,
List<ClawDimension> dimensions)
{
try {
Xpragma p = XmlHelper.createXpragma();
p.setValue(raw);
AcceleratorGenerator generator =
AcceleratorHelper.
createAcceleratorGenerator(AcceleratorDirective.OPENACC);
ClawLanguage l = ClawLanguage.analyze(p, generator, Target.GPU);
assertEquals(ClawDirective.PARALLELIZE, l.getDirective());
assertEquals(data.size(), l.getDataClauseValues().size());
assertEquals(over.size(), l.getOverClauseValues().size());
assertTrue(l.hasDataClause());
for(int i = 0; i < data.size(); ++i){
assertEquals(data.get(i), l.getDataClauseValues().get(i));
}
assertTrue(l.hasOverClause());
for(int i = 0; i < over.size(); ++i){
assertEquals(over.get(i), l.getOverClauseValues().get(i));
}
if(dimensions != null){
assertEquals(dimensions.size(), l.getDimesionValues().size());
for(int i = 0; i < dimensions.size(); ++i){
assertEquals(dimensions.get(i).getIdentifier(),
l.getDimesionValues().get(i).getIdentifier());
assertEquals(dimensions.get(i).lowerBoundIsVar(),
l.getDimesionValues().get(i).lowerBoundIsVar());
assertEquals(dimensions.get(i).upperBoundIsVar(),
l.getDimesionValues().get(i).upperBoundIsVar());
assertEquals(dimensions.get(i).getLowerBoundInt(),
l.getDimesionValues().get(i).getLowerBoundInt());
assertEquals(dimensions.get(i).getUpperBoundInt(),
l.getDimesionValues().get(i).getUpperBoundInt());
assertEquals(dimensions.get(i).getLowerBoundId(),
l.getDimesionValues().get(i).getLowerBoundId());
assertEquals(dimensions.get(i).getUpperBoundId(),
l.getDimesionValues().get(i).getUpperBoundId());
}
}
} catch(IllegalDirectiveException idex){
System.err.print(idex.getMessage());
fail();
}
}
@Test
public void ContinuationTest(){
String continuedPragma = "claw loop-fusion claw collapse(2)";
analyzeValidClawLoopFusion(continuedPragma, null, true, 2);
}
}
| Fix test case insensitive
| omni-cx2x/unittest/cx2x/translator/language/ClawLanguageTest.java | Fix test case insensitive | <ide><path>mni-cx2x/unittest/cx2x/translator/language/ClawLanguageTest.java
<ide> public void parallelizeTest(){
<ide>
<ide> // Valid directives
<del> ClawDimension d1 = new ClawDimension("i", "1", "NX");
<del> analyzeValidParallelize("claw define dimension i(1,NX)" +
<add> ClawDimension d1 = new ClawDimension("i", "1", "nx");
<add> analyzeValidParallelize("claw define dimension i(1,nx)" +
<ide> " parallelize data(t,qc,qv) over (i,j,:)",
<ide> Arrays.asList("t", "qc", "qv"), Arrays.asList("i", "j", ":"),
<ide> Collections.singletonList(d1));
<ide>
<del> ClawDimension d2 = new ClawDimension("j", "1", "NY");
<del> analyzeValidParallelize("claw define dimension j(1,NY)" +
<add> ClawDimension d2 = new ClawDimension("j", "1", "ny");
<add> analyzeValidParallelize("claw define dimension j(1,ny)" +
<ide> "parallelize data(t,qc,qv) over (i,j,:)",
<ide> Arrays.asList("t", "qc", "qv"), Arrays.asList("i", "j", ":"),
<ide> Collections.singletonList(d2));
<ide> }
<ide>
<ide> }
<add> |
|
JavaScript | apache-2.0 | ad6ecbd5b9cbece48b96cb2d5ec7f0c9714749a2 | 0 | monetate/closure-compiler,google/closure-compiler,ChadKillingsworth/closure-compiler,nawawi/closure-compiler,google/closure-compiler,ChadKillingsworth/closure-compiler,ChadKillingsworth/closure-compiler,nawawi/closure-compiler,monetate/closure-compiler,monetate/closure-compiler,google/closure-compiler,nawawi/closure-compiler,ChadKillingsworth/closure-compiler,google/closure-compiler,monetate/closure-compiler,nawawi/closure-compiler | /*
* Copyright 2008 The Closure Compiler Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Definitions for all the extensions over the
* W3C's DOM3 specification in HTML5. This file depends on
* w3c_dom3.js. The whole file has been fully type annotated.
*
* @see http://www.whatwg.org/specs/web-apps/current-work/multipage/index.html
* @see http://dev.w3.org/html5/spec/Overview.html
*
* This also includes Typed Array definitions from
* http://www.khronos.org/registry/typedarray/specs/latest/
*
* This relies on w3c_event.js being included first.
*
* @externs
*/
/** @type {?HTMLSlotElement} */
Node.prototype.assignedSlot;
/**
* @type {string}
* @see https://dom.spec.whatwg.org/#dom-element-slot
*/
Element.prototype.slot;
/**
* Note: In IE, the contains() method only exists on Elements, not Nodes.
* Therefore, it is recommended that you use the Conformance framework to
* prevent calling this on Nodes which are not Elements.
* @see https://connect.microsoft.com/IE/feedback/details/780874/node-contains-is-incorrect
*
* @param {Node} n The node to check
* @return {boolean} If 'n' is this Node, or is contained within this Node.
* @see https://developer.mozilla.org/en-US/docs/Web/API/Node.contains
* @nosideeffects
*/
Node.prototype.contains = function(n) {};
/** @type {boolean} */
Node.prototype.isConnected;
/**
* @type {boolean}
* @see https://html.spec.whatwg.org/multipage/scripting.html#the-script-element
*/
HTMLScriptElement.prototype.async;
/**
* @type {string?}
* @see https://html.spec.whatwg.org/multipage/scripting.html#the-script-element
*/
HTMLScriptElement.prototype.crossOrigin;
/**
* @type {string}
* @see https://html.spec.whatwg.org/multipage/scripting.html#the-script-element
*/
HTMLScriptElement.prototype.integrity;
/**
* @type {boolean}
* @see https://html.spec.whatwg.org/multipage/scripting.html#the-script-element
*/
HTMLScriptElement.prototype.noModule;
/**
* @type {string}
* @see https://html.spec.whatwg.org/multipage/scripting.html#the-script-element
*/
HTMLScriptElement.prototype.referrerPolicy;
/**
* @constructor
* @see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#the-canvas-element
* @extends {HTMLElement}
*/
function HTMLCanvasElement() {}
/** @type {number} */
HTMLCanvasElement.prototype.width;
/** @type {number} */
HTMLCanvasElement.prototype.height;
/**
* @see https://www.w3.org/TR/html5/scripting-1.html#dom-canvas-toblob
* @param {function(!Blob)} callback
* @param {string=} opt_type
* @param {...*} var_args
* @throws {Error}
*/
HTMLCanvasElement.prototype.toBlob = function(callback, opt_type, var_args) {};
/**
* @param {string=} opt_type
* @param {...*} var_args
* @return {string}
* @throws {Error}
*/
HTMLCanvasElement.prototype.toDataURL = function(opt_type, var_args) {};
/**
* @modifies {this}
* @param {string} contextId
* @param {Object=} opt_args
* @return {Object}
*/
HTMLCanvasElement.prototype.getContext = function(contextId, opt_args) {};
/**
* @see https://www.w3.org/TR/mediacapture-fromelement/
* @param {number=} opt_framerate
* @return {!MediaStream}
* @throws {Error}
* */
HTMLCanvasElement.prototype.captureStream = function(opt_framerate) {};
/**
* @see https://html.spec.whatwg.org/multipage/canvas.html#dom-canvas-transfercontroltooffscreen
* @return {!OffscreenCanvas}
* @throws {Error}
* */
HTMLCanvasElement.prototype.transferControlToOffscreen = function() {};
/**
* @interface
* @extends {MediaStreamTrack}
* @see https://w3c.github.io/mediacapture-fromelement/#the-canvascapturemediastreamtrack
*/
function CanvasCaptureMediaStreamTrack() {}
/**
* The canvas element that this media stream captures.
* @type {!HTMLCanvasElement}
*/
CanvasCaptureMediaStreamTrack.prototype.canvas;
/**
* Allows applications to manually request that a frame from the canvas be
* captured and rendered into the track.
* @return {undefined}
*/
CanvasCaptureMediaStreamTrack.prototype.requestFrame = function() {};
/**
* @see https://html.spec.whatwg.org/multipage/canvas.html#the-offscreencanvas-interface
* @implements {EventTarget}
* @implements {Transferable}
* @param {number} width
* @param {number} height
* @nosideeffects
* @constructor
*/
function OffscreenCanvas(width, height) {}
/** @override */
OffscreenCanvas.prototype.addEventListener = function(
type, listener, opt_options) {};
/** @override */
OffscreenCanvas.prototype.removeEventListener = function(
type, listener, opt_options) {};
/** @override */
OffscreenCanvas.prototype.dispatchEvent = function(evt) {};
/** @type {number} */
OffscreenCanvas.prototype.width;
/** @type {number} */
OffscreenCanvas.prototype.height;
/**
* @param {string} contextId
* @param {!Object=} opt_options
* @modifies {this}
* @return {!Object}
*/
OffscreenCanvas.prototype.getContext = function(contextId, opt_options) {};
/**
* @return {!ImageBitmap}
*/
OffscreenCanvas.prototype.transferToImageBitmap = function() {};
/**
* @param {{type: (string|undefined), quality: (number|undefined)}=} opt_options
* @return {!Promise<!Blob>}
*/
OffscreenCanvas.prototype.convertToBlob = function(opt_options) {};
// TODO(tjgq): Find a way to add SVGImageElement to this typedef without making
// svg.js part of core.
/**
* @typedef {HTMLImageElement|HTMLVideoElement|HTMLCanvasElement|ImageBitmap|
* OffscreenCanvas}
*/
var CanvasImageSource;
/**
* @interface
* @see https://www.w3.org/TR/2dcontext/#canvaspathmethods
*/
function CanvasPathMethods() {}
/**
* @return {undefined}
*/
CanvasPathMethods.prototype.closePath = function() {};
/**
* @param {number} x
* @param {number} y
* @return {undefined}
*/
CanvasPathMethods.prototype.moveTo = function(x, y) {};
/**
* @param {number} x
* @param {number} y
* @return {undefined}
*/
CanvasPathMethods.prototype.lineTo = function(x, y) {};
/**
* @param {number} cpx
* @param {number} cpy
* @param {number} x
* @param {number} y
* @return {undefined}
*/
CanvasPathMethods.prototype.quadraticCurveTo = function(cpx, cpy, x, y) {};
/**
* @param {number} cp1x
* @param {number} cp1y
* @param {number} cp2x
* @param {number} cp2y
* @param {number} x
* @param {number} y
* @return {undefined}
*/
CanvasPathMethods.prototype.bezierCurveTo = function(
cp1x, cp1y, cp2x, cp2y, x, y) {};
/**
* @param {number} x1
* @param {number} y1
* @param {number} x2
* @param {number} y2
* @param {number} radius
* @return {undefined}
*/
CanvasPathMethods.prototype.arcTo = function(x1, y1, x2, y2, radius) {};
/**
* @param {number} x
* @param {number} y
* @param {number} w
* @param {number} h
* @return {undefined}
*/
CanvasPathMethods.prototype.rect = function(x, y, w, h) {};
/**
* @param {number} x
* @param {number} y
* @param {number} radius
* @param {number} startAngle
* @param {number} endAngle
* @param {boolean=} opt_anticlockwise
* @return {undefined}
*/
CanvasPathMethods.prototype.arc = function(
x, y, radius, startAngle, endAngle, opt_anticlockwise) {};
/**
* @constructor
* @param {!Path2D|string=} arg
* @implements {CanvasPathMethods}
* @see https://html.spec.whatwg.org/multipage/scripting.html#path2d-objects
*/
function Path2D(arg) {}
/**
* @return {undefined}
* @override
*/
Path2D.prototype.closePath = function() {};
/**
* @param {number} x
* @param {number} y
* @return {undefined}
* @override
*/
Path2D.prototype.moveTo = function(x, y) {};
/**
* @param {number} x
* @param {number} y
* @return {undefined}
* @override
*/
Path2D.prototype.lineTo = function(x, y) {};
/**
* @param {number} cpx
* @param {number} cpy
* @param {number} x
* @param {number} y
* @return {undefined}
* @override
*/
Path2D.prototype.quadraticCurveTo = function(cpx, cpy, x, y) {};
/**
* @param {number} cp1x
* @param {number} cp1y
* @param {number} cp2x
* @param {number} cp2y
* @param {number} x
* @param {number} y
* @return {undefined}
* @override
*/
Path2D.prototype.bezierCurveTo = function(
cp1x, cp1y, cp2x, cp2y, x, y) {};
/**
* @param {number} x1
* @param {number} y1
* @param {number} x2
* @param {number} y2
* @param {number} radius
* @return {undefined}
* @override
*/
Path2D.prototype.arcTo = function(x1, y1, x2, y2, radius) {};
/**
* @param {number} x
* @param {number} y
* @param {number} w
* @param {number} h
* @return {undefined}
* @override
*/
Path2D.prototype.rect = function(x, y, w, h) {};
/**
* @param {number} x
* @param {number} y
* @param {number} radius
* @param {number} startAngle
* @param {number} endAngle
* @param {boolean=} optAnticlockwise
* @return {undefined}
* @override
*/
Path2D.prototype.arc = function(
x, y, radius, startAngle, endAngle, optAnticlockwise) {};
/**
* @param {Path2D} path
* @return {undefined}
*/
Path2D.prototype.addPath = function(path) {};
/**
* @interface
* @see https://www.w3.org/TR/2dcontext/#canvasdrawingstyles
*/
function CanvasDrawingStyles() {}
/** @type {number} */
CanvasDrawingStyles.prototype.lineWidth;
/** @type {string} */
CanvasDrawingStyles.prototype.lineCap;
/** @type {string} */
CanvasDrawingStyles.prototype.lineJoin;
/** @type {number} */
CanvasDrawingStyles.prototype.miterLimit;
/**
* @param {Array<number>} segments
* @return {undefined}
*/
CanvasDrawingStyles.prototype.setLineDash = function(segments) {};
/**
* @return {!Array<number>}
*/
CanvasDrawingStyles.prototype.getLineDash = function() {};
/** @type {string} */
CanvasDrawingStyles.prototype.font;
/** @type {string} */
CanvasDrawingStyles.prototype.textAlign;
/** @type {string} */
CanvasDrawingStyles.prototype.textBaseline;
// TODO(dramaix): replace this with @record.
/**
* @constructor
* @abstract
* @implements {CanvasDrawingStyles}
* @implements {CanvasPathMethods}
* @see http://www.w3.org/TR/2dcontext/#canvasrenderingcontext2d
*/
function BaseRenderingContext2D() {}
/** @const {!HTMLCanvasElement|!OffscreenCanvas} */
BaseRenderingContext2D.prototype.canvas;
/**
* @return {undefined}
*/
BaseRenderingContext2D.prototype.save = function() {};
/**
* @return {undefined}
*/
BaseRenderingContext2D.prototype.restore = function() {};
/**
* @param {number} x
* @param {number} y
* @return {undefined}
*/
BaseRenderingContext2D.prototype.scale = function(x, y) {};
/**
* @param {number} angle
* @return {undefined}
*/
BaseRenderingContext2D.prototype.rotate = function(angle) {};
/**
* @param {number} x
* @param {number} y
* @return {undefined}
*/
BaseRenderingContext2D.prototype.translate = function(x, y) {};
/**
* @param {number} m11
* @param {number} m12
* @param {number} m21
* @param {number} m22
* @param {number} dx
* @param {number} dy
* @return {undefined}
*/
BaseRenderingContext2D.prototype.transform = function(
m11, m12, m21, m22, dx, dy) {};
/**
* @param {number} m11
* @param {number} m12
* @param {number} m21
* @param {number} m22
* @param {number} dx
* @param {number} dy
* @return {undefined}
*/
BaseRenderingContext2D.prototype.setTransform = function(
m11, m12, m21, m22, dx, dy) {};
/**
* @return {!DOMMatrixReadOnly}
*/
BaseRenderingContext2D.prototype.getTransform = function() {};
/**
* @param {number} x0
* @param {number} y0
* @param {number} x1
* @param {number} y1
* @return {!CanvasGradient}
* @throws {Error}
*/
BaseRenderingContext2D.prototype.createLinearGradient = function(
x0, y0, x1, y1) {};
/**
* @param {number} x0
* @param {number} y0
* @param {number} r0
* @param {number} x1
* @param {number} y1
* @param {number} r1
* @return {!CanvasGradient}
* @throws {Error}
*/
BaseRenderingContext2D.prototype.createRadialGradient = function(
x0, y0, r0, x1, y1, r1) {};
/**
* @param {CanvasImageSource} image
* @param {string} repetition
* @return {?CanvasPattern}
* @throws {Error}
* @see https://html.spec.whatwg.org/multipage/scripting.html#dom-context-2d-createpattern
*/
BaseRenderingContext2D.prototype.createPattern = function(
image, repetition) {};
/**
* @param {number} x
* @param {number} y
* @param {number} w
* @param {number} h
* @return {undefined}
*/
BaseRenderingContext2D.prototype.clearRect = function(x, y, w, h) {};
/**
* @param {number} x
* @param {number} y
* @param {number} w
* @param {number} h
* @return {undefined}
*/
BaseRenderingContext2D.prototype.fillRect = function(x, y, w, h) {};
/**
* @param {number} x
* @param {number} y
* @param {number} w
* @param {number} h
* @return {undefined}
*/
BaseRenderingContext2D.prototype.strokeRect = function(x, y, w, h) {};
/**
* @return {undefined}
*/
BaseRenderingContext2D.prototype.beginPath = function() {};
/**
* @return {undefined}
* @override
*/
BaseRenderingContext2D.prototype.closePath = function() {};
/**
* @param {number} x
* @param {number} y
* @return {undefined}
* @override
*/
BaseRenderingContext2D.prototype.moveTo = function(x, y) {};
/**
* @param {number} x
* @param {number} y
* @return {undefined}
* @override
*/
BaseRenderingContext2D.prototype.lineTo = function(x, y) {};
/**
* @param {number} cpx
* @param {number} cpy
* @param {number} x
* @param {number} y
* @return {undefined}
* @override
*/
BaseRenderingContext2D.prototype.quadraticCurveTo = function(
cpx, cpy, x, y) {};
/**
* @param {number} cp1x
* @param {number} cp1y
* @param {number} cp2x
* @param {number} cp2y
* @param {number} x
* @param {number} y
* @return {undefined}
* @override
*/
BaseRenderingContext2D.prototype.bezierCurveTo = function(
cp1x, cp1y, cp2x, cp2y, x, y) {};
/**
* @param {number} x1
* @param {number} y1
* @param {number} x2
* @param {number} y2
* @param {number} radius
* @return {undefined}
* @override
*/
BaseRenderingContext2D.prototype.arcTo = function(x1, y1, x2, y2, radius) {};
/**
* @param {number} x
* @param {number} y
* @param {number} w
* @param {number} h
* @return {undefined}
* @override
*/
BaseRenderingContext2D.prototype.rect = function(x, y, w, h) {};
/**
* @param {number} x
* @param {number} y
* @param {number} radius
* @param {number} startAngle
* @param {number} endAngle
* @param {boolean=} opt_anticlockwise
* @return {undefined}
* @override
*/
BaseRenderingContext2D.prototype.arc = function(
x, y, radius, startAngle, endAngle, opt_anticlockwise) {};
/**
* @param {number} x
* @param {number} y
* @param {number} radiusX
* @param {number} radiusY
* @param {number} rotation
* @param {number} startAngle
* @param {number} endAngle
* @param {boolean=} opt_anticlockwise
* @return {undefined}
* @see http://developer.mozilla.org/en/docs/Web/API/CanvasRenderingContext2D/ellipse
*/
BaseRenderingContext2D.prototype.ellipse = function(
x, y, radiusX, radiusY, rotation, startAngle, endAngle, opt_anticlockwise) {
};
/**
* @param {Path2D|string=} optFillRuleOrPath
* @param {string=} optFillRule
* @return {undefined}
*/
BaseRenderingContext2D.prototype.fill = function(optFillRuleOrPath, optFillRule) {};
/**
* @param {Path2D=} optStroke
* @return {undefined}
*/
BaseRenderingContext2D.prototype.stroke = function(optStroke) {};
/**
* @param {Element} element
* @return {undefined}
*/
BaseRenderingContext2D.prototype.drawFocusIfNeeded = function(element) {};
/**
* @param {Path2D|string=} optFillRuleOrPath
* @param {string=} optFillRule
* @return {undefined}
*/
BaseRenderingContext2D.prototype.clip = function(optFillRuleOrPath, optFillRule) {};
/**
* @param {number} x
* @param {number} y
* @return {boolean}
* @nosideeffects
* @see http://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/isPointInStroke
*/
BaseRenderingContext2D.prototype.isPointInStroke = function(x, y) {};
/**
* @param {number} x
* @param {number} y
* @param {string=} opt_fillRule
* @return {boolean}
* @nosideeffects
*/
BaseRenderingContext2D.prototype.isPointInPath = function(
x, y, opt_fillRule) {};
/**
* @param {string} text
* @param {number} x
* @param {number} y
* @param {number=} opt_maxWidth
* @return {undefined}
*/
BaseRenderingContext2D.prototype.fillText = function(
text, x, y, opt_maxWidth) {};
/**
* @param {string} text
* @param {number} x
* @param {number} y
* @param {number=} opt_maxWidth
* @return {undefined}
*/
BaseRenderingContext2D.prototype.strokeText = function(
text, x, y, opt_maxWidth) {};
/**
* @param {string} text
* @return {!TextMetrics}
* @nosideeffects
*/
BaseRenderingContext2D.prototype.measureText = function(text) {};
/**
* @param {CanvasImageSource} image
* @param {number} dx Destination x coordinate.
* @param {number} dy Destination y coordinate.
* @param {number=} opt_dw Destination box width. Defaults to the image width.
* @param {number=} opt_dh Destination box height.
* Defaults to the image height.
* @param {number=} opt_sx Source box x coordinate. Used to select a portion of
* the source image to draw. Defaults to 0.
* @param {number=} opt_sy Source box y coordinate. Used to select a portion of
* the source image to draw. Defaults to 0.
* @param {number=} opt_sw Source box width. Used to select a portion of
* the source image to draw. Defaults to the full image width.
* @param {number=} opt_sh Source box height. Used to select a portion of
* the source image to draw. Defaults to the full image height.
* @return {undefined}
*/
BaseRenderingContext2D.prototype.drawImage = function(
image, dx, dy, opt_dw, opt_dh, opt_sx, opt_sy, opt_sw, opt_sh) {};
/**
* @param {number} sw
* @param {number} sh
* @return {!ImageData}
* @throws {Error}
* @nosideeffects
*/
BaseRenderingContext2D.prototype.createImageData = function(sw, sh) {};
/**
* @param {number} sx
* @param {number} sy
* @param {number} sw
* @param {number} sh
* @return {!ImageData}
* @throws {Error}
*/
BaseRenderingContext2D.prototype.getImageData = function(sx, sy, sw, sh) {};
/**
* @param {ImageData} imagedata
* @param {number} dx
* @param {number} dy
* @param {number=} opt_dirtyX
* @param {number=} opt_dirtyY
* @param {number=} opt_dirtyWidth
* @param {number=} opt_dirtyHeight
* @return {undefined}
*/
BaseRenderingContext2D.prototype.putImageData = function(imagedata, dx, dy,
opt_dirtyX, opt_dirtyY, opt_dirtyWidth, opt_dirtyHeight) {};
/**
* Note: WebKit only
* @param {number|string=} opt_a
* @param {number=} opt_b
* @param {number=} opt_c
* @param {number=} opt_d
* @param {number=} opt_e
* @see http://developer.apple.com/library/safari/#documentation/appleapplications/reference/WebKitDOMRef/CanvasRenderingContext2D_idl/Classes/CanvasRenderingContext2D/index.html
* @return {undefined}
* @deprecated
*/
BaseRenderingContext2D.prototype.setFillColor = function(
opt_a, opt_b, opt_c, opt_d, opt_e) {};
/**
* Note: WebKit only
* @param {number|string=} opt_a
* @param {number=} opt_b
* @param {number=} opt_c
* @param {number=} opt_d
* @param {number=} opt_e
* @see http://developer.apple.com/library/safari/#documentation/appleapplications/reference/WebKitDOMRef/CanvasRenderingContext2D_idl/Classes/CanvasRenderingContext2D/index.html
* @return {undefined}
* @deprecated
*/
BaseRenderingContext2D.prototype.setStrokeColor = function(
opt_a, opt_b, opt_c, opt_d, opt_e) {};
/**
* @return {!Array<number>}
* @override
*/
BaseRenderingContext2D.prototype.getLineDash = function() {};
/**
* @param {Array<number>} segments
* @return {undefined}
* @override
*/
BaseRenderingContext2D.prototype.setLineDash = function(segments) {};
/** @type {string} */
BaseRenderingContext2D.prototype.fillColor;
/**
* @type {string|!CanvasGradient|!CanvasPattern}
* @see https://html.spec.whatwg.org/multipage/scripting.html#fill-and-stroke-styles:dom-context-2d-fillstyle
* @implicitCast
*/
BaseRenderingContext2D.prototype.fillStyle;
/** @type {string} */
BaseRenderingContext2D.prototype.font;
/** @type {number} */
BaseRenderingContext2D.prototype.globalAlpha;
/** @type {string} */
BaseRenderingContext2D.prototype.globalCompositeOperation;
/** @type {number} */
BaseRenderingContext2D.prototype.lineWidth;
/** @type {string} */
BaseRenderingContext2D.prototype.lineCap;
/** @type {string} */
BaseRenderingContext2D.prototype.lineJoin;
/** @type {number} */
BaseRenderingContext2D.prototype.miterLimit;
/** @type {number} */
BaseRenderingContext2D.prototype.shadowBlur;
/** @type {string} */
BaseRenderingContext2D.prototype.shadowColor;
/** @type {number} */
BaseRenderingContext2D.prototype.shadowOffsetX;
/** @type {number} */
BaseRenderingContext2D.prototype.shadowOffsetY;
/** @type {boolean} */
BaseRenderingContext2D.prototype.imageSmoothingEnabled;
/**
* @type {string}
* @see https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/imageSmoothingQuality
*/
BaseRenderingContext2D.prototype.imageSmoothingQuality;
/**
* @type {string|!CanvasGradient|!CanvasPattern}
* @see https://html.spec.whatwg.org/multipage/scripting.html#fill-and-stroke-styles:dom-context-2d-strokestyle
* @implicitCast
*/
BaseRenderingContext2D.prototype.strokeStyle;
/** @type {string} */
BaseRenderingContext2D.prototype.strokeColor;
/** @type {string} */
BaseRenderingContext2D.prototype.textAlign;
/** @type {string} */
BaseRenderingContext2D.prototype.textBaseline;
/** @type {number} */
BaseRenderingContext2D.prototype.lineDashOffset;
/**
* @type {string}
* @see https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/direction
*/
BaseRenderingContext2D.prototype.direction;
/**
* @constructor
* @extends {BaseRenderingContext2D}
* @see http://www.w3.org/TR/2dcontext/#canvasrenderingcontext2d
*/
function CanvasRenderingContext2D() {}
/** @const {!HTMLCanvasElement} */
CanvasRenderingContext2D.prototype.canvas;
/**
* @type {string}
* @see https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/filter
*/
CanvasRenderingContext2D.prototype.filter;
/**
* @constructor
* @extends {BaseRenderingContext2D}
* @see http://www.w3.org/TR/2dcontext/#canvasrenderingcontext2d
*/
function OffscreenCanvasRenderingContext2D() {}
/** @const {!OffscreenCanvas} */
OffscreenCanvasRenderingContext2D.prototype.canvas;
/**
* @constructor
*/
function CanvasGradient() {}
/**
* @param {number} offset
* @param {string} color
* @return {undefined}
*/
CanvasGradient.prototype.addColorStop = function(offset, color) {};
/**
* @constructor
*/
function CanvasPattern() {}
/**
* @constructor
*/
function TextMetrics() {}
/** @const {number} */
TextMetrics.prototype.width;
/** @const {number|undefined} */
TextMetrics.prototype.actualBoundingBoxAscent;
/** @const {number|undefined} */
TextMetrics.prototype.actualBoundingBoxDescent;
/** @const {number|undefined} */
TextMetrics.prototype.actualBoundingBoxLeft;
/** @const {number|undefined} */
TextMetrics.prototype.actualBoundingBoxRight;
/**
* @param {!Uint8ClampedArray|number} dataOrWidth In the first form, this is the
* array of pixel data. In the second form, this is the image width.
* @param {number} widthOrHeight In the first form, this is the image width. In
* the second form, this is the image height.
* @param {number=} opt_height In the first form, this is the optional image
* height. The second form omits this argument.
* @see https://html.spec.whatwg.org/multipage/scripting.html#imagedata
* @constructor
*/
function ImageData(dataOrWidth, widthOrHeight, opt_height) {}
/** @const {!Uint8ClampedArray} */
ImageData.prototype.data;
/** @const {number} */
ImageData.prototype.width;
/** @const {number} */
ImageData.prototype.height;
/**
* @see https://www.w3.org/TR/html51/webappapis.html#webappapis-images
* @interface
*/
function ImageBitmap() {}
/**
* @const {number}
*/
ImageBitmap.prototype.width;
/**
* @const {number}
*/
ImageBitmap.prototype.height;
/**
* Releases ImageBitmap's underlying bitmap data.
* @return {undefined}
* @see https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#images-2
*/
ImageBitmap.prototype.close = function() {};
/**
* @typedef {!CanvasImageSource | !Blob | !ImageData}
* @see https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#imagebitmapsource
*/
var ImageBitmapSource;
/**
* @typedef {{
* imageOrientation: (string|undefined),
* premultiplyAlpha: (string|undefined),
* colorSpaceConversion: (string|undefined),
* resizeWidth: (number|undefined),
* resizeHeight: (number|undefined),
* resizeQuality: (string|undefined)
* }}
* @see https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#images-2
*/
var ImageBitmapOptions;
/**
* @param {!ImageBitmapSource} image
* @param {(number|!ImageBitmapOptions)=} sxOrOptions
* @param {number=} sy
* @param {number=} sw
* @param {number=} sh
* @param {!ImageBitmapOptions=} options
* @return {!Promise<!ImageBitmap>}
* @see https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#dom-createimagebitmap
* @see https://html.spec.whatwg.org/multipage/webappapis.html#windoworworkerglobalscope-mixin
*/
function createImageBitmap(image, sxOrOptions, sy, sw, sh, options) {}
/**
* @constructor
*/
function ClientInformation() {}
/** @type {boolean} */
ClientInformation.prototype.onLine;
/**
* @param {string} protocol
* @param {string} uri
* @param {string} title
* @return {undefined}
*/
ClientInformation.prototype.registerProtocolHandler = function(
protocol, uri, title) {};
/**
* @param {string} mimeType
* @param {string} uri
* @param {string} title
* @return {undefined}
*/
ClientInformation.prototype.registerContentHandler = function(
mimeType, uri, title) {};
// HTML5 Database objects
/**
* @constructor
*/
function Database() {}
/**
* @type {string}
*/
Database.prototype.version;
/**
* @param {function(!SQLTransaction) : void} callback
* @param {(function(!SQLError) : void)=} opt_errorCallback
* @param {Function=} opt_Callback
* @return {undefined}
*/
Database.prototype.transaction = function(
callback, opt_errorCallback, opt_Callback) {};
/**
* @param {function(!SQLTransaction) : void} callback
* @param {(function(!SQLError) : void)=} opt_errorCallback
* @param {Function=} opt_Callback
* @return {undefined}
*/
Database.prototype.readTransaction = function(
callback, opt_errorCallback, opt_Callback) {};
/**
* @param {string} oldVersion
* @param {string} newVersion
* @param {function(!SQLTransaction) : void} callback
* @param {function(!SQLError) : void} errorCallback
* @param {Function} successCallback
* @return {undefined}
*/
Database.prototype.changeVersion = function(
oldVersion, newVersion, callback, errorCallback, successCallback) {};
/**
* @interface
*/
function DatabaseCallback() {}
/**
* @param {!Database} db
* @return {undefined}
*/
DatabaseCallback.prototype.handleEvent = function(db) {};
/**
* @constructor
*/
function SQLError() {}
/**
* @type {number}
*/
SQLError.prototype.code;
/**
* @type {string}
*/
SQLError.prototype.message;
/**
* @constructor
*/
function SQLTransaction() {}
/**
* @param {string} sqlStatement
* @param {Array<*>=} opt_queryArgs
* @param {SQLStatementCallback=} opt_callback
* @param {(function(!SQLTransaction, !SQLError) : (boolean|void))=}
* opt_errorCallback
* @return {undefined}
*/
SQLTransaction.prototype.executeSql = function(
sqlStatement, opt_queryArgs, opt_callback, opt_errorCallback) {};
/**
* @typedef {(function(!SQLTransaction, !SQLResultSet) : void)}
*/
var SQLStatementCallback;
/**
* @constructor
*/
function SQLResultSet() {}
/**
* @type {number}
*/
SQLResultSet.prototype.insertId;
/**
* @type {number}
*/
SQLResultSet.prototype.rowsAffected;
/**
* @type {!SQLResultSetRowList}
*/
SQLResultSet.prototype.rows;
/**
* @constructor
* @implements {IArrayLike<!Object>}
* @see http://www.w3.org/TR/webdatabase/#sqlresultsetrowlist
*/
function SQLResultSetRowList() {}
/**
* @type {number}
*/
SQLResultSetRowList.prototype.length;
/**
* @param {number} index
* @return {Object}
* @nosideeffects
*/
SQLResultSetRowList.prototype.item = function(index) {};
/**
* @param {string} name
* @param {string} version
* @param {string} description
* @param {number} size
* @param {(DatabaseCallback|function(Database))=} opt_callback
* @return {!Database}
*/
function openDatabase(name, version, description, size, opt_callback) {}
/**
* @param {string} name
* @param {string} version
* @param {string} description
* @param {number} size
* @param {(DatabaseCallback|function(Database))=} opt_callback
* @return {!Database}
*/
Window.prototype.openDatabase =
function(name, version, description, size, opt_callback) {};
/**
* @type {boolean}
* @see https://www.w3.org/TR/html5/embedded-content-0.html#dom-img-complete
*/
HTMLImageElement.prototype.complete;
/**
* @type {number}
* @see https://www.w3.org/TR/html5/embedded-content-0.html#dom-img-naturalwidth
*/
HTMLImageElement.prototype.naturalWidth;
/**
* @type {number}
* @see https://www.w3.org/TR/html5/embedded-content-0.html#dom-img-naturalheight
*/
HTMLImageElement.prototype.naturalHeight;
/**
* @type {string}
* @see http://www.whatwg.org/specs/web-apps/current-work/multipage/embedded-content-1.html#attr-img-crossorigin
*/
HTMLImageElement.prototype.crossOrigin;
/**
* @type {string}
* @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-img-currentsrc
*/
HTMLImageElement.prototype.currentSrc;
/**
* @type {string}
* @see https://html.spec.whatwg.org/multipage/images.html#image-decoding-hint
*/
HTMLImageElement.prototype.decoding;
/**
* @return {!Promise<undefined>}
* @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-img-decode
*/
HTMLImageElement.prototype.decode;
/**
* This is a superposition of the Window and Worker postMessage methods.
* @param {*} message
* @param {(string|!Array<!Transferable>)=} opt_targetOriginOrTransfer
* @param {(string|!Array<!MessagePort>|!Array<!Transferable>)=}
* opt_targetOriginOrPortsOrTransfer
* @return {void}
*/
function postMessage(message, opt_targetOriginOrTransfer,
opt_targetOriginOrPortsOrTransfer) {}
/**
* @param {*} message
* @param {string=} targetOrigin
* @param {(!Array<!Transferable>)=} transfer
* @return {void}
* @see https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
*/
Window.prototype.postMessage = function(message, targetOrigin, transfer) {};
/**
* The postMessage method (as implemented in Opera).
* @param {string} message
*/
Document.prototype.postMessage = function(message) {};
/**
* Document head accessor.
* @see http://www.whatwg.org/specs/web-apps/current-work/multipage/dom.html#the-head-element-0
* @type {HTMLHeadElement}
*/
Document.prototype.head;
/**
* @type {string}
* @see https://html.spec.whatwg.org/multipage/dom.html#current-document-readiness
*/
Document.prototype.readyState;
/**
* @see https://html.spec.whatwg.org/#application-cache-api
* @constructor
* @implements {EventTarget}
*/
function ApplicationCache() {}
/** @override */
ApplicationCache.prototype.addEventListener = function(
type, listener, opt_options) {};
/** @override */
ApplicationCache.prototype.removeEventListener = function(
type, listener, opt_options) {};
/** @override */
ApplicationCache.prototype.dispatchEvent = function(evt) {};
/**
* The object isn't associated with an application cache. This can occur if the
* update process fails and there is no previous cache to revert to, or if there
* is no manifest file.
* @const {number}
*/
ApplicationCache.prototype.UNCACHED;
/**
* The object isn't associated with an application cache. This can occur if the
* update process fails and there is no previous cache to revert to, or if there
* is no manifest file.
* @const {number}
*/
ApplicationCache.UNCACHED;
/**
* The cache is idle.
* @const {number}
*/
ApplicationCache.prototype.IDLE;
/**
* The cache is idle.
* @const {number}
*/
ApplicationCache.IDLE;
/**
* The update has started but the resources are not downloaded yet - for
* example, this can happen when the manifest file is fetched.
* @const {number}
*/
ApplicationCache.prototype.CHECKING;
/**
* The update has started but the resources are not downloaded yet - for
* example, this can happen when the manifest file is fetched.
* @const {number}
*/
ApplicationCache.CHECKING;
/**
* The resources are being downloaded into the cache.
* @const {number}
*/
ApplicationCache.prototype.DOWNLOADING;
/**
* The resources are being downloaded into the cache.
* @const {number}
*/
ApplicationCache.DOWNLOADING;
/**
* Resources have finished downloading and the new cache is ready to be used.
* @const {number}
*/
ApplicationCache.prototype.UPDATEREADY;
/**
* Resources have finished downloading and the new cache is ready to be used.
* @const {number}
*/
ApplicationCache.UPDATEREADY;
/**
* The cache is obsolete.
* @const {number}
*/
ApplicationCache.prototype.OBSOLETE;
/**
* The cache is obsolete.
* @const {number}
*/
ApplicationCache.OBSOLETE;
/**
* The current status of the application cache.
* @type {number}
*/
ApplicationCache.prototype.status;
/**
* Sent when the update process finishes for the first time; that is, the first
* time an application cache is saved.
* @type {?function(!Event): void}
*/
ApplicationCache.prototype.oncached;
/**
* Sent when the cache update process begins.
* @type {?function(!Event): void}
*/
ApplicationCache.prototype.onchecking;
/**
* Sent when the update process begins downloading resources in the manifest
* file.
* @type {?function(!Event): void}
*/
ApplicationCache.prototype.ondownloading;
/**
* Sent when an error occurs.
* @type {?function(!Event): void}
*/
ApplicationCache.prototype.onerror;
/**
* Sent when the update process finishes but the manifest file does not change.
* @type {?function(!Event): void}
*/
ApplicationCache.prototype.onnoupdate;
/**
* Sent when each resource in the manifest file begins to download.
* @type {?function(!Event): void}
*/
ApplicationCache.prototype.onprogress;
/**
* Sent when there is an existing application cache, the update process
* finishes, and there is a new application cache ready for use.
* @type {?function(!Event): void}
*/
ApplicationCache.prototype.onupdateready;
/**
* Replaces the active cache with the latest version.
* @throws {DOMException}
* @return {undefined}
*/
ApplicationCache.prototype.swapCache = function() {};
/**
* Manually triggers the update process.
* @throws {DOMException}
* @return {undefined}
*/
ApplicationCache.prototype.update = function() {};
/** @type {?ApplicationCache} */
var applicationCache;
/** @type {ApplicationCache} */
Window.prototype.applicationCache;
/**
* @see https://developer.mozilla.org/En/DOM/Worker/Functions_available_to_workers
* @param {...!TrustedScriptURL|string} var_args
* @return {undefined}
*/
Window.prototype.importScripts = function(var_args) {};
/**
* Decodes a string of data which has been encoded using base-64 encoding.
*
* @param {string} encodedData
* @return {string}
* @nosideeffects
* @see https://html.spec.whatwg.org/multipage/webappapis.html#dom-atob
*/
function atob(encodedData) {}
/**
* @param {string} stringToEncode
* @return {string}
* @nosideeffects
* @see https://html.spec.whatwg.org/multipage/webappapis.html#dom-btoa
*/
function btoa(stringToEncode) {}
/**
* @see https://developer.mozilla.org/En/DOM/Worker/Functions_available_to_workers
* @param {...!TrustedScriptURL|string} var_args
* @return {undefined}
*/
function importScripts(var_args) {}
/**
* @see http://dev.w3.org/html5/workers/
* @param {!TrustedScriptURL|string} scriptURL
* @param {!WorkerOptions=} opt_options
* @constructor
* @implements {EventTarget}
*/
function Worker(scriptURL, opt_options) {}
/** @override */
Worker.prototype.addEventListener = function(type, listener, opt_options) {};
/** @override */
Worker.prototype.removeEventListener = function(type, listener, opt_options) {};
/** @override */
Worker.prototype.dispatchEvent = function(evt) {};
/**
* Stops the worker process
* @return {undefined}
*/
Worker.prototype.terminate = function() {};
/**
* Posts a message to the worker thread.
* @param {*} message
* @param {Array<!Transferable>=} opt_transfer
* @return {undefined}
*/
Worker.prototype.postMessage = function(message, opt_transfer) {};
/**
* Posts a message to the worker thread.
* @param {*} message
* @param {Array<!Transferable>=} opt_transfer
* @return {undefined}
*/
Worker.prototype.webkitPostMessage = function(message, opt_transfer) {};
/**
* Sent when the worker thread posts a message to its creator.
* @type {?function(!MessageEvent<*>): void}
*/
Worker.prototype.onmessage;
/**
* Sent when the worker thread encounters an error.
* @type {?function(!ErrorEvent): void}
*/
Worker.prototype.onerror;
/**
* @see http://dev.w3.org/html5/workers/
* @record
*/
function WorkerOptions() {}
/**
* Defines a name for the new global environment of the worker, primarily for
* debugging purposes.
* @type {string|undefined}
*/
WorkerOptions.prototype.name;
/**
* 'classic' or 'module'. Default: 'classic'.
* Specifying 'module' ensures the worker environment supports JavaScript
* modules.
* @type {string|undefined}
*/
WorkerOptions.prototype.type;
// WorkerOptions.prototype.credentials is defined in fetchapi.js.
// if type = 'module', it specifies how scriptURL is fetched.
/**
* @see http://dev.w3.org/html5/workers/
* @param {!TrustedScriptURL|string} scriptURL The URL of the script to run in
* the SharedWorker.
* @param {(string|!WorkerOptions)=} options A name that can
* later be used to obtain a reference to the same SharedWorker or a
* WorkerOptions object which can be be used to specify how scriptURL is
* fetched through the credentials option.
* @constructor
* @implements {EventTarget}
*/
function SharedWorker(scriptURL, options) {}
/** @override */
SharedWorker.prototype.addEventListener = function(
type, listener, opt_options) {};
/** @override */
SharedWorker.prototype.removeEventListener = function(
type, listener, opt_options) {};
/** @override */
SharedWorker.prototype.dispatchEvent = function(evt) {};
/**
* @type {!MessagePort}
*/
SharedWorker.prototype.port;
/**
* Called on network errors for loading the initial script.
* @type {?function(!ErrorEvent): void}
*/
SharedWorker.prototype.onerror;
/**
* @see http://dev.w3.org/html5/workers/
* @see http://www.w3.org/TR/url-1/#dom-urlutilsreadonly
* @interface
*/
function WorkerLocation() {}
/** @type {string} */
WorkerLocation.prototype.href;
/** @type {string} */
WorkerLocation.prototype.origin;
/** @type {string} */
WorkerLocation.prototype.protocol;
/** @type {string} */
WorkerLocation.prototype.host;
/** @type {string} */
WorkerLocation.prototype.hostname;
/** @type {string} */
WorkerLocation.prototype.port;
/** @type {string} */
WorkerLocation.prototype.pathname;
/** @type {string} */
WorkerLocation.prototype.search;
/** @type {string} */
WorkerLocation.prototype.hash;
/**
* @see http://dev.w3.org/html5/workers/
* @interface
* @extends {EventTarget}
*/
function WorkerGlobalScope() {}
/** @type {!WorkerGlobalScope} */
WorkerGlobalScope.prototype.self;
/** @type {!WorkerLocation} */
WorkerGlobalScope.prototype.location;
/**
* @const {string}
* @see https://html.spec.whatwg.org/#windoworworkerglobalscope-mixin
*/
WorkerGlobalScope.prototype.origin;
/**
* @const {string}
* Duplicate definition, since we don't model WindowOrWorkerGlobalScope.
* @see https://html.spec.whatwg.org/#windoworworkerglobalscope-mixin
*/
Window.prototype.origin;
/**
* Closes the worker represented by this WorkerGlobalScope.
* @return {undefined}
*/
WorkerGlobalScope.prototype.close = function() {};
/**
* Sent when the worker encounters an error.
* @type {?function(string, string, number, number, !Error): void}
*/
WorkerGlobalScope.prototype.onerror;
/**
* Sent when the worker goes offline.
* @type {?function(!Event): void}
*/
WorkerGlobalScope.prototype.onoffline;
/**
* Sent when the worker goes online.
* @type {?function(!Event): void}
*/
WorkerGlobalScope.prototype.ononline;
/** @type {!WorkerPerformance} */
WorkerGlobalScope.prototype.performance;
/** @type {!WorkerNavigator} */
WorkerGlobalScope.prototype.navigator;
/**
* Worker postMessage method.
* @param {*} message
* @param {(!Array<!Transferable>)=} transfer
* @return {void}
*/
WorkerGlobalScope.prototype.postMessage = function(message, transfer) {};
/**
* @see http://dev.w3.org/html5/workers/
* @interface
* @extends {WorkerGlobalScope}
*/
function DedicatedWorkerGlobalScope() {}
/**
* Posts a message to creator of this worker.
* @param {*} message
* @param {Array<!Transferable>=} opt_transfer
* @return {undefined}
*/
DedicatedWorkerGlobalScope.prototype.postMessage =
function(message, opt_transfer) {};
/**
* Posts a message to creator of this worker.
* @param {*} message
* @param {Array<!Transferable>=} opt_transfer
* @return {undefined}
*/
DedicatedWorkerGlobalScope.prototype.webkitPostMessage =
function(message, opt_transfer) {};
/**
* Sent when the creator posts a message to this worker.
* @type {?function(!MessageEvent<*>): void}
*/
DedicatedWorkerGlobalScope.prototype.onmessage;
/**
* @see http://dev.w3.org/html5/workers/
* @interface
* @extends {WorkerGlobalScope}
*/
function SharedWorkerGlobalScope() {}
/** @type {string} */
SharedWorkerGlobalScope.prototype.name;
/**
* Sent when a connection to this worker is opened.
* @type {?function(!Event)}
*/
SharedWorkerGlobalScope.prototype.onconnect;
/** @type {!Array<string>|undefined} */
HTMLElement.observedAttributes;
/**
* @param {!Document} oldDocument
* @param {!Document} newDocument
*/
HTMLElement.prototype.adoptedCallback = function(oldDocument, newDocument) {};
/**
* @param {!ShadowRootInit} options
* @return {!ShadowRoot}
*/
HTMLElement.prototype.attachShadow = function(options) {};
/**
* @param {string} attributeName
* @param {?string} oldValue
* @param {?string} newValue
* @param {?string} namespace
*/
HTMLElement.prototype.attributeChangedCallback = function(attributeName, oldValue, newValue, namespace) {};
/** @type {function()|undefined} */
HTMLElement.prototype.connectedCallback;
/** @type {Element} */
HTMLElement.prototype.contextMenu;
/** @type {function()|undefined} */
HTMLElement.prototype.disconnectedCallback;
/** @type {boolean} */
HTMLElement.prototype.draggable;
/**
* This is actually a DOMSettableTokenList property. However since that
* interface isn't currently defined and no known browsers implement this
* feature, just define the property for now.
*
* @const {Object}
*/
HTMLElement.prototype.dropzone;
/** @type {boolean} */
HTMLElement.prototype.hidden;
/** @type {boolean} */
HTMLElement.prototype.inert;
/** @type {boolean} */
HTMLElement.prototype.spellcheck;
/**
* @see https://dom.spec.whatwg.org/#dictdef-getrootnodeoptions
* @typedef {{
* composed: boolean
* }}
*/
var GetRootNodeOptions;
/**
* @see https://dom.spec.whatwg.org/#dom-node-getrootnode
* @param {GetRootNodeOptions=} opt_options
* @return {!Node}
*/
Node.prototype.getRootNode = function(opt_options) {};
/**
* @see http://www.w3.org/TR/components-intro/
* @return {!ShadowRoot}
*/
HTMLElement.prototype.createShadowRoot;
/**
* @see http://www.w3.org/TR/components-intro/
* @return {!ShadowRoot}
*/
HTMLElement.prototype.webkitCreateShadowRoot;
/**
* @see http://www.w3.org/TR/shadow-dom/
* @type {ShadowRoot}
*/
HTMLElement.prototype.shadowRoot;
/**
* @see http://www.w3.org/TR/shadow-dom/
* @return {!NodeList<!Node>}
*/
HTMLElement.prototype.getDestinationInsertionPoints = function() {};
/**
* @see http://www.w3.org/TR/components-intro/
* @type {function()}
*/
HTMLElement.prototype.createdCallback;
/**
* @see http://w3c.github.io/webcomponents/explainer/#lifecycle-callbacks
* @type {function()}
*/
HTMLElement.prototype.attachedCallback;
/**
* @see http://w3c.github.io/webcomponents/explainer/#lifecycle-callbacks
* @type {function()}
*/
HTMLElement.prototype.detachedCallback;
/**
* Cryptographic nonce used by Content Security Policy.
* @see https://html.spec.whatwg.org/multipage/dom.html#elements-in-the-dom:noncedelement
* @type {?string}
*/
HTMLElement.prototype.nonce;
/** @type {string} */
HTMLAnchorElement.prototype.download;
/** @type {string} */
HTMLAnchorElement.prototype.hash;
/** @type {string} */
HTMLAnchorElement.prototype.host;
/** @type {string} */
HTMLAnchorElement.prototype.hostname;
/** @type {string} */
HTMLAnchorElement.prototype.pathname;
/**
* The 'ping' attribute is known to be supported in recent versions (as of
* mid-2014) of Chrome, Safari, and Firefox, and is not supported in any
* current version of Internet Explorer.
*
* @type {string}
* @see http://www.whatwg.org/specs/web-apps/current-work/multipage/semantics.html#hyperlink-auditing
*/
HTMLAnchorElement.prototype.ping;
/** @type {string} */
HTMLAnchorElement.prototype.port;
/** @type {string} */
HTMLAnchorElement.prototype.protocol;
/** @type {!DOMTokenList} */
HTMLAnchorElement.prototype.relList;
/** @type {string} */
HTMLAnchorElement.prototype.search;
/** @type {string} */
HTMLAreaElement.prototype.download;
/**
* @type {string}
* @see http://www.whatwg.org/specs/web-apps/current-work/multipage/semantics.html#hyperlink-auditing
*/
HTMLAreaElement.prototype.ping;
/**
* @type {string}
* @implicitCast
* @see http://www.w3.org/TR/html-markup/iframe.html#iframe.attrs.srcdoc
*/
HTMLIFrameElement.prototype.srcdoc;
/**
* @type {?DOMTokenList}
* @see http://www.w3.org/TR/2012/WD-html5-20121025/the-iframe-element.html#attr-iframe-sandbox
*/
HTMLIFrameElement.prototype.sandbox;
/**
* @type {string}
* @see https://html.spec.whatwg.org/multipage/iframe-embed-object.html#attr-iframe-allow
*/
HTMLIFrameElement.prototype.allow;
/**
* @type {Window}
* @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLIFrameElement/contentWindow
*/
HTMLIFrameElement.prototype.contentWindow;
/** @type {string} */
HTMLInputElement.prototype.autocomplete;
/** @type {string} */
HTMLInputElement.prototype.dirname;
/** @type {FileList} */
HTMLInputElement.prototype.files;
/**
* @type {boolean}
* @see https://www.w3.org/TR/html5/forms.html#dom-input-indeterminate
*/
HTMLInputElement.prototype.indeterminate;
/** @type {string} */
HTMLInputElement.prototype.list;
/** @implicitCast @type {string} */
HTMLInputElement.prototype.max;
/** @implicitCast @type {string} */
HTMLInputElement.prototype.min;
/** @type {string} */
HTMLInputElement.prototype.pattern;
/** @type {boolean} */
HTMLInputElement.prototype.multiple;
/** @type {string} */
HTMLInputElement.prototype.placeholder;
/** @type {boolean} */
HTMLInputElement.prototype.required;
/** @implicitCast @type {string} */
HTMLInputElement.prototype.step;
/** @type {Date} */
HTMLInputElement.prototype.valueAsDate;
/** @type {number} */
HTMLInputElement.prototype.valueAsNumber;
/**
* Changes the form control's value by the value given in the step attribute
* multiplied by opt_n.
* @param {number=} opt_n step multiplier. Defaults to 1.
* @return {undefined}
*/
HTMLInputElement.prototype.stepDown = function(opt_n) {};
/**
* Changes the form control's value by the value given in the step attribute
* multiplied by opt_n.
* @param {number=} opt_n step multiplier. Defaults to 1.
* @return {undefined}
*/
HTMLInputElement.prototype.stepUp = function(opt_n) {};
/**
* @constructor
* @extends {HTMLElement}
* @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement
*/
function HTMLMediaElement() {}
/**
* @see https://html.spec.whatwg.org/multipage/media.html#dom-media-network_empty
* @const {number}
*/
HTMLMediaElement.NETWORK_EMPTY;
/**
* @see https://html.spec.whatwg.org/multipage/media.html#dom-media-network_empty
* @const {number}
*/
HTMLMediaElement.prototype.NETWORK_EMPTY;
/**
* @see https://html.spec.whatwg.org/multipage/media.html#dom-media-network_idle
* @const {number}
*/
HTMLMediaElement.NETWORK_IDLE;
/**
* @see https://html.spec.whatwg.org/multipage/media.html#dom-media-network_idle
* @const {number}
*/
HTMLMediaElement.prototype.NETWORK_IDLE;
/**
* @see https://html.spec.whatwg.org/multipage/media.html#dom-media-network_loading
* @const {number}
*/
HTMLMediaElement.NETWORK_LOADING;
/**
* @see https://html.spec.whatwg.org/multipage/media.html#dom-media-network_loading
* @const {number}
*/
HTMLMediaElement.prototype.NETWORK_LOADING;
/**
* @see https://html.spec.whatwg.org/multipage/media.html#dom-media-network_no_source
* @const {number}
*/
HTMLMediaElement.NETWORK_NO_SOURCE;
/**
* @see https://html.spec.whatwg.org/multipage/media.html#dom-media-network_no_source
* @const {number}
*/
HTMLMediaElement.prototype.NETWORK_NO_SOURCE;
/**
* @see https://html.spec.whatwg.org/multipage/media.html#dom-media-have_nothing
* @const {number}
*/
HTMLMediaElement.HAVE_NOTHING;
/**
* @see https://html.spec.whatwg.org/multipage/media.html#dom-media-have_nothing
* @const {number}
*/
HTMLMediaElement.prototype.HAVE_NOTHING;
/**
* @see https://html.spec.whatwg.org/multipage/media.html#dom-media-have_metadata
* @const {number}
*/
HTMLMediaElement.HAVE_METADATA;
/**
* @see https://html.spec.whatwg.org/multipage/media.html#dom-media-have_metadata
* @const {number}
*/
HTMLMediaElement.prototype.HAVE_METADATA;
/**
* @see https://html.spec.whatwg.org/multipage/media.html#dom-media-have_current_data
* @const {number}
*/
HTMLMediaElement.HAVE_CURRENT_DATA;
/**
* @see https://html.spec.whatwg.org/multipage/media.html#dom-media-have_current_data
* @const {number}
*/
HTMLMediaElement.prototype.HAVE_CURRENT_DATA;
/**
* @see https://html.spec.whatwg.org/multipage/media.html#dom-media-have_future_data
* @const {number}
*/
HTMLMediaElement.HAVE_FUTURE_DATA;
/**
* @see https://html.spec.whatwg.org/multipage/media.html#dom-media-have_future_data
* @const {number}
*/
HTMLMediaElement.prototype.HAVE_FUTURE_DATA;
/**
* @see https://html.spec.whatwg.org/multipage/media.html#dom-media-have_enough_data
* @const {number}
*/
HTMLMediaElement.HAVE_ENOUGH_DATA;
/**
* @see https://html.spec.whatwg.org/multipage/media.html#dom-media-have_enough_data
* @const {number}
*/
HTMLMediaElement.prototype.HAVE_ENOUGH_DATA;
/** @type {MediaError} */
HTMLMediaElement.prototype.error;
/** @type {string} @implicitCast */
HTMLMediaElement.prototype.src;
/** @type {string} */
HTMLMediaElement.prototype.currentSrc;
/** @type {number} */
HTMLMediaElement.prototype.networkState;
/** @type {boolean} */
HTMLMediaElement.prototype.autobuffer;
/** @type {!TimeRanges} */
HTMLMediaElement.prototype.buffered;
/** @type {?MediaStream} */
HTMLMediaElement.prototype.srcObject;
/**
* Loads the media element.
* @return {undefined}
*/
HTMLMediaElement.prototype.load = function() {};
/**
* @param {string} type Type of the element in question in question.
* @return {string} Whether it can play the type.
* @nosideeffects
*/
HTMLMediaElement.prototype.canPlayType = function(type) {};
/** Event handlers */
/** @type {?function(Event)} */
HTMLMediaElement.prototype.onabort;
/** @type {?function(!Event)} */
HTMLMediaElement.prototype.oncanplay;
/** @type {?function(!Event)} */
HTMLMediaElement.prototype.oncanplaythrough;
/** @type {?function(!Event)} */
HTMLMediaElement.prototype.ondurationchange;
/** @type {?function(!Event)} */
HTMLMediaElement.prototype.onemptied;
/** @type {?function(!Event)} */
HTMLMediaElement.prototype.onended;
/** @type {?function(Event)} */
HTMLMediaElement.prototype.onerror;
/** @type {?function(!Event)} */
HTMLMediaElement.prototype.onloadeddata;
/** @type {?function(!Event)} */
HTMLMediaElement.prototype.onloadedmetadata;
/** @type {?function(!Event)} */
HTMLMediaElement.prototype.onloadstart;
/** @type {?function(!Event)} */
HTMLMediaElement.prototype.onpause;
/** @type {?function(!Event)} */
HTMLMediaElement.prototype.onplay;
/** @type {?function(!Event)} */
HTMLMediaElement.prototype.onplaying;
/** @type {?function(!Event)} */
HTMLMediaElement.prototype.onprogress;
/** @type {?function(!Event)} */
HTMLMediaElement.prototype.onratechange;
/** @type {?function(!Event)} */
HTMLMediaElement.prototype.onseeked;
/** @type {?function(!Event)} */
HTMLMediaElement.prototype.onseeking;
/** @type {?function(!Event)} */
HTMLMediaElement.prototype.onstalled;
/** @type {?function(!Event)} */
HTMLMediaElement.prototype.onsuspend;
/** @type {?function(!Event)} */
HTMLMediaElement.prototype.ontimeupdate;
/** @type {?function(!Event)} */
HTMLMediaElement.prototype.onvolumechange;
/** @type {?function(!Event)} */
HTMLMediaElement.prototype.onwaiting;
/** @type {?function(Event)} */
HTMLImageElement.prototype.onload;
/** @type {?function(Event)} */
HTMLImageElement.prototype.onerror;
/** @type {string} */
HTMLMediaElement.prototype.preload;
/** @type {number} */
HTMLMediaElement.prototype.readyState;
/** @type {boolean} */
HTMLMediaElement.prototype.seeking;
/**
* @type {string}
* @see https://html.spec.whatwg.org/multipage/media.html#dom-media-crossorigin
*/
HTMLMediaElement.prototype.crossOrigin;
/**
* The current time, in seconds.
* @type {number}
*/
HTMLMediaElement.prototype.currentTime;
/**
* The absolute timeline offset.
* @return {!Date}
*/
HTMLMediaElement.prototype.getStartDate = function() {};
/**
* The length of the media in seconds.
* @type {number}
*/
HTMLMediaElement.prototype.duration;
/** @type {boolean} */
HTMLMediaElement.prototype.paused;
/** @type {number} */
HTMLMediaElement.prototype.defaultPlaybackRate;
/** @type {number} */
HTMLMediaElement.prototype.playbackRate;
/** @type {TimeRanges} */
HTMLMediaElement.prototype.played;
/** @type {TimeRanges} */
HTMLMediaElement.prototype.seekable;
/** @type {boolean} */
HTMLMediaElement.prototype.ended;
/** @type {boolean} */
HTMLMediaElement.prototype.autoplay;
/** @type {boolean} */
HTMLMediaElement.prototype.loop;
/**
* Starts playing the media.
* @return {?Promise<undefined>} This is a *nullable* Promise on purpose unlike
* the HTML5 spec because supported older browsers (incl. Smart TVs) don't
* return a Promise.
*/
HTMLMediaElement.prototype.play = function() {};
/**
* Pauses the media.
* @return {undefined}
*/
HTMLMediaElement.prototype.pause = function() {};
/** @type {boolean} */
HTMLMediaElement.prototype.controls;
/**
* The audio volume, from 0.0 (silent) to 1.0 (loudest).
* @type {number}
*/
HTMLMediaElement.prototype.volume;
/** @type {boolean} */
HTMLMediaElement.prototype.muted;
/**
* @see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#dom-media-addtexttrack
* @param {string} kind Kind of the text track.
* @param {string=} opt_label Label of the text track.
* @param {string=} opt_language Language of the text track.
* @return {!TextTrack} TextTrack object added to the media element.
*/
HTMLMediaElement.prototype.addTextTrack =
function(kind, opt_label, opt_language) {};
/** @type {!TextTrackList} */
HTMLMediaElement.prototype.textTracks;
/**
* The ID of the audio device through which output is being delivered, or an
* empty string if using the default device.
*
* Implemented as a draft spec in Chrome 49+.
*
* @see https://w3c.github.io/mediacapture-output/#htmlmediaelement-extensions
* @type {string}
*/
HTMLMediaElement.prototype.sinkId;
/**
* Sets the audio device through which output should be delivered.
*
* Implemented as a draft spec in Chrome 49+.
*
* @param {string} sinkId The ID of the audio output device, or empty string
* for default device.
*
* @see https://w3c.github.io/mediacapture-output/#htmlmediaelement-extensions
* @return {!Promise<void>}
*/
HTMLMediaElement.prototype.setSinkId = function(sinkId) {};
/**
* Produces a real-time capture of the media that is rendered to the media
* element.
* @return {!MediaStream}
* @see https://w3c.github.io/mediacapture-fromelement/#html-media-element-media-capture-extensions
*/
HTMLMediaElement.prototype.captureStream = function() {};
/**
* The Firefox flavor of captureStream.
* @return {!MediaStream}
* @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/captureStream#Browser_compatibility
*/
HTMLMediaElement.prototype.mozCaptureStream = function() {};
/**
* @constructor
* @extends {HTMLElement}
* @see https://html.spec.whatwg.org/multipage/dom.html#htmlunknownelement
* @see https://html.spec.whatwg.org/multipage/scripting.html#customized-built-in-element-restrictions
* @see https://w3c.github.io/webcomponents/spec/custom/#custom-elements-api
*/
function HTMLUnknownElement() {}
/**
* @see http://www.w3.org/TR/shadow-dom/
* @return {!NodeList<!Node>}
*/
Text.prototype.getDestinationInsertionPoints = function() {};
/**
* @see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#texttracklist
* @constructor
* @implements {EventTarget}
* @implements {IArrayLike<!TextTrack>}
*/
function TextTrackList() {}
/** @type {number} */
TextTrackList.prototype.length;
/**
* @param {string} id
* @return {TextTrack}
*/
TextTrackList.prototype.getTrackById = function(id) {};
/** @override */
TextTrackList.prototype.addEventListener = function(
type, listener, opt_useCapture) {};
/** @override */
TextTrackList.prototype.dispatchEvent = function(evt) {};
/** @override */
TextTrackList.prototype.removeEventListener = function(
type, listener, opt_options) {};
/**
* @see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#texttrack
* @constructor
* @implements {EventTarget}
*/
function TextTrack() {}
/**
* @param {TextTrackCue} cue
* @return {undefined}
*/
TextTrack.prototype.addCue = function(cue) {};
/**
* @param {TextTrackCue} cue
* @return {undefined}
*/
TextTrack.prototype.removeCue = function(cue) {};
/**
* @const {TextTrackCueList}
*/
TextTrack.prototype.activeCues;
/**
* @const {TextTrackCueList}
*/
TextTrack.prototype.cues;
/**
* @type {string}
*/
TextTrack.prototype.mode;
/** @override */
TextTrack.prototype.addEventListener = function(
type, listener, opt_useCapture) {};
/** @override */
TextTrack.prototype.dispatchEvent = function(evt) {};
/** @override */
TextTrack.prototype.removeEventListener = function(
type, listener, opt_options) {};
/**
* @see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#texttrackcuelist
* @constructor
* @implements {IArrayLike<!TextTrackCue>}
*/
function TextTrackCueList() {}
/** @const {number} */
TextTrackCueList.prototype.length;
/**
* @param {string} id
* @return {TextTrackCue}
*/
TextTrackCueList.prototype.getCueById = function(id) {};
/**
* @see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#texttrackcue
* @constructor
* @param {number} startTime
* @param {number} endTime
* @param {string} text
*/
function TextTrackCue(startTime, endTime, text) {}
/** @type {string} */
TextTrackCue.prototype.id;
/** @type {number} */
TextTrackCue.prototype.startTime;
/** @type {number} */
TextTrackCue.prototype.endTime;
/** @type {string} */
TextTrackCue.prototype.text;
/**
* @see https://w3c.github.io/webvtt/#vttregion
* @constructor
*/
function VTTRegion() {}
/** @type {string} */
VTTRegion.prototype.id;
/** @type {number} */
VTTRegion.prototype.width;
/** @type {number} */
VTTRegion.prototype.lines;
/** @type {number} */
VTTRegion.prototype.regionAnchorX;
/** @type {number} */
VTTRegion.prototype.regionAnchorY;
/** @type {number} */
VTTRegion.prototype.viewportAnchorX;
/** @type {number} */
VTTRegion.prototype.viewportAnchorY;
/**
* @see https://w3c.github.io/webvtt/#enumdef-scrollsetting
* @type {string}
*/
VTTRegion.prototype.scroll;
/**
* @see http://dev.w3.org/html5/webvtt/#the-vttcue-interface
* @constructor
* @extends {TextTrackCue}
* @param {number} startTime
* @param {number} endTime
* @param {string} text
*/
function VTTCue(startTime, endTime, text) {}
/** @type {?VTTRegion} */
VTTCue.prototype.region;
/**
* @see https://w3c.github.io/webvtt/#enumdef-directionsetting
* @type {string}
*/
VTTCue.prototype.vertical;
/** @type {boolean} */
VTTCue.prototype.snapToLines;
/** @type {(number|string)} */
VTTCue.prototype.line;
/**
* @see https://w3c.github.io/webvtt/#enumdef-linealignsetting
* @type {string}
*/
VTTCue.prototype.lineAlign;
/** @type {(number|string)} */
VTTCue.prototype.position;
/**
* @see https://w3c.github.io/webvtt/#enumdef-positionalignsetting
* @type {string}
*/
VTTCue.prototype.positionAlign;
/** @type {number} */
VTTCue.prototype.size;
/**
* @see https://w3c.github.io/webvtt/#enumdef-alignsetting
* @type {string}
*/
VTTCue.prototype.align;
/** @type {string} */
VTTCue.prototype.text;
/** @return {!DocumentFragment} */
VTTCue.prototype.getCueAsHTML = function() {};
/**
* @constructor
* @extends {HTMLMediaElement}
*/
function HTMLAudioElement() {}
/**
* @constructor
* @extends {HTMLMediaElement}
* The webkit-prefixed attributes are defined in
* https://cs.chromium.org/chromium/src/third_party/WebKit/Source/core/html/media/HTMLMediaElement.idl
*/
function HTMLVideoElement() {}
/**
* Starts displaying the video in full screen mode.
* @return {undefined}
*/
HTMLVideoElement.prototype.webkitEnterFullscreen = function() {};
/**
* Starts displaying the video in full screen mode.
* @return {undefined}
*/
HTMLVideoElement.prototype.webkitEnterFullScreen = function() {};
/**
* Stops displaying the video in full screen mode.
* @return {undefined}
*/
HTMLVideoElement.prototype.webkitExitFullscreen = function() {};
/**
* Stops displaying the video in full screen mode.
* @return {undefined}
*/
HTMLVideoElement.prototype.webkitExitFullScreen = function() {};
/** @type {number} */
HTMLVideoElement.prototype.width;
/** @type {number} */
HTMLVideoElement.prototype.height;
/** @type {number} */
HTMLVideoElement.prototype.videoWidth;
/** @type {number} */
HTMLVideoElement.prototype.videoHeight;
/** @type {string} */
HTMLVideoElement.prototype.poster;
/** @type {boolean} */
HTMLVideoElement.prototype.webkitSupportsFullscreen;
/** @type {boolean} */
HTMLVideoElement.prototype.webkitDisplayingFullscreen;
/** @type {number} */
HTMLVideoElement.prototype.webkitDecodedFrameCount;
/** @type {number} */
HTMLVideoElement.prototype.webkitDroppedFrameCount;
/**
* @typedef {{
* creationTime: number,
* totalVideoFrames: number,
* droppedVideoFrames: number,
* corruptedVideoFrames: number,
* totalFrameDelay: number,
* displayCompositedVideoFrames: (number|undefined)
* }}
*/
var VideoPlaybackQuality;
/**
* @see https://w3c.github.io/media-source/#htmlvideoelement-extensions
* @return {!VideoPlaybackQuality} Stats about the current playback.
*/
HTMLVideoElement.prototype.getVideoPlaybackQuality = function() {};
/**
* The metadata provided by the callback given to
* HTMLVideoElement.requestVideoFrameCallback().
*
* See https://wicg.github.io/video-rvfc/#video-frame-metadata
*
* @record
*/
function VideoFrameMetadata() {};
/**
* The time at which the user agent submitted the frame for composition.
* @const {number}
*/
VideoFrameMetadata.prototype.presentationTime;
/**
* The time at which the user agent expects the frame to be visible.
* @const {number}
*/
VideoFrameMetadata.prototype.expectedDisplayTime;
/**
* The width of the video frame, in media pixels.
* @const {number}
*/
VideoFrameMetadata.prototype.width;
/**
* The height of the video frame, in media pixels.
* @const {number}
*/
VideoFrameMetadata.prototype.height;
/**
* The media presentation timestamp (PTS) in seconds of the frame presented
* (e.g. its timestamp on the video.currentTime timeline).
* @const {number}
*/
VideoFrameMetadata.prototype.mediaTime;
/**
* A count of the number of frames submitted for composition.
* @const {number}
*/
VideoFrameMetadata.prototype.presentedFrames;
/**
* The elapsed duration in seconds from submission of the encoded packet with
* the same presentation timestamp (PTS) as this frame (e.g. same as the
* mediaTime) to the decoder until the decoded frame was ready for presentation.
* @const {number|undefined}
*/
VideoFrameMetadata.prototype.processingDuration;
/**
* For video frames coming from either a local or remote source, this is the
* time at which the frame was captured by the camera.
* @const {number|undefined}
*/
VideoFrameMetadata.prototype.captureTime;
/**
* For video frames coming from a remote source, this is the time the encoded
* frame was received by the platform, i.e., the time at which the last packet
* belonging to this frame was received over the network.
* @const {number|undefined}
*/
VideoFrameMetadata.prototype.receiveTime;
/**
* The RTP timestamp associated with this video frame.
* @const {number|undefined}
*/
VideoFrameMetadata.prototype.rtpTimestamp;
/**
* @typedef {function(number, ?VideoFrameMetadata): undefined}
* @see https://wicg.github.io/video-rvfc/#dom-htmlvideoelement-requestvideoframecallback
*/
var VideoFrameRequestCallback;
/**
* Registers a callback to be fired the next time a frame is presented to the
* compositor.
* @param {!VideoFrameRequestCallback} callback
* @return {number}
*/
HTMLVideoElement.prototype.requestVideoFrameCallback = function(callback) {};
/**
* Cancels an existing video frame request callback given its handle.
* @param {number} handle
* @return {undefined}
*/
HTMLVideoElement.prototype.cancelVideoFrameCallback = function(handle) {};
/**
* @constructor
* @see https://html.spec.whatwg.org/multipage/media.html#error-codes
*/
function MediaError() {}
/** @type {number} */
MediaError.prototype.code;
/** @type {string} */
MediaError.prototype.message;
/**
* The fetching process for the media resource was aborted by the user agent at
* the user's request.
* @const {number}
*/
MediaError.MEDIA_ERR_ABORTED;
/**
* A network error of some description caused the user agent to stop fetching
* the media resource, after the resource was established to be usable.
* @const {number}
*/
MediaError.MEDIA_ERR_NETWORK;
/**
* An error of some description occurred while decoding the media resource,
* after the resource was established to be usable.
* @const {number}
*/
MediaError.MEDIA_ERR_DECODE;
/**
* The media resource indicated by the src attribute was not suitable.
* @const {number}
*/
MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED;
// HTML5 MessageChannel
/**
* @see http://dev.w3.org/html5/spec/comms.html#messagechannel
* @constructor
*/
function MessageChannel() {}
/**
* Returns the first port.
* @type {!MessagePort}
*/
MessageChannel.prototype.port1;
/**
* Returns the second port.
* @type {!MessagePort}
*/
MessageChannel.prototype.port2;
// HTML5 MessagePort
/**
* @see http://dev.w3.org/html5/spec/comms.html#messageport
* @constructor
* @implements {EventTarget}
* @implements {Transferable}
*/
function MessagePort() {}
/** @override */
MessagePort.prototype.addEventListener = function(type, listener, opt_options) {
};
/** @override */
MessagePort.prototype.removeEventListener = function(
type, listener, opt_options) {};
/** @override */
MessagePort.prototype.dispatchEvent = function(evt) {};
/**
* Posts a message through the channel, optionally with the given
* Array of Transferables.
* @param {*} message
* @param {Array<!Transferable>=} opt_transfer
* @return {undefined}
*/
MessagePort.prototype.postMessage = function(message, opt_transfer) {
};
/**
* Begins dispatching messages received on the port.
* @return {undefined}
*/
MessagePort.prototype.start = function() {};
/**
* Disconnects the port, so that it is no longer active.
* @return {undefined}
*/
MessagePort.prototype.close = function() {};
/**
* TODO(blickly): Change this to MessageEvent<*> and add casts as needed
* @type {?function(!MessageEvent<?>): void}
*/
MessagePort.prototype.onmessage;
// HTML5 MessageEvent class
/**
* @typedef {Window|MessagePort|ServiceWorker}
* @see https://html.spec.whatwg.org/multipage/comms.html#messageeventsource
*/
var MessageEventSource;
/**
* @record
* @extends {EventInit}
* @template T
* @see https://html.spec.whatwg.org/multipage/comms.html#messageeventinit
*/
function MessageEventInit() {}
/** @type {T|undefined} */
MessageEventInit.prototype.data;
/** @type {(string|undefined)} */
MessageEventInit.prototype.origin;
/** @type {(string|undefined)} */
MessageEventInit.prototype.lastEventId;
/** @type {(?MessageEventSource|undefined)} */
MessageEventInit.prototype.source;
/** @type {(!Array<MessagePort>|undefined)} */
MessageEventInit.prototype.ports;
/**
* @see https://html.spec.whatwg.org/multipage/comms.html#messageevent
* @constructor
* @extends {Event}
* @param {string} type
* @param {MessageEventInit<T>=} opt_eventInitDict
* @template T
*/
function MessageEvent(type, opt_eventInitDict) {}
/**
* The data payload of the message.
* @type {T}
*/
MessageEvent.prototype.data;
/**
* The origin of the message, for server-sent events and cross-document
* messaging.
* @type {string}
*/
MessageEvent.prototype.origin;
/**
* The last event ID, for server-sent events.
* @type {string}
*/
MessageEvent.prototype.lastEventId;
/**
* The window that dispatched the event.
* @type {Window}
*/
MessageEvent.prototype.source;
/**
* The Array of MessagePorts sent with the message, for cross-document
* messaging and channel messaging.
* @type {!Array<MessagePort>}
*/
MessageEvent.prototype.ports;
/**
* Initializes the event in a manner analogous to the similarly-named methods in
* the DOM Events interfaces.
* @param {string} typeArg
* @param {boolean=} canBubbleArg
* @param {boolean=} cancelableArg
* @param {T=} dataArg
* @param {string=} originArg
* @param {string=} lastEventIdArg
* @param {?MessageEventSource=} sourceArg
* @param {!Array<MessagePort>=} portsArg
* @return {undefined}
*/
MessageEvent.prototype.initMessageEvent = function(typeArg, canBubbleArg,
cancelableArg, dataArg, originArg, lastEventIdArg, sourceArg, portsArg) {};
/**
* Initializes the event in a manner analogous to the similarly-named methods in
* the DOM Events interfaces.
* @param {string} namespaceURI
* @param {string=} typeArg
* @param {boolean=} canBubbleArg
* @param {boolean=} cancelableArg
* @param {T=} dataArg
* @param {string=} originArg
* @param {string=} lastEventIdArg
* @param {?MessageEventSource=} sourceArg
* @param {!Array<MessagePort>=} portsArg
* @return {undefined}
*/
MessageEvent.prototype.initMessageEventNS = function(namespaceURI, typeArg,
canBubbleArg, cancelableArg, dataArg, originArg, lastEventIdArg, sourceArg,
portsArg) {};
/**
* @record
* @extends {EventInit}
* @see https://html.spec.whatwg.org/multipage/web-sockets.html#the-closeevent-interface
*/
function CloseEventInit() {}
/**
* @type {undefined|boolean}
*/
CloseEventInit.prototype.wasClean;
/**
* @type {undefined|number}
*/
CloseEventInit.prototype.code;
/**
* @type {undefined|string}
*/
CloseEventInit.prototype.reason;
/**
* @constructor
* @extends {Event}
* @param {string} type
* @param {!CloseEventInit=} opt_init
*/
var CloseEvent = function(type, opt_init) {};
/**
* @type {boolean}
*/
CloseEvent.prototype.wasClean;
/**
* @type {number}
*/
CloseEvent.prototype.code;
/**
* @type {string}
*/
CloseEvent.prototype.reason;
/**
* HTML5 BroadcastChannel class.
* @param {string} channelName
* @see https://developer.mozilla.org/en-US/docs/Web/API/BroadcastChannel
* @see https://html.spec.whatwg.org/multipage/comms.html#dom-broadcastchannel
* @implements {EventTarget}
* @constructor
*/
function BroadcastChannel(channelName) {}
/**
* Sends the message, of any type of object, to each BroadcastChannel object
* listening to the same channel.
* @param {*} message
*/
BroadcastChannel.prototype.postMessage = function(message) {};
/**
* Closes the channel object, indicating it won't get any new messages, and
* allowing it to be, eventually, garbage collected.
* @return {void}
*/
BroadcastChannel.prototype.close = function() {};
/** @override */
BroadcastChannel.prototype.addEventListener = function(
type, listener, opt_options) {};
/** @override */
BroadcastChannel.prototype.dispatchEvent = function(evt) {};
/** @override */
BroadcastChannel.prototype.removeEventListener = function(
type, listener, opt_options) {};
/**
* An EventHandler property that specifies the function to execute when a
* message event is fired on this object.
* @type {?function(!MessageEvent<*>)}
*/
BroadcastChannel.prototype.onmessage;
/**
* The name of the channel.
* @type {string}
*/
BroadcastChannel.prototype.name;
/**
* HTML5 DataTransfer class.
*
* @see http://www.w3.org/TR/2011/WD-html5-20110113/dnd.html
* @see http://www.whatwg.org/specs/web-apps/current-work/multipage/dnd.html
* @see http://developers.whatwg.org/dnd.html#datatransferitem
* @constructor
*/
function DataTransfer() {}
/** @type {string} */
DataTransfer.prototype.dropEffect;
/** @type {string} */
DataTransfer.prototype.effectAllowed;
/** @type {!Array<string>} */
DataTransfer.prototype.types;
/** @type {!FileList} */
DataTransfer.prototype.files;
/**
* @param {string=} opt_format Format for which to remove data.
* @return {undefined}
*/
DataTransfer.prototype.clearData = function(opt_format) {};
/**
* @param {string} format Format for which to set data.
* @param {string} data Data to add.
* @return {boolean}
*/
DataTransfer.prototype.setData = function(format, data) {};
/**
* @param {string} format Format for which to set data.
* @return {string} Data for the given format.
*/
DataTransfer.prototype.getData = function(format) { return ''; };
/**
* @param {HTMLElement} img The image to use when dragging.
* @param {number} x Horizontal position of the cursor.
* @param {number} y Vertical position of the cursor.
* @return {undefined}
*/
DataTransfer.prototype.setDragImage = function(img, x, y) {};
/**
* @param {HTMLElement} elem Element to receive drag result events.
* @return {undefined}
*/
DataTransfer.prototype.addElement = function(elem) {};
/**
* Addition for accessing clipboard file data that are part of the proposed
* HTML5 spec.
* @type {DataTransfer}
*/
MouseEvent.prototype.dataTransfer;
/**
* @record
* @extends {MouseEventInit}
* @see https://w3c.github.io/uievents/#idl-wheeleventinit
*/
function WheelEventInit() {}
/** @type {undefined|number} */
WheelEventInit.prototype.deltaX;
/** @type {undefined|number} */
WheelEventInit.prototype.deltaY;
/** @type {undefined|number} */
WheelEventInit.prototype.deltaZ;
/** @type {undefined|number} */
WheelEventInit.prototype.deltaMode;
/**
* @param {string} type
* @param {WheelEventInit=} opt_eventInitDict
* @see http://www.w3.org/TR/DOM-Level-3-Events/#interface-WheelEvent
* @constructor
* @extends {MouseEvent}
*/
function WheelEvent(type, opt_eventInitDict) {}
/** @const {number} */
WheelEvent.DOM_DELTA_PIXEL;
/** @const {number} */
WheelEvent.DOM_DELTA_LINE;
/** @const {number} */
WheelEvent.DOM_DELTA_PAGE;
/** @const {number} */
WheelEvent.prototype.deltaX;
/** @const {number} */
WheelEvent.prototype.deltaY;
/** @const {number} */
WheelEvent.prototype.deltaZ;
/** @const {number} */
WheelEvent.prototype.deltaMode;
/**
* HTML5 DataTransferItem class.
*
* @see http://www.w3.org/TR/2011/WD-html5-20110113/dnd.html
* @see http://www.whatwg.org/specs/web-apps/current-work/multipage/dnd.html
* @see http://developers.whatwg.org/dnd.html#datatransferitem
* @constructor
*/
function DataTransferItem() {}
/** @type {string} */
DataTransferItem.prototype.kind;
/** @type {string} */
DataTransferItem.prototype.type;
/**
* @param {function(string)} callback
* @return {undefined}
*/
DataTransferItem.prototype.getAsString = function(callback) {};
/**
* @return {?File} The file corresponding to this item, or null.
* @nosideeffects
*/
DataTransferItem.prototype.getAsFile = function() { return null; };
/**
* HTML5 DataTransferItemList class. There are some discrepancies in the docs
* on the whatwg.org site. When in doubt, these prototypes match what is
* implemented as of Chrome 30.
*
* @see http://www.w3.org/TR/2011/WD-html5-20110113/dnd.html
* @see http://www.whatwg.org/specs/web-apps/current-work/multipage/dnd.html
* @see http://developers.whatwg.org/dnd.html#datatransferitem
* @constructor
* @implements {IArrayLike<!DataTransferItem>}
*/
function DataTransferItemList() {}
/** @type {number} */
DataTransferItemList.prototype.length;
/**
* @param {number} i File to return from the list.
* @return {DataTransferItem} The ith DataTransferItem in the list, or null.
* @nosideeffects
*/
DataTransferItemList.prototype.item = function(i) { return null; };
/**
* Adds an item to the list.
* @param {string|!File} data Data for the item being added.
* @param {string=} opt_type Mime type of the item being added. MUST be present
* if the {@code data} parameter is a string.
* @return {DataTransferItem}
*/
DataTransferItemList.prototype.add = function(data, opt_type) {};
/**
* Removes an item from the list.
* @param {number} i File to remove from the list.
* @return {undefined}
*/
DataTransferItemList.prototype.remove = function(i) {};
/**
* Removes all items from the list.
* @return {undefined}
*/
DataTransferItemList.prototype.clear = function() {};
/** @type {!DataTransferItemList} */
DataTransfer.prototype.items;
/**
* @record
* @extends {MouseEventInit}
* @see http://w3c.github.io/html/editing.html#dictdef-drageventinit
*/
function DragEventInit() {}
/** @type {undefined|?DataTransfer} */
DragEventInit.prototype.dataTransfer;
/**
* @see http://www.whatwg.org/specs/web-apps/current-work/multipage/dnd.html#the-dragevent-interface
* @constructor
* @extends {MouseEvent}
* @param {string} type
* @param {DragEventInit=} opt_eventInitDict
*/
function DragEvent(type, opt_eventInitDict) {}
/** @type {DataTransfer} */
DragEvent.prototype.dataTransfer;
/**
* @record
* @extends {EventInit}
* @see https://www.w3.org/TR/progress-events/#progresseventinit
*/
function ProgressEventInit() {}
/** @type {undefined|boolean} */
ProgressEventInit.prototype.lengthComputable;
/** @type {undefined|number} */
ProgressEventInit.prototype.loaded;
/** @type {undefined|number} */
ProgressEventInit.prototype.total;
/**
* @constructor
* @template TARGET
* @param {string} type
* @param {ProgressEventInit=} opt_progressEventInitDict
* @extends {Event}
* @see https://developer.mozilla.org/en-US/docs/Web/API/ProgressEvent
*/
function ProgressEvent(type, opt_progressEventInitDict) {}
/**
* @override
* @type {TARGET}
*/
ProgressEvent.prototype.target;
/** @type {number} */
ProgressEvent.prototype.total;
/** @type {number} */
ProgressEvent.prototype.loaded;
/** @type {boolean} */
ProgressEvent.prototype.lengthComputable;
/**
* @constructor
*/
function TimeRanges() {}
/** @type {number} */
TimeRanges.prototype.length;
/**
* @param {number} index The index.
* @return {number} The start time of the range at index.
* @throws {DOMException}
*/
TimeRanges.prototype.start = function(index) { return 0; };
/**
* @param {number} index The index.
* @return {number} The end time of the range at index.
* @throws {DOMException}
*/
TimeRanges.prototype.end = function(index) { return 0; };
// HTML5 Web Socket class
/**
* @see https://html.spec.whatwg.org/multipage/web-sockets.html
* @constructor
* @param {string} url
* @param {(string|!Array<string>)=} opt_protocol
* @implements {EventTarget}
*/
function WebSocket(url, opt_protocol) {}
/**
* The connection has not yet been established.
* @const {number}
*/
WebSocket.CONNECTING;
/**
* The connection has not yet been established.
* @const {number}
*/
WebSocket.prototype.CONNECTING;
/**
* The WebSocket connection is established and communication is possible.
* @const {number}
*/
WebSocket.OPEN;
/**
* The WebSocket connection is established and communication is possible.
* @const {number}
*/
WebSocket.prototype.OPEN;
/**
* The connection is going through the closing handshake, or the close() method has been invoked.
* @const {number}
*/
WebSocket.CLOSING;
/**
* The connection is going through the closing handshake, or the close() method has been invoked.
* @const {number}
*/
WebSocket.prototype.CLOSING;
/**
* The connection has been closed or could not be opened.
* @const {number}
*/
WebSocket.CLOSED;
/**
* The connection has been closed or could not be opened.
* @const {number}
*/
WebSocket.prototype.CLOSED;
/** @override */
WebSocket.prototype.addEventListener = function(type, listener, opt_options) {};
/** @override */
WebSocket.prototype.removeEventListener = function(
type, listener, opt_options) {};
/** @override */
WebSocket.prototype.dispatchEvent = function(evt) {};
/**
* Returns the URL value that was passed to the constructor.
* @type {string}
*/
WebSocket.prototype.url;
/**
* Represents the state of the connection.
* @type {number}
*/
WebSocket.prototype.readyState;
/**
* Returns the number of bytes that have been queued but not yet sent.
* @type {number}
*/
WebSocket.prototype.bufferedAmount;
/**
* An event handler called on error event.
* @type {?function(!Event): void}
*/
WebSocket.prototype.onerror;
/**
* An event handler called on open event.
* @type {?function(!Event): void}
*/
WebSocket.prototype.onopen;
/**
* An event handler called on message event.
* @type {?function(!MessageEvent<string|!ArrayBuffer|!Blob>): void}
*/
WebSocket.prototype.onmessage;
/**
* An event handler called on close event.
* @type {?function(!CloseEvent): void}
*/
WebSocket.prototype.onclose;
/**
* Transmits data using the connection.
* @param {string|!ArrayBuffer|!ArrayBufferView|!Blob} data
* @return {void}
*/
WebSocket.prototype.send = function(data) {};
/**
* Closes the Web Socket connection or connection attempt, if any.
* @param {number=} opt_code
* @param {string=} opt_reason
* @return {undefined}
*/
WebSocket.prototype.close = function(opt_code, opt_reason) {};
/**
* @type {string} Sets the type of data (blob or arraybuffer) for binary data.
*/
WebSocket.prototype.binaryType;
// HTML5 History
/**
* @constructor
* @see http://w3c.github.io/html/browsers.html#the-history-interface
*/
function History() {}
/**
* Goes back one step in the joint session history.
* If there is no previous page, does nothing.
*
* @see https://html.spec.whatwg.org/multipage/history.html#dom-history-back
*
* @return {undefined}
*/
History.prototype.back = function() {};
/**
* Goes forward one step in the joint session history.
* If there is no next page, does nothing.
*
* @return {undefined}
*/
History.prototype.forward = function() {};
/**
* The number of entries in the joint session history.
*
* @type {number}
*/
History.prototype.length;
/**
* Goes back or forward the specified number of steps in the joint session
* history. A zero delta will reload the current page. If the delta is out of
* range, does nothing.
*
* @param {number} delta The number of entries to go back.
* @return {undefined}
*/
History.prototype.go = function(delta) {};
/**
* Pushes a new state into the session history.
* @see http://www.w3.org/TR/html5/history.html#the-history-interface
* @param {*} data New state.
* @param {string} title The title for a new session history entry.
* @param {string=} opt_url The URL for a new session history entry.
* @return {undefined}
*/
History.prototype.pushState = function(data, title, opt_url) {};
/**
* Replaces the current state in the session history.
* @see http://www.w3.org/TR/html5/history.html#the-history-interface
* @param {*} data New state.
* @param {string} title The title for a session history entry.
* @param {string=} opt_url The URL for a new session history entry.
* @return {undefined}
*/
History.prototype.replaceState = function(data, title, opt_url) {};
/**
* Pending state object.
* @see https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history#Reading_the_current_state
* @type {*}
*/
History.prototype.state;
/**
* Allows web applications to explicitly set default scroll restoration behavior
* on history navigation. This property can be either auto or manual.
*
* Non-standard. Only supported in Chrome 46+.
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/History
* @see https://majido.github.io/scroll-restoration-proposal/history-based-api.html
* @type {string}
*/
History.prototype.scrollRestoration;
/**
* Add history property to Window.
*
* @type {!History}
*/
Window.prototype.history;
/**
* @constructor
* @see https://html.spec.whatwg.org/multipage/history.html#the-location-interface
*/
function Location() {}
/**
* Returns the Location object's URL. Can be set, to navigate to the given URL.
* @implicitCast
* @type {string}
* @see https://html.spec.whatwg.org/multipage/history.html#dom-location-href
*/
Location.prototype.href;
/**
* Returns the Location object's URL's origin.
* @const {string}
* @see https://html.spec.whatwg.org/multipage/history.html#dom-location-origin
*/
Location.prototype.origin;
/**
* Returns the Location object's URL's scheme. Can be set, to navigate to the
* same URL with a changed scheme.
* @type {string}
* @see https://html.spec.whatwg.org/multipage/history.html#dom-location-protocol
*/
Location.prototype.protocol;
/**
* Returns the Location object's URL's host and port (if different from the
* default port for the scheme). Can be set, to navigate to the same URL with
* a changed host and port.
* @type {string}
* @see https://html.spec.whatwg.org/multipage/history.html#dom-location-host
*/
Location.prototype.host;
/**
* Returns the Location object's URL's host. Can be set, to navigate to the
* same URL with a changed host.
* @type {string}
* @see https://html.spec.whatwg.org/multipage/history.html#dom-location-hostname
*/
Location.prototype.hostname;
/**
* Returns the Location object's URL's port. Can be set, to navigate to the
* same URL with a changed port.
* @type {string}
* @see https://html.spec.whatwg.org/multipage/history.html#the-location-interface:dom-location-port
*/
Location.prototype.port;
/**
* Returns the Location object's URL's path. Can be set, to navigate to the
* same URL with a changed path.
* @type {string}
* @see https://html.spec.whatwg.org/multipage/history.html#dom-location-pathname
*/
Location.prototype.pathname;
/**
* Returns the Location object's URL's query (includes leading "?" if
* non-empty). Can be set, to navigate to the same URL with a changed query
* (ignores leading "?").
* @type {string}
* @see https://html.spec.whatwg.org/multipage/history.html#dom-location-search
*/
Location.prototype.search;
/**
* Returns the Location object's URL's fragment (includes leading "#" if
* non-empty). Can be set, to navigate to the same URL with a changed fragment
* (ignores leading "#").
* @type {string}
* @see https://html.spec.whatwg.org/multipage/history.html#dom-location-hash
*/
Location.prototype.hash;
/**
* Navigates to the given page.
* @param {string} url
* @return {undefined}
* @see https://html.spec.whatwg.org/multipage/history.html#dom-location-assign
*/
Location.prototype.assign = function(url) {};
/**
* Removes the current page from the session history and navigates to the given
* page.
* @param {string} url
* @return {undefined}
* @see https://html.spec.whatwg.org/multipage/history.html#dom-location-replace
*/
Location.prototype.replace = function(url) {};
/**
* Reloads the current page.
* @param {boolean=} forceReload If true, reloads the page from
* the server. Defaults to false.
* @return {undefined}
* @see https://html.spec.whatwg.org/multipage/history.html#dom-location-reload
*/
Location.prototype.reload = function(forceReload) {};
/**
* Returns a DOMStringList object listing the origins of the ancestor browsing
* contexts, from the parent browsing context to the top-level browsing
* context.
* @type {DOMStringList}
* @see https://html.spec.whatwg.org/multipage/history.html#dom-location-ancestororigins
*/
Location.prototype.ancestorOrigins;
/**
* @see http://www.whatwg.org/specs/web-apps/current-work/#popstateevent
* @constructor
* @extends {Event}
*
* @param {string} type
* @param {{state: *}=} opt_eventInitDict
*/
function PopStateEvent(type, opt_eventInitDict) {}
/**
* @type {*}
*/
PopStateEvent.prototype.state;
/**
* Initializes the event after it has been created with document.createEvent
* @param {string} typeArg
* @param {boolean} canBubbleArg
* @param {boolean} cancelableArg
* @param {*} stateArg
* @return {undefined}
*/
PopStateEvent.prototype.initPopStateEvent = function(typeArg, canBubbleArg,
cancelableArg, stateArg) {};
/**
* @see http://www.whatwg.org/specs/web-apps/current-work/#hashchangeevent
* @constructor
* @extends {Event}
*
* @param {string} type
* @param {{oldURL: string, newURL: string}=} opt_eventInitDict
*/
function HashChangeEvent(type, opt_eventInitDict) {}
/** @type {string} */
HashChangeEvent.prototype.oldURL;
/** @type {string} */
HashChangeEvent.prototype.newURL;
/**
* Initializes the event after it has been created with document.createEvent
* @param {string} typeArg
* @param {boolean} canBubbleArg
* @param {boolean} cancelableArg
* @param {string} oldURLArg
* @param {string} newURLArg
* @return {undefined}
*/
HashChangeEvent.prototype.initHashChangeEvent = function(typeArg, canBubbleArg,
cancelableArg, oldURLArg, newURLArg) {};
/**
* @see http://www.whatwg.org/specs/web-apps/current-work/#pagetransitionevent
* @constructor
* @extends {Event}
*
* @param {string} type
* @param {{persisted: boolean}=} opt_eventInitDict
*/
function PageTransitionEvent(type, opt_eventInitDict) {}
/** @type {boolean} */
PageTransitionEvent.prototype.persisted;
/**
* Initializes the event after it has been created with document.createEvent
* @param {string} typeArg
* @param {boolean} canBubbleArg
* @param {boolean} cancelableArg
* @param {*} persistedArg
* @return {undefined}
*/
PageTransitionEvent.prototype.initPageTransitionEvent = function(typeArg,
canBubbleArg, cancelableArg, persistedArg) {};
/**
* @constructor
* @implements {IArrayLike<!File>}
*/
function FileList() {}
/** @type {number} */
FileList.prototype.length;
/**
* @param {number} i File to return from the list.
* @return {File} The ith file in the list.
* @nosideeffects
*/
FileList.prototype.item = function(i) { return null; };
/**
* @type {boolean}
* @see http://dev.w3.org/2006/webapi/XMLHttpRequest-2/#withcredentials
*/
XMLHttpRequest.prototype.withCredentials;
/**
* @type {?function(!ProgressEvent): void}
* @see https://xhr.spec.whatwg.org/#handler-xhr-onloadstart
*/
XMLHttpRequest.prototype.onloadstart;
/**
* @type {?function(!ProgressEvent): void}
* @see https://dvcs.w3.org/hg/xhr/raw-file/tip/Overview.html#handler-xhr-onprogress
*/
XMLHttpRequest.prototype.onprogress;
/**
* @type {?function(!ProgressEvent): void}
* @see https://xhr.spec.whatwg.org/#handler-xhr-onabort
*/
XMLHttpRequest.prototype.onabort;
/**
* @type {?function(!ProgressEvent): void}
* @see https://xhr.spec.whatwg.org/#handler-xhr-onload
*/
XMLHttpRequest.prototype.onload;
/**
* @type {?function(!ProgressEvent): void}
* @see https://xhr.spec.whatwg.org/#handler-xhr-ontimeout
*/
XMLHttpRequest.prototype.ontimeout;
/**
* @type {?function(!ProgressEvent): void}
* @see https://xhr.spec.whatwg.org/#handler-xhr-onloadend
*/
XMLHttpRequest.prototype.onloadend;
/**
* @type {XMLHttpRequestUpload}
* @see http://dev.w3.org/2006/webapi/XMLHttpRequest-2/#the-upload-attribute
*/
XMLHttpRequest.prototype.upload;
/**
* @param {string} mimeType The mime type to override with.
* @return {undefined}
*/
XMLHttpRequest.prototype.overrideMimeType = function(mimeType) {};
/**
* @type {string}
* @see http://dev.w3.org/2006/webapi/XMLHttpRequest-2/#the-responsetype-attribute
*/
XMLHttpRequest.prototype.responseType;
/**
* @type {?(ArrayBuffer|Blob|Document|Object|string)}
* @see http://dev.w3.org/2006/webapi/XMLHttpRequest-2/#the-response-attribute
*/
XMLHttpRequest.prototype.response;
/**
* @type {ArrayBuffer}
* Implemented as a draft spec in Firefox 4 as the way to get a requested array
* buffer from an XMLHttpRequest.
* @see https://developer.mozilla.org/En/Using_XMLHttpRequest#Receiving_binary_data_using_JavaScript_typed_arrays
*
* This property is not used anymore and should be removed.
* @see https://github.com/google/closure-compiler/pull/1389
*/
XMLHttpRequest.prototype.mozResponseArrayBuffer;
/**
* XMLHttpRequestEventTarget defines events for checking the status of a data
* transfer between a client and a server. This should be a common base class
* for XMLHttpRequest and XMLHttpRequestUpload.
*
* @constructor
* @implements {EventTarget}
*/
function XMLHttpRequestEventTarget() {}
/** @override */
XMLHttpRequestEventTarget.prototype.addEventListener = function(
type, listener, opt_options) {};
/** @override */
XMLHttpRequestEventTarget.prototype.removeEventListener = function(
type, listener, opt_options) {};
/** @override */
XMLHttpRequestEventTarget.prototype.dispatchEvent = function(evt) {};
/**
* An event target to track the status of an upload.
*
* @constructor
* @extends {XMLHttpRequestEventTarget}
*/
function XMLHttpRequestUpload() {}
/**
* @type {?function(!ProgressEvent): void}
* @see https://dvcs.w3.org/hg/xhr/raw-file/tip/Overview.html#handler-xhr-onprogress
*/
XMLHttpRequestUpload.prototype.onprogress;
/**
* @param {number=} opt_width
* @param {number=} opt_height
* @constructor
* @extends {HTMLImageElement}
*/
function Image(opt_width, opt_height) {}
/**
* Dataset collection.
* This is really a DOMStringMap but it behaves close enough to an object to
* pass as an object.
* @const {!Object<string, string>}
*/
HTMLElement.prototype.dataset;
/**
* @constructor
* @implements {IArrayLike<string>}
* @see https://dom.spec.whatwg.org/#interface-domtokenlist
*/
function DOMTokenList() {}
/**
* Returns the number of CSS classes applied to this Element.
* @type {number}
*/
DOMTokenList.prototype.length;
/**
* Returns the string value applied to this Element.
* @type {string|undefined}
*/
DOMTokenList.prototype.value;
/**
* @param {number} index The index of the item to return.
* @return {string} The CSS class at the specified index.
* @nosideeffects
*/
DOMTokenList.prototype.item = function(index) {};
/**
* @param {string} token The CSS class to check for.
* @return {boolean} Whether the CSS class has been applied to the Element.
* @nosideeffects
*/
DOMTokenList.prototype.contains = function(token) {};
/**
* @param {...string} var_args The CSS class(es) to add to this element.
* @return {undefined}
*/
DOMTokenList.prototype.add = function(var_args) {};
/**
* @param {...string} var_args The CSS class(es) to remove from this element.
* @return {undefined}
*/
DOMTokenList.prototype.remove = function(var_args) {};
/**
* Replaces token with newToken.
* @param {string} token The CSS class to replace.
* @param {string} newToken The new CSS class to use.
* @return {undefined}
*/
DOMTokenList.prototype.replace = function(token, newToken) {};
/**
* @param {string} token The token to query for.
* @return {boolean} Whether the token was found.
* @see https://developer.mozilla.org/en-US/docs/Web/API/DOMTokenList/supports
* @nosideeffects
*/
DOMTokenList.prototype.supports = function(token) {};
/**
* @param {string} token The CSS class to toggle from this element.
* @param {boolean=} opt_force True to add the class whether it exists
* or not. False to remove the class whether it exists or not.
* This argument is not supported on IE 10 and below, according to
* the MDN page linked below.
* @return {boolean} False if the token was removed; True otherwise.
* @see https://developer.mozilla.org/en-US/docs/Web/API/Element.classList
*/
DOMTokenList.prototype.toggle = function(token, opt_force) {};
/**
* @return {string} A stringified representation of CSS classes.
* @nosideeffects
* @override
*/
DOMTokenList.prototype.toString = function() {};
/**
* @return {!IteratorIterable<string>} An iterator to go through all values of
* the key/value pairs contained in this object.
* @nosideeffects
* @see https://developer.mozilla.org/en-US/docs/Web/API/DOMTokenList/values
*/
DOMTokenList.prototype.values = function() {};
/**
* A better interface to CSS classes than className.
* @const {!DOMTokenList}
* @see https://developer.mozilla.org/en-US/docs/Web/API/Element/classList
*/
Element.prototype.classList;
/**
* Constraint Validation API properties and methods
* @see http://www.w3.org/TR/2009/WD-html5-20090423/forms.html#the-constraint-validation-api
*/
/** @return {boolean} */
HTMLFormElement.prototype.checkValidity = function() {};
/** @return {boolean} */
HTMLFormElement.prototype.reportValidity = function() {};
/** @type {boolean} */
HTMLFormElement.prototype.noValidate;
/** @constructor */
function ValidityState() {}
/** @type {boolean} */
ValidityState.prototype.badInput;
/** @type {boolean} */
ValidityState.prototype.customError;
/** @type {boolean} */
ValidityState.prototype.patternMismatch;
/** @type {boolean} */
ValidityState.prototype.rangeOverflow;
/** @type {boolean} */
ValidityState.prototype.rangeUnderflow;
/** @type {boolean} */
ValidityState.prototype.stepMismatch;
/** @type {boolean} */
ValidityState.prototype.typeMismatch;
/** @type {boolean} */
ValidityState.prototype.tooLong;
/** @type {boolean} */
ValidityState.prototype.tooShort;
/** @type {boolean} */
ValidityState.prototype.valid;
/** @type {boolean} */
ValidityState.prototype.valueMissing;
/** @type {boolean} */
HTMLButtonElement.prototype.autofocus;
/**
* Can return null when hidden.
* See https://html.spec.whatwg.org/multipage/forms.html#dom-lfe-labels
* @const {?NodeList<!HTMLLabelElement>}
*/
HTMLButtonElement.prototype.labels;
/** @type {string} */
HTMLButtonElement.prototype.validationMessage;
/**
* @const {ValidityState}
*/
HTMLButtonElement.prototype.validity;
/** @type {boolean} */
HTMLButtonElement.prototype.willValidate;
/** @return {boolean} */
HTMLButtonElement.prototype.checkValidity = function() {};
/** @return {boolean} */
HTMLButtonElement.prototype.reportValidity = function() {};
/**
* @param {string} message
* @return {undefined}
*/
HTMLButtonElement.prototype.setCustomValidity = function(message) {};
/**
* @type {string}
* @implicitCast
* @see http://www.w3.org/TR/html5/forms.html#attr-fs-formaction
*/
HTMLButtonElement.prototype.formAction;
/**
* @type {string}
* @see http://www.w3.org/TR/html5/forms.html#attr-fs-formenctype
*/
HTMLButtonElement.prototype.formEnctype;
/**
* @type {string}
* @see http://www.w3.org/TR/html5/forms.html#attr-fs-formmethod
*/
HTMLButtonElement.prototype.formMethod;
/**
* @type {string}
* @see http://www.w3.org/TR/html5/forms.html#attr-fs-formtarget
*/
HTMLButtonElement.prototype.formTarget;
/** @type {boolean} */
HTMLInputElement.prototype.autofocus;
/** @type {boolean} */
HTMLInputElement.prototype.formNoValidate;
/**
* @type {string}
* @implicitCast
* @see http://www.w3.org/TR/html5/forms.html#attr-fs-formaction
*/
HTMLInputElement.prototype.formAction;
/**
* @type {string}
* @see http://www.w3.org/TR/html5/forms.html#attr-fs-formenctype
*/
HTMLInputElement.prototype.formEnctype;
/**
* @type {string}
* @see http://www.w3.org/TR/html5/forms.html#attr-fs-formmethod
*/
HTMLInputElement.prototype.formMethod;
/**
* @type {string}
* @see http://www.w3.org/TR/html5/forms.html#attr-fs-formtarget
*/
HTMLInputElement.prototype.formTarget;
/**
* Can return null when hidden.
* See https://html.spec.whatwg.org/multipage/forms.html#dom-lfe-labels
* @const {?NodeList<!HTMLLabelElement>}
*/
HTMLInputElement.prototype.labels;
/** @type {string} */
HTMLInputElement.prototype.validationMessage;
/**
* @type {number}
* @implicitCast
*/
HTMLInputElement.prototype.selectionStart;
/**
* @type {number}
* @implicitCast
*/
HTMLInputElement.prototype.selectionEnd;
/** @type {string} */
HTMLInputElement.prototype.selectionDirection;
/**
* @param {number} start
* @param {number} end
* @param {string=} direction
* @see https://html.spec.whatwg.org/#dom-textarea/input-setselectionrange
* @return {undefined}
*/
HTMLInputElement.prototype.setSelectionRange = function(start, end, direction) {};
/**
* @param {string} replacement
* @param {number=} start
* @param {number=} end
* @param {string=} selectionMode
* @see https://html.spec.whatwg.org/#dom-textarea/input-setrangetext
* @return {undefined}
*/
HTMLInputElement.prototype.setRangeText =
function(replacement, start, end, selectionMode) {};
/**
* @const {ValidityState}
*/
HTMLInputElement.prototype.validity;
/** @type {boolean} */
HTMLInputElement.prototype.willValidate;
/** @return {boolean} */
HTMLInputElement.prototype.checkValidity = function() {};
/** @return {boolean} */
HTMLInputElement.prototype.reportValidity = function() {};
/**
* @param {string} message
* @return {undefined}
*/
HTMLInputElement.prototype.setCustomValidity = function(message) {};
/** @type {Element} */
HTMLLabelElement.prototype.control;
/** @type {boolean} */
HTMLSelectElement.prototype.autofocus;
/**
* Can return null when hidden.
* See https://html.spec.whatwg.org/multipage/forms.html#dom-lfe-labels
* @const {?NodeList<!HTMLLabelElement>}
*/
HTMLSelectElement.prototype.labels;
/** @type {boolean} */
HTMLSelectElement.prototype.required;
/** @type {HTMLCollection<!HTMLOptionElement>} */
HTMLSelectElement.prototype.selectedOptions;
/** @type {string} */
HTMLSelectElement.prototype.validationMessage;
/**
* @const {ValidityState}
*/
HTMLSelectElement.prototype.validity;
/** @type {boolean} */
HTMLSelectElement.prototype.willValidate;
/** @return {boolean} */
HTMLSelectElement.prototype.checkValidity = function() {};
/** @return {boolean} */
HTMLSelectElement.prototype.reportValidity = function() {};
/**
* @param {string} message
* @return {undefined}
*/
HTMLSelectElement.prototype.setCustomValidity = function(message) {};
/** @type {boolean} */
HTMLTextAreaElement.prototype.autofocus;
/**
* Can return null when hidden.
* See https://html.spec.whatwg.org/multipage/forms.html#dom-lfe-labels
* @const {?NodeList<!HTMLLabelElement>}
*/
HTMLTextAreaElement.prototype.labels;
/** @type {number} */
HTMLTextAreaElement.prototype.maxLength;
/** @type {number} */
HTMLTextAreaElement.prototype.minLength;
/** @type {string} */
HTMLTextAreaElement.prototype.placeholder;
/** @type {number} */
HTMLTextAreaElement.prototype.textLength;
/** @type {string} */
HTMLTextAreaElement.prototype.validationMessage;
/**
* @const {ValidityState}
*/
HTMLTextAreaElement.prototype.validity;
/** @type {boolean} */
HTMLTextAreaElement.prototype.willValidate;
/** @return {boolean} */
HTMLTextAreaElement.prototype.checkValidity = function() {};
/** @return {boolean} */
HTMLTextAreaElement.prototype.reportValidity = function() {};
/**
* @param {string} message
* @return {undefined}
*/
HTMLTextAreaElement.prototype.setCustomValidity = function(message) {};
/**
* @constructor
* @extends {HTMLElement}
* @see http://www.w3.org/TR/html5/the-embed-element.html#htmlembedelement
*/
function HTMLEmbedElement() {}
/**
* @type {string}
* @see http://www.w3.org/TR/html5/dimension-attributes.html#dom-dim-width
*/
HTMLEmbedElement.prototype.width;
/**
* @type {string}
* @see http://www.w3.org/TR/html5/dimension-attributes.html#dom-dim-height
*/
HTMLEmbedElement.prototype.height;
/**
* @type {string}
* @implicitCast
* @see http://www.w3.org/TR/html5/the-embed-element.html#dom-embed-src
*/
HTMLEmbedElement.prototype.src;
/**
* @type {string}
* @see http://www.w3.org/TR/html5/the-embed-element.html#dom-embed-type
*/
HTMLEmbedElement.prototype.type;
// Fullscreen APIs.
/**
* @record
* @see https://fullscreen.spec.whatwg.org/#dictdef-fullscreenoptions
*/
function FullscreenOptions() {}
/** @type {string} */
FullscreenOptions.prototype.navigationUI;
/**
* @see https://fullscreen.spec.whatwg.org/#dom-element-requestfullscreen
* @param {!FullscreenOptions=} options
* @return {!Promise<undefined>}
*/
Element.prototype.requestFullscreen = function(options) {};
/**
* @type {boolean}
* @see http://www.w3.org/TR/2012/WD-fullscreen-20120703/#dom-document-fullscreenenabled
*/
Document.prototype.fullscreenEnabled;
/**
* @type {Element}
* @see http://www.w3.org/TR/2012/WD-fullscreen-20120703/#dom-document-fullscreenelement
*/
Document.prototype.fullscreenElement;
/**
* @see http://www.w3.org/TR/2012/WD-fullscreen-20120703/#dom-document-exitfullscreen
* @return {undefined}
*/
Document.prototype.exitFullscreen = function() {};
// Externs definitions of browser current implementations.
// Firefox 10 implementation.
Element.prototype.mozRequestFullScreen = function() {};
Element.prototype.mozRequestFullScreenWithKeys = function() {};
/** @type {boolean} */
Document.prototype.mozFullScreen;
Document.prototype.mozCancelFullScreen = function() {};
/** @type {Element} */
Document.prototype.mozFullScreenElement;
/** @type {boolean} */
Document.prototype.mozFullScreenEnabled;
// Chrome 21 implementation.
/**
* The current fullscreen element for the document is set to this element.
* Valid only for Webkit browsers.
* @param {number=} opt_allowKeyboardInput Whether keyboard input is desired.
* Should use ALLOW_KEYBOARD_INPUT constant.
* @return {undefined}
*/
Element.prototype.webkitRequestFullScreen = function(opt_allowKeyboardInput) {};
/**
* The current fullscreen element for the document is set to this element.
* Valid only for Webkit browsers.
* @param {number=} opt_allowKeyboardInput Whether keyboard input is desired.
* Should use ALLOW_KEYBOARD_INPUT constant.
* @return {undefined}
*/
Element.prototype.webkitRequestFullscreen = function(opt_allowKeyboardInput) {};
/** @type {boolean} */
Document.prototype.webkitIsFullScreen;
Document.prototype.webkitCancelFullScreen = function() {};
/** @type {boolean} */
Document.prototype.webkitFullscreenEnabled;
/** @type {Element} */
Document.prototype.webkitCurrentFullScreenElement;
/** @type {Element} */
Document.prototype.webkitFullscreenElement;
/** @type {boolean} */
Document.prototype.webkitFullScreenKeyboardInputAllowed;
// IE 11 implementation.
// http://msdn.microsoft.com/en-us/library/ie/dn265028(v=vs.85).aspx
/** @return {void} */
Element.prototype.msRequestFullscreen = function() {};
/** @return {void} */
Document.prototype.msExitFullscreen = function() {};
/** @type {boolean} */
Document.prototype.msFullscreenEnabled;
/** @type {Element} */
Document.prototype.msFullscreenElement;
/** @const {number} */
Element.ALLOW_KEYBOARD_INPUT;
/** @const {number} */
Element.prototype.ALLOW_KEYBOARD_INPUT;
/**
* @typedef {{
* childList: (boolean|undefined),
* attributes: (boolean|undefined),
* characterData: (boolean|undefined),
* subtree: (boolean|undefined),
* attributeOldValue: (boolean|undefined),
* characterDataOldValue: (boolean|undefined),
* attributeFilter: (!Array<string>|undefined)
* }}
*/
var MutationObserverInit;
/** @constructor */
function MutationRecord() {}
/** @type {string} */
MutationRecord.prototype.type;
/** @type {Node} */
MutationRecord.prototype.target;
/** @type {!NodeList<!Node>} */
MutationRecord.prototype.addedNodes;
/** @type {!NodeList<!Node>} */
MutationRecord.prototype.removedNodes;
/** @type {?Node} */
MutationRecord.prototype.previousSibling;
/** @type {?Node} */
MutationRecord.prototype.nextSibling;
/** @type {?string} */
MutationRecord.prototype.attributeName;
/** @type {?string} */
MutationRecord.prototype.attributeNamespace;
/** @type {?string} */
MutationRecord.prototype.oldValue;
/**
* @see http://www.w3.org/TR/domcore/#mutation-observers
* @param {function(!Array<!MutationRecord>, !MutationObserver)} callback
* @constructor
*/
function MutationObserver(callback) {}
/**
* @param {Node} target
* @param {MutationObserverInit=} options
* @return {undefined}
*/
MutationObserver.prototype.observe = function(target, options) {};
MutationObserver.prototype.disconnect = function() {};
/**
* @return {!Array<!MutationRecord>}
*/
MutationObserver.prototype.takeRecords = function() {};
/**
* @type {function(new:MutationObserver, function(Array<MutationRecord>))}
*/
Window.prototype.WebKitMutationObserver;
/**
* @type {function(new:MutationObserver, function(Array<MutationRecord>))}
*/
Window.prototype.MozMutationObserver;
/**
* @see http://www.w3.org/TR/page-visibility/
* @type {VisibilityState}
*/
Document.prototype.visibilityState;
/**
* @type {string}
*/
Document.prototype.mozVisibilityState;
/**
* @type {string}
*/
Document.prototype.webkitVisibilityState;
/**
* @type {string}
*/
Document.prototype.msVisibilityState;
/**
* @see http://www.w3.org/TR/page-visibility/
* @type {boolean}
*/
Document.prototype.hidden;
/**
* @type {boolean}
*/
Document.prototype.mozHidden;
/**
* @type {boolean}
*/
Document.prototype.webkitHidden;
/**
* @type {boolean}
*/
Document.prototype.msHidden;
/**
* @see http://www.w3.org/TR/components-intro/
* @see http://w3c.github.io/webcomponents/spec/custom/#extensions-to-document-interface-to-register
* @param {string} type
* @param {{extends: (string|undefined), prototype: (Object|undefined)}=}
* options
* @return {function(new:Element, ...*)} a constructor for the new tag.
* @deprecated document.registerElement() is deprecated in favor of
* customElements.define()
*/
Document.prototype.registerElement = function(type, options) {};
/**
* @see http://www.w3.org/TR/components-intro/
* @see http://w3c.github.io/webcomponents/spec/custom/#extensions-to-document-interface-to-register
* @param {string} type
* @param {{extends: (string|undefined), prototype: (Object|undefined)}} options
* @deprecated This method has been removed and will be removed soon from this file.
*/
Document.prototype.register = function(type, options) {};
/**
* @type {!FontFaceSet}
* @see http://dev.w3.org/csswg/css-font-loading/#dom-fontfacesource-fonts
*/
Document.prototype.fonts;
/**
* @type {?HTMLScriptElement}
* @see https://developer.mozilla.org/en-US/docs/Web/API/Document/currentScript
*/
Document.prototype.currentScript;
/**
* Definition of ShadowRoot interface,
* @see http://www.w3.org/TR/shadow-dom/#api-shadow-root
* @constructor
* @extends {DocumentFragment}
*/
function ShadowRoot() {}
/**
* The host element that a ShadowRoot is attached to.
* Note: this is not yet W3C standard but is undergoing development.
* W3C feature tracking bug:
* https://www.w3.org/Bugs/Public/show_bug.cgi?id=22399
* Draft specification:
* https://dvcs.w3.org/hg/webcomponents/raw-file/6743f1ace623/spec/shadow/index.html#shadow-root-object
* @type {!Element}
*/
ShadowRoot.prototype.host;
/**
* @param {string} id id.
* @return {HTMLElement}
* @nosideeffects
*/
ShadowRoot.prototype.getElementById = function(id) {};
/**
* @return {Selection}
* @nosideeffects
*/
ShadowRoot.prototype.getSelection = function() {};
/**
* @param {number} x
* @param {number} y
* @return {Element}
* @nosideeffects
*/
ShadowRoot.prototype.elementFromPoint = function(x, y) {};
/**
* @param {number} x
* @param {number} y
* @return {!IArrayLike<!Element>}
* @nosideeffects
*/
ShadowRoot.prototype.elementsFromPoint = function(x, y) {};
/**
* @type {?Element}
*/
ShadowRoot.prototype.activeElement;
/**
* @type {!ShadowRootMode}
*/
ShadowRoot.prototype.mode;
/**
* @type {?ShadowRoot}
* @deprecated
*/
ShadowRoot.prototype.olderShadowRoot;
/**
* @type {string}
* @implicitCast
*/
ShadowRoot.prototype.innerHTML;
/**
* @type {!StyleSheetList}
*/
ShadowRoot.prototype.styleSheets;
/**
* @typedef {string}
* @see https://dom.spec.whatwg.org/#enumdef-shadowrootmode
*/
var ShadowRootMode;
/**
* @typedef {string}
* @see https://dom.spec.whatwg.org/#enumdef-slotassignmentmode
*/
var SlotAssignmentMode;
/**
* @record
* @see https://dom.spec.whatwg.org/#dictdef-shadowrootinit
*/
function ShadowRootInit() {}
/** @type {!ShadowRootMode} */
ShadowRootInit.prototype.mode;
/** @type {(undefined|boolean)} */
ShadowRootInit.prototype.delegatesFocus;
/** @type {(undefined|SlotAssignmentMode)} */
ShadowRootInit.prototype.slotAssignment;
/**
* @see http://www.w3.org/TR/shadow-dom/#the-content-element
* @constructor
* @extends {HTMLElement}
*/
function HTMLContentElement() {}
/**
* @type {string}
*/
HTMLContentElement.prototype.select;
/**
* @return {!NodeList<!Node>}
*/
HTMLContentElement.prototype.getDistributedNodes = function() {};
/**
* @see http://www.w3.org/TR/shadow-dom/#the-shadow-element
* @constructor
* @extends {HTMLElement}
*/
function HTMLShadowElement() {}
/**
* @return {!NodeList<!Node>}
*/
HTMLShadowElement.prototype.getDistributedNodes = function() {};
/**
* @see http://www.w3.org/TR/html5/webappapis.html#the-errorevent-interface
*
* @constructor
* @extends {Event}
*
* @param {string} type
* @param {ErrorEventInit=} opt_eventInitDict
*/
function ErrorEvent(type, opt_eventInitDict) {}
/** @const {string} */
ErrorEvent.prototype.message;
/** @const {string} */
ErrorEvent.prototype.filename;
/** @const {number} */
ErrorEvent.prototype.lineno;
/** @const {number} */
ErrorEvent.prototype.colno;
/** @const {*} */
ErrorEvent.prototype.error;
/**
* @record
* @extends {EventInit}
* @see https://www.w3.org/TR/html5/webappapis.html#erroreventinit
*/
function ErrorEventInit() {}
/** @type {undefined|string} */
ErrorEventInit.prototype.message;
/** @type {undefined|string} */
ErrorEventInit.prototype.filename;
/** @type {undefined|number} */
ErrorEventInit.prototype.lineno;
/** @type {undefined|number} */
ErrorEventInit.prototype.colno;
/** @type {*} */
ErrorEventInit.prototype.error;
/**
* @see http://dom.spec.whatwg.org/#dom-domimplementation-createhtmldocument
* @param {string=} opt_title A title to give the new HTML document
* @return {!HTMLDocument}
*/
DOMImplementation.prototype.createHTMLDocument = function(opt_title) {};
/**
* @constructor
* @see https://html.spec.whatwg.org/multipage/embedded-content.html#the-picture-element
* @extends {HTMLElement}
*/
function HTMLPictureElement() {}
/**
* @constructor
* @see https://html.spec.whatwg.org/multipage/embedded-content.html#the-picture-element
* @extends {HTMLElement}
*/
function HTMLSourceElement() {}
/** @type {string} */
HTMLSourceElement.prototype.media;
/** @type {string} */
HTMLSourceElement.prototype.sizes;
/** @type {string} @implicitCast */
HTMLSourceElement.prototype.src;
/** @type {string} */
HTMLSourceElement.prototype.srcset;
/** @type {string} */
HTMLSourceElement.prototype.type;
/** @type {string} */
HTMLImageElement.prototype.sizes;
/** @type {string} */
HTMLImageElement.prototype.srcset;
/**
* 4.11 Interactive elements
* @see http://www.w3.org/html/wg/drafts/html/master/interactive-elements.html
*/
/**
* @see http://www.w3.org/html/wg/drafts/html/master/interactive-elements.html#the-details-element
* @constructor
* @extends {HTMLElement}
*/
function HTMLDetailsElement() {}
/**
* @see http://www.w3.org/html/wg/drafts/html/master/interactive-elements.html#dom-details-open
* @type {boolean}
*/
HTMLDetailsElement.prototype.open;
// As of 2/20/2015, <summary> has no special web IDL interface nor global
// constructor (i.e. HTMLSummaryElement).
/**
* @see http://www.w3.org/html/wg/drafts/html/master/interactive-elements.html#dom-menu-type
* @type {string}
*/
HTMLMenuElement.prototype.type;
/**
* @see http://www.w3.org/html/wg/drafts/html/master/interactive-elements.html#dom-menu-label
* @type {string}
*/
HTMLMenuElement.prototype.label;
/**
* @see http://www.w3.org/html/wg/drafts/html/master/interactive-elements.html#the-menuitem-element
* @constructor
* @extends {HTMLElement}
*/
function HTMLMenuItemElement() {}
/**
* @see http://www.w3.org/html/wg/drafts/html/master/interactive-elements.html#dom-menuitem-type
* @type {string}
*/
HTMLMenuItemElement.prototype.type;
/**
* @see http://www.w3.org/html/wg/drafts/html/master/interactive-elements.html#dom-menuitem-label
* @type {string}
*/
HTMLMenuItemElement.prototype.label;
/**
* @see http://www.w3.org/html/wg/drafts/html/master/interactive-elements.html#dom-menuitem-icon
* @type {string}
*/
HTMLMenuItemElement.prototype.icon;
/**
* @see http://www.w3.org/html/wg/drafts/html/master/interactive-elements.html#dom-menuitem-disabled
* @type {boolean}
*/
HTMLMenuItemElement.prototype.disabled;
/**
* @see http://www.w3.org/html/wg/drafts/html/master/interactive-elements.html#dom-menuitem-checked
* @type {boolean}
*/
HTMLMenuItemElement.prototype.checked;
/**
* @see http://www.w3.org/html/wg/drafts/html/master/interactive-elements.html#dom-menuitem-radiogroup
* @type {string}
*/
HTMLMenuItemElement.prototype.radiogroup;
/**
* @see http://www.w3.org/html/wg/drafts/html/master/interactive-elements.html#dom-menuitem-default
* @type {boolean}
*/
HTMLMenuItemElement.prototype.default;
// TODO(dbeam): add HTMLMenuItemElement.prototype.command if it's implemented.
/**
* @see http://www.w3.org/html/wg/drafts/html/master/interactive-elements.html#relatedevent
* @param {string} type
* @param {{relatedTarget: (EventTarget|undefined)}=} opt_eventInitDict
* @constructor
* @extends {Event}
*/
function RelatedEvent(type, opt_eventInitDict) {}
/**
* @see http://www.w3.org/html/wg/drafts/html/master/interactive-elements.html#dom-relatedevent-relatedtarget
* @type {EventTarget|undefined}
*/
RelatedEvent.prototype.relatedTarget;
/**
* @see http://www.w3.org/html/wg/drafts/html/master/interactive-elements.html#the-dialog-element
* @constructor
* @extends {HTMLElement}
*/
function HTMLDialogElement() {}
/**
* @see http://www.w3.org/html/wg/drafts/html/master/interactive-elements.html#dom-dialog-open
* @type {boolean}
*/
HTMLDialogElement.prototype.open;
/**
* @see http://www.w3.org/html/wg/drafts/html/master/interactive-elements.html#dom-dialog-returnvalue
* @type {string}
*/
HTMLDialogElement.prototype.returnValue;
/**
* @see http://www.w3.org/html/wg/drafts/html/master/interactive-elements.html#dom-dialog-show
* @param {(MouseEvent|Element)=} opt_anchor
* @return {undefined}
*/
HTMLDialogElement.prototype.show = function(opt_anchor) {};
/**
* @see http://www.w3.org/html/wg/drafts/html/master/interactive-elements.html#dom-dialog-showmodal
* @param {(MouseEvent|Element)=} opt_anchor
* @return {undefined}
*/
HTMLDialogElement.prototype.showModal = function(opt_anchor) {};
/**
* @see http://www.w3.org/html/wg/drafts/html/master/interactive-elements.html#dom-dialog-close
* @param {string=} opt_returnValue
* @return {undefined}
*/
HTMLDialogElement.prototype.close = function(opt_returnValue) {};
/**
* @see https://html.spec.whatwg.org/multipage/scripting.html#the-template-element
* @constructor
* @extends {HTMLElement}
*/
function HTMLTemplateElement() {}
/**
* @see https://html.spec.whatwg.org/multipage/scripting.html#the-template-element
* @type {!DocumentFragment}
*/
HTMLTemplateElement.prototype.content;
/**
* @type {?Document}
* @see w3c_dom2.js
* @see http://www.w3.org/TR/html-imports/#interface-import
*/
HTMLLinkElement.prototype.import;
/**
* @type {string}
* @see https://html.spec.whatwg.org/#attr-link-as
* @see https://w3c.github.io/preload/#as-attribute
*/
HTMLLinkElement.prototype.as;
/**
* @see https://html.spec.whatwg.org/#attr-link-crossorigin
* @type {string}
*/
HTMLLinkElement.prototype.crossOrigin;
/**
* @return {boolean}
* @see https://www.w3.org/TR/html5/forms.html#dom-fieldset-elements
*/
HTMLFieldSetElement.prototype.checkValidity = function() {};
/**
* @type {HTMLCollection}
* @see https://www.w3.org/TR/html5/forms.html#dom-fieldset-elements
*/
HTMLFieldSetElement.prototype.elements;
/**
* @type {string}
* @see https://www.w3.org/TR/html5/forms.html#the-fieldset-element
*/
HTMLFieldSetElement.prototype.name;
/**
* @param {string} message
* @see https://www.w3.org/TR/html5/forms.html#dom-fieldset-elements
* @return {undefined}
*/
HTMLFieldSetElement.prototype.setCustomValidity = function(message) {};
/**
* @type {string}
* @see https://www.w3.org/TR/html5/forms.html#dom-fieldset-type
*/
HTMLFieldSetElement.prototype.type;
/**
* @type {string}
* @see https://www.w3.org/TR/html5/forms.html#the-fieldset-element
*/
HTMLFieldSetElement.prototype.validationMessage;
/**
* @type {ValidityState}
* @see https://www.w3.org/TR/html5/forms.html#the-fieldset-element
*/
HTMLFieldSetElement.prototype.validity;
/**
* @type {boolean}
* @see https://www.w3.org/TR/html5/forms.html#the-fieldset-element
*/
HTMLFieldSetElement.prototype.willValidate;
/**
* @constructor
* @extends {NodeList<T>}
* @template T
* @see https://html.spec.whatwg.org/multipage/infrastructure.html#radionodelist
*/
function RadioNodeList() {}
/**
* @type {string}
* @see https://html.spec.whatwg.org/multipage/infrastructure.html#radionodelist
*/
RadioNodeList.prototype.value;
/**
* @see https://html.spec.whatwg.org/multipage/forms.html#the-datalist-element
* @constructor
* @extends {HTMLElement}
*/
function HTMLDataListElement() {}
/** @type {HTMLCollection<!HTMLOptionElement>} */
HTMLDataListElement.prototype.options;
/**
* @return {boolean}
* @see https://html.spec.whatwg.org/multipage/iframe-embed-object.html#the-object-element
*/
HTMLObjectElement.prototype.checkValidity;
/**
* @param {string} message
* @see https://html.spec.whatwg.org/multipage/iframe-embed-object.html#the-object-element
* @return {undefined}
*/
HTMLObjectElement.prototype.setCustomValidity;
/**
* @type {string}
* @see https://html.spec.whatwg.org/multipage/iframe-embed-object.html#the-object-element
*/
HTMLObjectElement.prototype.validationMessage;
/**
* @type {!ValidityState}
* @see https://html.spec.whatwg.org/multipage/iframe-embed-object.html#the-object-element
*/
HTMLObjectElement.prototype.validity;
/**
* @type {boolean}
* @see https://html.spec.whatwg.org/multipage/iframe-embed-object.html#the-object-element
*/
HTMLObjectElement.prototype.willValidate;
/**
* @see https://html.spec.whatwg.org/multipage/forms.html#the-output-element
* @constructor
* @extends {HTMLElement}
*/
function HTMLOutputElement() {}
/**
* @const {!DOMTokenList}
*/
HTMLOutputElement.prototype.htmlFor;
/**
* @type {HTMLFormElement}
*/
HTMLOutputElement.prototype.form;
/**
* @type {string}
*/
HTMLOutputElement.prototype.name;
/**
* @const {string}
*/
HTMLOutputElement.prototype.type;
/**
* @type {string}
*/
HTMLOutputElement.prototype.defaultValue;
/**
* @type {string}
*/
HTMLOutputElement.prototype.value;
/**
* @const {?NodeList<!HTMLLabelElement>}
*/
HTMLOutputElement.prototype.labels;
/** @type {string} */
HTMLOutputElement.prototype.validationMessage;
/**
* @const {ValidityState}
*/
HTMLOutputElement.prototype.validity;
/** @type {boolean} */
HTMLOutputElement.prototype.willValidate;
/** @return {boolean} */
HTMLOutputElement.prototype.checkValidity = function() {};
/** @return {boolean} */
HTMLOutputElement.prototype.reportValidity = function() {};
/** @param {string} message */
HTMLOutputElement.prototype.setCustomValidity = function(message) {};
/**
* @see https://html.spec.whatwg.org/multipage/forms.html#the-progress-element
* @constructor
* @extends {HTMLElement}
*/
function HTMLProgressElement() {}
/** @type {number} */
HTMLProgressElement.prototype.value;
/** @type {number} */
HTMLProgressElement.prototype.max;
/** @type {number} */
HTMLProgressElement.prototype.position;
/** @type {?NodeList<!Node>} */
HTMLProgressElement.prototype.labels;
/**
* @see https://html.spec.whatwg.org/multipage/embedded-content.html#the-track-element
* @constructor
* @extends {HTMLElement}
*/
function HTMLTrackElement() {}
/** @type {string} */
HTMLTrackElement.prototype.kind;
/** @type {string} @implicitCast */
HTMLTrackElement.prototype.src;
/** @type {string} */
HTMLTrackElement.prototype.srclang;
/** @type {string} */
HTMLTrackElement.prototype.label;
/** @type {boolean} */
HTMLTrackElement.prototype.default;
/** @const {number} */
HTMLTrackElement.prototype.readyState;
/** @const {!TextTrack} */
HTMLTrackElement.prototype.track;
/**
* @see https://html.spec.whatwg.org/multipage/forms.html#the-meter-element
* @constructor
* @extends {HTMLElement}
*/
function HTMLMeterElement() {}
/** @type {number} */
HTMLMeterElement.prototype.value;
/** @type {number} */
HTMLMeterElement.prototype.min;
/** @type {number} */
HTMLMeterElement.prototype.max;
/** @type {number} */
HTMLMeterElement.prototype.low;
/** @type {number} */
HTMLMeterElement.prototype.high;
/** @type {number} */
HTMLMeterElement.prototype.optimum;
/** @type {?NodeList<!Node>} */
HTMLMeterElement.prototype.labels;
/**
* @interface
* @see https://storage.spec.whatwg.org/#api
*/
function NavigatorStorage() {};
/**
* @type {!StorageManager}
*/
NavigatorStorage.prototype.storage;
/**
* @constructor
* @implements NavigatorStorage
* @see https://www.w3.org/TR/html5/webappapis.html#navigator
*/
function Navigator() {}
/**
* @type {string}
* @see https://www.w3.org/TR/html5/webappapis.html#dom-navigator-appcodename
*/
Navigator.prototype.appCodeName;
/**
* @type {string}
* @see https://www.w3.org/TR/html5/webappapis.html#dom-navigator-appname
*/
Navigator.prototype.appName;
/**
* @type {string}
* @see https://www.w3.org/TR/html5/webappapis.html#dom-navigator-appversion
*/
Navigator.prototype.appVersion;
/**
* @type {string}
* @see https://www.w3.org/TR/html5/webappapis.html#dom-navigator-platform
*/
Navigator.prototype.platform;
/**
* @type {string}
* @see https://www.w3.org/TR/html5/webappapis.html#dom-navigator-product
*/
Navigator.prototype.product;
/**
* @type {string}
* @see https://www.w3.org/TR/html5/webappapis.html#dom-navigator-useragent
*/
Navigator.prototype.userAgent;
/**
* @return {boolean}
* @see https://www.w3.org/TR/html5/webappapis.html#dom-navigator-taintenabled
*/
Navigator.prototype.taintEnabled = function() {};
/**
* @type {string}
* @see https://www.w3.org/TR/html5/webappapis.html#dom-navigator-language
*/
Navigator.prototype.language;
/**
* @type {boolean}
* @see https://www.w3.org/TR/html5/browsers.html#navigatoronline
*/
Navigator.prototype.onLine;
/**
* @type {boolean}
* @see https://www.w3.org/TR/html5/webappapis.html#dom-navigator-cookieenabled
*/
Navigator.prototype.cookieEnabled;
/**
* @param {string} scheme
* @param {string} url
* @param {string} title
* @return {undefined}
*/
Navigator.prototype.registerProtocolHandler = function(scheme, url, title) {}
/**
* @param {string} mimeType
* @param {string} url
* @param {string} title
* @return {undefined}
*/
Navigator.prototype.registerContentHandler = function(mimeType, url, title) {}
/**
* @param {string} scheme
* @param {string} url
* @return {undefined}
*/
Navigator.prototype.unregisterProtocolHandler = function(scheme, url) {}
/**
* @param {string} mimeType
* @param {string} url
* @return {undefined}
*/
Navigator.prototype.unregisterContentHandler = function(mimeType, url) {}
/**
* @type {!MimeTypeArray}
* @see https://www.w3.org/TR/html5/webappapis.html#dom-navigator-mimetypes
*/
Navigator.prototype.mimeTypes;
/**
* @type {!PluginArray}
* @see https://www.w3.org/TR/html5/webappapis.html#dom-navigator-plugins
*/
Navigator.prototype.plugins;
/**
* @return {boolean}
* @see https://www.w3.org/TR/html5/webappapis.html#dom-navigator-javaenabled
* @nosideeffects
*/
Navigator.prototype.javaEnabled = function() {};
/**
* @type {number}
* @see https://developers.google.com/web/updates/2017/12/device-memory
* https://github.com/w3c/device-memory
*/
Navigator.prototype.deviceMemory;
/**
* @type {!StorageManager}
* @see https://storage.spec.whatwg.org
*/
Navigator.prototype.storage;
/**
* @param {!ShareData=} data
* @return {boolean}
* @see https://developer.mozilla.org/en-US/docs/Web/API/Navigator/canShare
*/
Navigator.prototype.canShare = function(data) {};
/**
* @param {!ShareData=} data
* @return {!Promise<undefined>}
* @see https://wicg.github.io/web-share/#share-method
*/
Navigator.prototype.share = function(data) {};
/**
* @type {number}
* @see https://developer.mozilla.org/en-US/docs/Web/API/NavigatorConcurrentHardware/hardwareConcurrency
*/
Navigator.prototype.hardwareConcurrency;
/**
* @constructor
* @implements NavigatorStorage
* @see https://html.spec.whatwg.org/multipage/workers.html#the-workernavigator-object
*/
function WorkerNavigator() {}
/**
* @type {number}
* @see https://developers.google.com/web/updates/2017/12/device-memory
* https://github.com/w3c/device-memory
*/
WorkerNavigator.prototype.deviceMemory;
/**
* @type {number}
* @see https://developer.mozilla.org/en-US/docs/Web/API/NavigatorConcurrentHardware/hardwareConcurrency
*/
WorkerNavigator.prototype.hardwareConcurrency;
/**
* @type {!StorageManager}
* @see https://storage.spec.whatwg.org
*/
WorkerNavigator.prototype.storage;
/**
* @record
* @see https://wicg.github.io/web-share/#sharedata-dictionary
*/
function ShareData() {}
/** @type {string|undefined} */
ShareData.prototype.title;
/** @type {string|undefined} */
ShareData.prototype.text;
/** @type {string|undefined} */
ShareData.prototype.url;
/**
* @constructor
* @implements {IObject<(string|number),!Plugin>}
* @implements {IArrayLike<!Plugin>}
* @see https://www.w3.org/TR/html5/webappapis.html#pluginarray
*/
function PluginArray() {}
/** @type {number} */
PluginArray.prototype.length;
/**
* @param {number} index
* @return {Plugin}
*/
PluginArray.prototype.item = function(index) {};
/**
* @param {string} name
* @return {Plugin}
*/
PluginArray.prototype.namedItem = function(name) {};
/**
* @param {boolean=} reloadDocuments
* @return {undefined}
*/
PluginArray.prototype.refresh = function(reloadDocuments) {};
/**
* @constructor
* @implements {IObject<(string|number),!MimeType>}
* @implements {IArrayLike<!MimeType>}
* @see https://www.w3.org/TR/html5/webappapis.html#mimetypearray
*/
function MimeTypeArray() {}
/**
* @param {number} index
* @return {MimeType}
*/
MimeTypeArray.prototype.item = function(index) {};
/**
* @type {number}
* @see https://developer.mozilla.org/en/DOM/window.navigator.mimeTypes
*/
MimeTypeArray.prototype.length;
/**
* @param {string} name
* @return {MimeType}
*/
MimeTypeArray.prototype.namedItem = function(name) {};
/**
* @constructor
* @see https://www.w3.org/TR/html5/webappapis.html#mimetype
*/
function MimeType() {}
/** @type {string} */
MimeType.prototype.description;
/** @type {Plugin} */
MimeType.prototype.enabledPlugin;
/** @type {string} */
MimeType.prototype.suffixes;
/** @type {string} */
MimeType.prototype.type;
/**
* @constructor
* @see https://www.w3.org/TR/html5/webappapis.html#dom-plugin
*/
function Plugin() {}
/** @type {string} */
Plugin.prototype.description;
/** @type {string} */
Plugin.prototype.filename;
/** @type {number} */
Plugin.prototype.length;
/** @type {string} */
Plugin.prototype.name;
/**
* @see https://html.spec.whatwg.org/multipage/custom-elements.html#customelementregistry
* @constructor
*/
function CustomElementRegistry() {}
/**
* @param {string} tagName
* @param {function(new:HTMLElement)} klass
* @param {{extends: string}=} options
* @return {undefined}
*/
CustomElementRegistry.prototype.define = function (tagName, klass, options) {};
/**
* @param {string} tagName
* @return {function(new:HTMLElement)|undefined}
*/
CustomElementRegistry.prototype.get = function(tagName) {};
/**
* @param {string} tagName
* @return {!Promise<undefined>}
*/
CustomElementRegistry.prototype.whenDefined = function(tagName) {};
/**
* @param {!Node} root
* @return {undefined}
*/
CustomElementRegistry.prototype.upgrade = function(root) {};
/** @type {!CustomElementRegistry} */
var customElements;
/**
* @constructor
* @extends {HTMLElement}
*/
function HTMLSlotElement() {}
/** @typedef {{flatten: boolean}} */
var AssignedNodesOptions;
/**
* @param {!AssignedNodesOptions=} options
* @return {!Array<!Node>}
*/
HTMLSlotElement.prototype.assignedNodes = function(options) {};
/**
* @param {!AssignedNodesOptions=} options
* @return {!Array<!HTMLElement>}
*/
HTMLSlotElement.prototype.assignedElements = function(options) {};
/** @type {boolean} */
Event.prototype.composed;
/**
* @return {!Array<!EventTarget>}
* @see https://developer.mozilla.org/en-US/docs/Web/API/Event/composedPath
*/
Event.prototype.composedPath = function() {};
/**
* @constructor
* @param {{
* firesTouchEvents: (string|undefined),
* pointerMovementScrolls: (string|undefined)
* }=} opt_options
*/
function InputDeviceCapabilities(opt_options){}
/** @type {boolean} */
InputDeviceCapabilities.prototype.firesTouchEvents;
/** @type {boolean} */
InputDeviceCapabilities.prototype.pointerMovementScrolls;
/** @type {?InputDeviceCapabilities} */
UIEvent.prototype.sourceCapabilities;
/**
* @see https://developer.mozilla.org/en-US/docs/Web/API/VisualViewport
* @constructor
* @implements {EventTarget}
*/
function VisualViewport() {}
/** @type {number} */
VisualViewport.prototype.offsetLeft;
/** @type {number} */
VisualViewport.prototype.offsetTop;
/** @type {number} */
VisualViewport.prototype.pageLeft;
/** @type {number} */
VisualViewport.prototype.pageTop;
/** @type {number} */
VisualViewport.prototype.width;
/** @type {number} */
VisualViewport.prototype.height;
/** @type {number} */
VisualViewport.prototype.scale;
/** @override */
VisualViewport.prototype.addEventListener = function(type, listener,
opt_options) {};
/** @override */
VisualViewport.prototype.removeEventListener = function(type, listener,
opt_options) {};
/** @override */
VisualViewport.prototype.dispatchEvent = function(evt) {};
/** @type {?function(!Event)} */
VisualViewport.prototype.onresize;
/** @type {?function(!Event)} */
VisualViewport.prototype.onscroll;
/**
* @see https://storage.spec.whatwg.org/
* @constructor
*/
function StorageManager() {}
/** @return {!Promise<boolean>} */
StorageManager.prototype.persisted = function() {};
/** @return {!Promise<boolean>} */
StorageManager.prototype.persist = function() {};
/** @return {!Promise<StorageEstimate>} */
StorageManager.prototype.estimate = function() {};
/**
* @see https://storage.spec.whatwg.org/
* @typedef {{
* usage: number,
* quota: number
* }}
*/
var StorageEstimate;
/*
* Focus Management APIs
*
* See https://html.spec.whatwg.org/multipage/interaction.html#focus-management-apis
*/
/**
* @type {?Element}
* @see https://html.spec.whatwg.org/multipage/interaction.html#dom-document-activeelement
*/
Document.prototype.activeElement;
/**
* @see https://html.spec.whatwg.org/multipage/interaction.html#dom-document-hasfocus
* @return {boolean}
*/
Document.prototype.hasFocus = function() {};
/**
* @param {{preventScroll: boolean}=} options
* @return {undefined}
* @see https://html.spec.whatwg.org/multipage/interaction.html#dom-focus
*/
Element.prototype.focus = function(options) {};
/**
* @return {undefined}
* @see https://html.spec.whatwg.org/multipage/interaction.html#dom-blur
*/
Element.prototype.blur = function() {};
/**
* @see https://www.w3.org/TR/CSP3/#securitypolicyviolationevent
*
* @constructor
* @extends {Event}
*
* @param {string} type
* @param {SecurityPolicyViolationEventInit=}
* opt_securityPolicyViolationEventInitDict
*/
function SecurityPolicyViolationEvent(
type, opt_securityPolicyViolationEventInitDict) {}
/** @const {string} */
SecurityPolicyViolationEvent.prototype.documentURI;
/** @const {string} */
SecurityPolicyViolationEvent.prototype.referrer;
/** @const {string} */
SecurityPolicyViolationEvent.prototype.blockedURI;
/** @const {string} */
SecurityPolicyViolationEvent.prototype.effectiveDirective;
/** @const {string} */
SecurityPolicyViolationEvent.prototype.violatedDirective;
/** @const {string} */
SecurityPolicyViolationEvent.prototype.originalPolicy;
/** @const {string} */
SecurityPolicyViolationEvent.prototype.sourceFile;
/** @const {string} */
SecurityPolicyViolationEvent.prototype.sample;
/**
* @see https://www.w3.org/TR/CSP3/#enumdef-securitypolicyviolationeventdisposition
* @const {string}
*/
SecurityPolicyViolationEvent.prototype.disposition;
/** @const {number} */
SecurityPolicyViolationEvent.prototype.statusCode;
/** @const {number} */
SecurityPolicyViolationEvent.prototype.lineNumber;
/** @const {number} */
SecurityPolicyViolationEvent.prototype.columnNumber;
/**
* @record
* @extends {EventInit}
* @see https://www.w3.org/TR/CSP3/#dictdef-securitypolicyviolationeventinit
*/
function SecurityPolicyViolationEventInit() {}
/** @type {string} */
SecurityPolicyViolationEventInit.prototype.documentURI;
/** @type {undefined|string} */
SecurityPolicyViolationEventInit.prototype.referrer;
/** @type {undefined|string} */
SecurityPolicyViolationEventInit.prototype.blockedURI;
/** @type {string} */
SecurityPolicyViolationEventInit.prototype.disposition;
/** @type {string} */
SecurityPolicyViolationEventInit.prototype.effectiveDirective;
/** @type {string} */
SecurityPolicyViolationEventInit.prototype.violatedDirective;
/** @type {string} */
SecurityPolicyViolationEventInit.prototype.originalPolicy;
/** @type {undefined|string} */
SecurityPolicyViolationEventInit.prototype.sourceFile;
/** @type {undefined|string} */
SecurityPolicyViolationEventInit.prototype.sample;
/** @type {number} */
SecurityPolicyViolationEventInit.prototype.statusCode;
/** @type {undefined|number} */
SecurityPolicyViolationEventInit.prototype.lineNumber;
/** @type {undefined|number} */
SecurityPolicyViolationEventInit.prototype.columnNumber;
/**
* @see https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#formdataevent
*
* @constructor
* @extends {Event}
*
* @param {string} type
* @param {FormDataEventInit=} eventInitDict
*/
function FormDataEvent(type, eventInitDict) {}
/** @const {!FormData} */
FormDataEvent.prototype.formData;
/**
* @see https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#formdataeventinit
*
* @record
* @extends {EventInit}
*/
function FormDataEventInit() {}
/** @type {!FormData} */
FormDataEventInit.prototype.formData;
/**
* @see https://html.spec.whatwg.org/multipage/indices.html#event-formdata
* @type {?function(FormDataEvent)}
*/
HTMLFormElement.prototype.onformdata;
/**
* @const {boolean}
* Whether the document has opted in to cross-origin isolation.
* @see https://html.spec.whatwg.org/multipage/webappapis.html#dom-crossoriginisolated
*/
Window.prototype.crossOriginIsolated;
| externs/browser/html5.js | /*
* Copyright 2008 The Closure Compiler Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview Definitions for all the extensions over the
* W3C's DOM3 specification in HTML5. This file depends on
* w3c_dom3.js. The whole file has been fully type annotated.
*
* @see http://www.whatwg.org/specs/web-apps/current-work/multipage/index.html
* @see http://dev.w3.org/html5/spec/Overview.html
*
* This also includes Typed Array definitions from
* http://www.khronos.org/registry/typedarray/specs/latest/
*
* This relies on w3c_event.js being included first.
*
* @externs
*/
/** @type {?HTMLSlotElement} */
Node.prototype.assignedSlot;
/**
* @type {string}
* @see https://dom.spec.whatwg.org/#dom-element-slot
*/
Element.prototype.slot;
/**
* Note: In IE, the contains() method only exists on Elements, not Nodes.
* Therefore, it is recommended that you use the Conformance framework to
* prevent calling this on Nodes which are not Elements.
* @see https://connect.microsoft.com/IE/feedback/details/780874/node-contains-is-incorrect
*
* @param {Node} n The node to check
* @return {boolean} If 'n' is this Node, or is contained within this Node.
* @see https://developer.mozilla.org/en-US/docs/Web/API/Node.contains
* @nosideeffects
*/
Node.prototype.contains = function(n) {};
/** @type {boolean} */
Node.prototype.isConnected;
/**
* @type {boolean}
* @see https://html.spec.whatwg.org/multipage/scripting.html#the-script-element
*/
HTMLScriptElement.prototype.async;
/**
* @type {string?}
* @see https://html.spec.whatwg.org/multipage/scripting.html#the-script-element
*/
HTMLScriptElement.prototype.crossOrigin;
/**
* @type {string}
* @see https://html.spec.whatwg.org/multipage/scripting.html#the-script-element
*/
HTMLScriptElement.prototype.integrity;
/**
* @type {boolean}
* @see https://html.spec.whatwg.org/multipage/scripting.html#the-script-element
*/
HTMLScriptElement.prototype.noModule;
/**
* @type {string}
* @see https://html.spec.whatwg.org/multipage/scripting.html#the-script-element
*/
HTMLScriptElement.prototype.referrerPolicy;
/**
* @constructor
* @see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#the-canvas-element
* @extends {HTMLElement}
*/
function HTMLCanvasElement() {}
/** @type {number} */
HTMLCanvasElement.prototype.width;
/** @type {number} */
HTMLCanvasElement.prototype.height;
/**
* @see https://www.w3.org/TR/html5/scripting-1.html#dom-canvas-toblob
* @param {function(!Blob)} callback
* @param {string=} opt_type
* @param {...*} var_args
* @throws {Error}
*/
HTMLCanvasElement.prototype.toBlob = function(callback, opt_type, var_args) {};
/**
* @param {string=} opt_type
* @param {...*} var_args
* @return {string}
* @throws {Error}
*/
HTMLCanvasElement.prototype.toDataURL = function(opt_type, var_args) {};
/**
* @modifies {this}
* @param {string} contextId
* @param {Object=} opt_args
* @return {Object}
*/
HTMLCanvasElement.prototype.getContext = function(contextId, opt_args) {};
/**
* @see https://www.w3.org/TR/mediacapture-fromelement/
* @param {number=} opt_framerate
* @return {!MediaStream}
* @throws {Error}
* */
HTMLCanvasElement.prototype.captureStream = function(opt_framerate) {};
/**
* @see https://html.spec.whatwg.org/multipage/canvas.html#dom-canvas-transfercontroltooffscreen
* @return {!OffscreenCanvas}
* @throws {Error}
* */
HTMLCanvasElement.prototype.transferControlToOffscreen = function() {};
/**
* @interface
* @extends {MediaStreamTrack}
* @see https://w3c.github.io/mediacapture-fromelement/#the-canvascapturemediastreamtrack
*/
function CanvasCaptureMediaStreamTrack() {}
/**
* The canvas element that this media stream captures.
* @type {!HTMLCanvasElement}
*/
CanvasCaptureMediaStreamTrack.prototype.canvas;
/**
* Allows applications to manually request that a frame from the canvas be
* captured and rendered into the track.
* @return {undefined}
*/
CanvasCaptureMediaStreamTrack.prototype.requestFrame = function() {};
/**
* @see https://html.spec.whatwg.org/multipage/canvas.html#the-offscreencanvas-interface
* @implements {EventTarget}
* @implements {Transferable}
* @param {number} width
* @param {number} height
* @nosideeffects
* @constructor
*/
function OffscreenCanvas(width, height) {}
/** @override */
OffscreenCanvas.prototype.addEventListener = function(
type, listener, opt_options) {};
/** @override */
OffscreenCanvas.prototype.removeEventListener = function(
type, listener, opt_options) {};
/** @override */
OffscreenCanvas.prototype.dispatchEvent = function(evt) {};
/** @type {number} */
OffscreenCanvas.prototype.width;
/** @type {number} */
OffscreenCanvas.prototype.height;
/**
* @param {string} contextId
* @param {!Object=} opt_options
* @modifies {this}
* @return {!Object}
*/
OffscreenCanvas.prototype.getContext = function(contextId, opt_options) {};
/**
* @return {!ImageBitmap}
*/
OffscreenCanvas.prototype.transferToImageBitmap = function() {};
/**
* @param {{type: (string|undefined), quality: (number|undefined)}=} opt_options
* @return {!Promise<!Blob>}
*/
OffscreenCanvas.prototype.convertToBlob = function(opt_options) {};
// TODO(tjgq): Find a way to add SVGImageElement to this typedef without making
// svg.js part of core.
/**
* @typedef {HTMLImageElement|HTMLVideoElement|HTMLCanvasElement|ImageBitmap|
* OffscreenCanvas}
*/
var CanvasImageSource;
/**
* @interface
* @see https://www.w3.org/TR/2dcontext/#canvaspathmethods
*/
function CanvasPathMethods() {}
/**
* @return {undefined}
*/
CanvasPathMethods.prototype.closePath = function() {};
/**
* @param {number} x
* @param {number} y
* @return {undefined}
*/
CanvasPathMethods.prototype.moveTo = function(x, y) {};
/**
* @param {number} x
* @param {number} y
* @return {undefined}
*/
CanvasPathMethods.prototype.lineTo = function(x, y) {};
/**
* @param {number} cpx
* @param {number} cpy
* @param {number} x
* @param {number} y
* @return {undefined}
*/
CanvasPathMethods.prototype.quadraticCurveTo = function(cpx, cpy, x, y) {};
/**
* @param {number} cp1x
* @param {number} cp1y
* @param {number} cp2x
* @param {number} cp2y
* @param {number} x
* @param {number} y
* @return {undefined}
*/
CanvasPathMethods.prototype.bezierCurveTo = function(
cp1x, cp1y, cp2x, cp2y, x, y) {};
/**
* @param {number} x1
* @param {number} y1
* @param {number} x2
* @param {number} y2
* @param {number} radius
* @return {undefined}
*/
CanvasPathMethods.prototype.arcTo = function(x1, y1, x2, y2, radius) {};
/**
* @param {number} x
* @param {number} y
* @param {number} w
* @param {number} h
* @return {undefined}
*/
CanvasPathMethods.prototype.rect = function(x, y, w, h) {};
/**
* @param {number} x
* @param {number} y
* @param {number} radius
* @param {number} startAngle
* @param {number} endAngle
* @param {boolean=} opt_anticlockwise
* @return {undefined}
*/
CanvasPathMethods.prototype.arc = function(
x, y, radius, startAngle, endAngle, opt_anticlockwise) {};
/**
* @constructor
* @param {!Path2D|string=} arg
* @implements {CanvasPathMethods}
* @see https://html.spec.whatwg.org/multipage/scripting.html#path2d-objects
*/
function Path2D(arg) {}
/**
* @return {undefined}
* @override
*/
Path2D.prototype.closePath = function() {};
/**
* @param {number} x
* @param {number} y
* @return {undefined}
* @override
*/
Path2D.prototype.moveTo = function(x, y) {};
/**
* @param {number} x
* @param {number} y
* @return {undefined}
* @override
*/
Path2D.prototype.lineTo = function(x, y) {};
/**
* @param {number} cpx
* @param {number} cpy
* @param {number} x
* @param {number} y
* @return {undefined}
* @override
*/
Path2D.prototype.quadraticCurveTo = function(cpx, cpy, x, y) {};
/**
* @param {number} cp1x
* @param {number} cp1y
* @param {number} cp2x
* @param {number} cp2y
* @param {number} x
* @param {number} y
* @return {undefined}
* @override
*/
Path2D.prototype.bezierCurveTo = function(
cp1x, cp1y, cp2x, cp2y, x, y) {};
/**
* @param {number} x1
* @param {number} y1
* @param {number} x2
* @param {number} y2
* @param {number} radius
* @return {undefined}
* @override
*/
Path2D.prototype.arcTo = function(x1, y1, x2, y2, radius) {};
/**
* @param {number} x
* @param {number} y
* @param {number} w
* @param {number} h
* @return {undefined}
* @override
*/
Path2D.prototype.rect = function(x, y, w, h) {};
/**
* @param {number} x
* @param {number} y
* @param {number} radius
* @param {number} startAngle
* @param {number} endAngle
* @param {boolean=} optAnticlockwise
* @return {undefined}
* @override
*/
Path2D.prototype.arc = function(
x, y, radius, startAngle, endAngle, optAnticlockwise) {};
/**
* @param {Path2D} path
* @return {undefined}
*/
Path2D.prototype.addPath = function(path) {};
/**
* @interface
* @see https://www.w3.org/TR/2dcontext/#canvasdrawingstyles
*/
function CanvasDrawingStyles() {}
/** @type {number} */
CanvasDrawingStyles.prototype.lineWidth;
/** @type {string} */
CanvasDrawingStyles.prototype.lineCap;
/** @type {string} */
CanvasDrawingStyles.prototype.lineJoin;
/** @type {number} */
CanvasDrawingStyles.prototype.miterLimit;
/**
* @param {Array<number>} segments
* @return {undefined}
*/
CanvasDrawingStyles.prototype.setLineDash = function(segments) {};
/**
* @return {!Array<number>}
*/
CanvasDrawingStyles.prototype.getLineDash = function() {};
/** @type {string} */
CanvasDrawingStyles.prototype.font;
/** @type {string} */
CanvasDrawingStyles.prototype.textAlign;
/** @type {string} */
CanvasDrawingStyles.prototype.textBaseline;
// TODO(dramaix): replace this with @record.
/**
* @constructor
* @abstract
* @implements {CanvasDrawingStyles}
* @implements {CanvasPathMethods}
* @see http://www.w3.org/TR/2dcontext/#canvasrenderingcontext2d
*/
function BaseRenderingContext2D() {}
/** @const {!HTMLCanvasElement|!OffscreenCanvas} */
BaseRenderingContext2D.prototype.canvas;
/**
* @return {undefined}
*/
BaseRenderingContext2D.prototype.save = function() {};
/**
* @return {undefined}
*/
BaseRenderingContext2D.prototype.restore = function() {};
/**
* @param {number} x
* @param {number} y
* @return {undefined}
*/
BaseRenderingContext2D.prototype.scale = function(x, y) {};
/**
* @param {number} angle
* @return {undefined}
*/
BaseRenderingContext2D.prototype.rotate = function(angle) {};
/**
* @param {number} x
* @param {number} y
* @return {undefined}
*/
BaseRenderingContext2D.prototype.translate = function(x, y) {};
/**
* @param {number} m11
* @param {number} m12
* @param {number} m21
* @param {number} m22
* @param {number} dx
* @param {number} dy
* @return {undefined}
*/
BaseRenderingContext2D.prototype.transform = function(
m11, m12, m21, m22, dx, dy) {};
/**
* @param {number} m11
* @param {number} m12
* @param {number} m21
* @param {number} m22
* @param {number} dx
* @param {number} dy
* @return {undefined}
*/
BaseRenderingContext2D.prototype.setTransform = function(
m11, m12, m21, m22, dx, dy) {};
/**
* @return {!DOMMatrixReadOnly}
*/
BaseRenderingContext2D.prototype.getTransform = function() {};
/**
* @param {number} x0
* @param {number} y0
* @param {number} x1
* @param {number} y1
* @return {!CanvasGradient}
* @throws {Error}
*/
BaseRenderingContext2D.prototype.createLinearGradient = function(
x0, y0, x1, y1) {};
/**
* @param {number} x0
* @param {number} y0
* @param {number} r0
* @param {number} x1
* @param {number} y1
* @param {number} r1
* @return {!CanvasGradient}
* @throws {Error}
*/
BaseRenderingContext2D.prototype.createRadialGradient = function(
x0, y0, r0, x1, y1, r1) {};
/**
* @param {CanvasImageSource} image
* @param {string} repetition
* @return {?CanvasPattern}
* @throws {Error}
* @see https://html.spec.whatwg.org/multipage/scripting.html#dom-context-2d-createpattern
*/
BaseRenderingContext2D.prototype.createPattern = function(
image, repetition) {};
/**
* @param {number} x
* @param {number} y
* @param {number} w
* @param {number} h
* @return {undefined}
*/
BaseRenderingContext2D.prototype.clearRect = function(x, y, w, h) {};
/**
* @param {number} x
* @param {number} y
* @param {number} w
* @param {number} h
* @return {undefined}
*/
BaseRenderingContext2D.prototype.fillRect = function(x, y, w, h) {};
/**
* @param {number} x
* @param {number} y
* @param {number} w
* @param {number} h
* @return {undefined}
*/
BaseRenderingContext2D.prototype.strokeRect = function(x, y, w, h) {};
/**
* @return {undefined}
*/
BaseRenderingContext2D.prototype.beginPath = function() {};
/**
* @return {undefined}
* @override
*/
BaseRenderingContext2D.prototype.closePath = function() {};
/**
* @param {number} x
* @param {number} y
* @return {undefined}
* @override
*/
BaseRenderingContext2D.prototype.moveTo = function(x, y) {};
/**
* @param {number} x
* @param {number} y
* @return {undefined}
* @override
*/
BaseRenderingContext2D.prototype.lineTo = function(x, y) {};
/**
* @param {number} cpx
* @param {number} cpy
* @param {number} x
* @param {number} y
* @return {undefined}
* @override
*/
BaseRenderingContext2D.prototype.quadraticCurveTo = function(
cpx, cpy, x, y) {};
/**
* @param {number} cp1x
* @param {number} cp1y
* @param {number} cp2x
* @param {number} cp2y
* @param {number} x
* @param {number} y
* @return {undefined}
* @override
*/
BaseRenderingContext2D.prototype.bezierCurveTo = function(
cp1x, cp1y, cp2x, cp2y, x, y) {};
/**
* @param {number} x1
* @param {number} y1
* @param {number} x2
* @param {number} y2
* @param {number} radius
* @return {undefined}
* @override
*/
BaseRenderingContext2D.prototype.arcTo = function(x1, y1, x2, y2, radius) {};
/**
* @param {number} x
* @param {number} y
* @param {number} w
* @param {number} h
* @return {undefined}
* @override
*/
BaseRenderingContext2D.prototype.rect = function(x, y, w, h) {};
/**
* @param {number} x
* @param {number} y
* @param {number} radius
* @param {number} startAngle
* @param {number} endAngle
* @param {boolean=} opt_anticlockwise
* @return {undefined}
* @override
*/
BaseRenderingContext2D.prototype.arc = function(
x, y, radius, startAngle, endAngle, opt_anticlockwise) {};
/**
* @param {number} x
* @param {number} y
* @param {number} radiusX
* @param {number} radiusY
* @param {number} rotation
* @param {number} startAngle
* @param {number} endAngle
* @param {boolean=} opt_anticlockwise
* @return {undefined}
* @see http://developer.mozilla.org/en/docs/Web/API/CanvasRenderingContext2D/ellipse
*/
BaseRenderingContext2D.prototype.ellipse = function(
x, y, radiusX, radiusY, rotation, startAngle, endAngle, opt_anticlockwise) {
};
/**
* @param {Path2D|string=} optFillRuleOrPath
* @param {string=} optFillRule
* @return {undefined}
*/
BaseRenderingContext2D.prototype.fill = function(optFillRuleOrPath, optFillRule) {};
/**
* @param {Path2D=} optStroke
* @return {undefined}
*/
BaseRenderingContext2D.prototype.stroke = function(optStroke) {};
/**
* @param {Element} element
* @return {undefined}
*/
BaseRenderingContext2D.prototype.drawFocusIfNeeded = function(element) {};
/**
* @param {Path2D|string=} optFillRuleOrPath
* @param {string=} optFillRule
* @return {undefined}
*/
BaseRenderingContext2D.prototype.clip = function(optFillRuleOrPath, optFillRule) {};
/**
* @param {number} x
* @param {number} y
* @return {boolean}
* @nosideeffects
* @see http://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/isPointInStroke
*/
BaseRenderingContext2D.prototype.isPointInStroke = function(x, y) {};
/**
* @param {number} x
* @param {number} y
* @param {string=} opt_fillRule
* @return {boolean}
* @nosideeffects
*/
BaseRenderingContext2D.prototype.isPointInPath = function(
x, y, opt_fillRule) {};
/**
* @param {string} text
* @param {number} x
* @param {number} y
* @param {number=} opt_maxWidth
* @return {undefined}
*/
BaseRenderingContext2D.prototype.fillText = function(
text, x, y, opt_maxWidth) {};
/**
* @param {string} text
* @param {number} x
* @param {number} y
* @param {number=} opt_maxWidth
* @return {undefined}
*/
BaseRenderingContext2D.prototype.strokeText = function(
text, x, y, opt_maxWidth) {};
/**
* @param {string} text
* @return {!TextMetrics}
* @nosideeffects
*/
BaseRenderingContext2D.prototype.measureText = function(text) {};
/**
* @param {CanvasImageSource} image
* @param {number} dx Destination x coordinate.
* @param {number} dy Destination y coordinate.
* @param {number=} opt_dw Destination box width. Defaults to the image width.
* @param {number=} opt_dh Destination box height.
* Defaults to the image height.
* @param {number=} opt_sx Source box x coordinate. Used to select a portion of
* the source image to draw. Defaults to 0.
* @param {number=} opt_sy Source box y coordinate. Used to select a portion of
* the source image to draw. Defaults to 0.
* @param {number=} opt_sw Source box width. Used to select a portion of
* the source image to draw. Defaults to the full image width.
* @param {number=} opt_sh Source box height. Used to select a portion of
* the source image to draw. Defaults to the full image height.
* @return {undefined}
*/
BaseRenderingContext2D.prototype.drawImage = function(
image, dx, dy, opt_dw, opt_dh, opt_sx, opt_sy, opt_sw, opt_sh) {};
/**
* @param {number} sw
* @param {number} sh
* @return {!ImageData}
* @throws {Error}
* @nosideeffects
*/
BaseRenderingContext2D.prototype.createImageData = function(sw, sh) {};
/**
* @param {number} sx
* @param {number} sy
* @param {number} sw
* @param {number} sh
* @return {!ImageData}
* @throws {Error}
*/
BaseRenderingContext2D.prototype.getImageData = function(sx, sy, sw, sh) {};
/**
* @param {ImageData} imagedata
* @param {number} dx
* @param {number} dy
* @param {number=} opt_dirtyX
* @param {number=} opt_dirtyY
* @param {number=} opt_dirtyWidth
* @param {number=} opt_dirtyHeight
* @return {undefined}
*/
BaseRenderingContext2D.prototype.putImageData = function(imagedata, dx, dy,
opt_dirtyX, opt_dirtyY, opt_dirtyWidth, opt_dirtyHeight) {};
/**
* Note: WebKit only
* @param {number|string=} opt_a
* @param {number=} opt_b
* @param {number=} opt_c
* @param {number=} opt_d
* @param {number=} opt_e
* @see http://developer.apple.com/library/safari/#documentation/appleapplications/reference/WebKitDOMRef/CanvasRenderingContext2D_idl/Classes/CanvasRenderingContext2D/index.html
* @return {undefined}
* @deprecated
*/
BaseRenderingContext2D.prototype.setFillColor = function(
opt_a, opt_b, opt_c, opt_d, opt_e) {};
/**
* Note: WebKit only
* @param {number|string=} opt_a
* @param {number=} opt_b
* @param {number=} opt_c
* @param {number=} opt_d
* @param {number=} opt_e
* @see http://developer.apple.com/library/safari/#documentation/appleapplications/reference/WebKitDOMRef/CanvasRenderingContext2D_idl/Classes/CanvasRenderingContext2D/index.html
* @return {undefined}
* @deprecated
*/
BaseRenderingContext2D.prototype.setStrokeColor = function(
opt_a, opt_b, opt_c, opt_d, opt_e) {};
/**
* @return {!Array<number>}
* @override
*/
BaseRenderingContext2D.prototype.getLineDash = function() {};
/**
* @param {Array<number>} segments
* @return {undefined}
* @override
*/
BaseRenderingContext2D.prototype.setLineDash = function(segments) {};
/** @type {string} */
BaseRenderingContext2D.prototype.fillColor;
/**
* @type {string|!CanvasGradient|!CanvasPattern}
* @see https://html.spec.whatwg.org/multipage/scripting.html#fill-and-stroke-styles:dom-context-2d-fillstyle
* @implicitCast
*/
BaseRenderingContext2D.prototype.fillStyle;
/** @type {string} */
BaseRenderingContext2D.prototype.font;
/** @type {number} */
BaseRenderingContext2D.prototype.globalAlpha;
/** @type {string} */
BaseRenderingContext2D.prototype.globalCompositeOperation;
/** @type {number} */
BaseRenderingContext2D.prototype.lineWidth;
/** @type {string} */
BaseRenderingContext2D.prototype.lineCap;
/** @type {string} */
BaseRenderingContext2D.prototype.lineJoin;
/** @type {number} */
BaseRenderingContext2D.prototype.miterLimit;
/** @type {number} */
BaseRenderingContext2D.prototype.shadowBlur;
/** @type {string} */
BaseRenderingContext2D.prototype.shadowColor;
/** @type {number} */
BaseRenderingContext2D.prototype.shadowOffsetX;
/** @type {number} */
BaseRenderingContext2D.prototype.shadowOffsetY;
/** @type {boolean} */
BaseRenderingContext2D.prototype.imageSmoothingEnabled;
/**
* @type {string}
* @see https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/imageSmoothingQuality
*/
BaseRenderingContext2D.prototype.imageSmoothingQuality;
/**
* @type {string|!CanvasGradient|!CanvasPattern}
* @see https://html.spec.whatwg.org/multipage/scripting.html#fill-and-stroke-styles:dom-context-2d-strokestyle
* @implicitCast
*/
BaseRenderingContext2D.prototype.strokeStyle;
/** @type {string} */
BaseRenderingContext2D.prototype.strokeColor;
/** @type {string} */
BaseRenderingContext2D.prototype.textAlign;
/** @type {string} */
BaseRenderingContext2D.prototype.textBaseline;
/** @type {number} */
BaseRenderingContext2D.prototype.lineDashOffset;
/**
* @type {string}
* @see https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/direction
*/
BaseRenderingContext2D.prototype.direction;
/**
* @constructor
* @extends {BaseRenderingContext2D}
* @see http://www.w3.org/TR/2dcontext/#canvasrenderingcontext2d
*/
function CanvasRenderingContext2D() {}
/** @const {!HTMLCanvasElement} */
CanvasRenderingContext2D.prototype.canvas;
/**
* @type {string}
* @see https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/filter
*/
CanvasRenderingContext2D.prototype.filter;
/**
* @constructor
* @extends {BaseRenderingContext2D}
* @see http://www.w3.org/TR/2dcontext/#canvasrenderingcontext2d
*/
function OffscreenCanvasRenderingContext2D() {}
/** @const {!OffscreenCanvas} */
OffscreenCanvasRenderingContext2D.prototype.canvas;
/**
* @constructor
*/
function CanvasGradient() {}
/**
* @param {number} offset
* @param {string} color
* @return {undefined}
*/
CanvasGradient.prototype.addColorStop = function(offset, color) {};
/**
* @constructor
*/
function CanvasPattern() {}
/**
* @constructor
*/
function TextMetrics() {}
/** @const {number} */
TextMetrics.prototype.width;
/** @const {number|undefined} */
TextMetrics.prototype.actualBoundingBoxAscent;
/** @const {number|undefined} */
TextMetrics.prototype.actualBoundingBoxDescent;
/** @const {number|undefined} */
TextMetrics.prototype.actualBoundingBoxLeft;
/** @const {number|undefined} */
TextMetrics.prototype.actualBoundingBoxRight;
/**
* @param {!Uint8ClampedArray|number} dataOrWidth In the first form, this is the
* array of pixel data. In the second form, this is the image width.
* @param {number} widthOrHeight In the first form, this is the image width. In
* the second form, this is the image height.
* @param {number=} opt_height In the first form, this is the optional image
* height. The second form omits this argument.
* @see https://html.spec.whatwg.org/multipage/scripting.html#imagedata
* @constructor
*/
function ImageData(dataOrWidth, widthOrHeight, opt_height) {}
/** @const {!Uint8ClampedArray} */
ImageData.prototype.data;
/** @const {number} */
ImageData.prototype.width;
/** @const {number} */
ImageData.prototype.height;
/**
* @see https://www.w3.org/TR/html51/webappapis.html#webappapis-images
* @interface
*/
function ImageBitmap() {}
/**
* @const {number}
*/
ImageBitmap.prototype.width;
/**
* @const {number}
*/
ImageBitmap.prototype.height;
/**
* Releases ImageBitmap's underlying bitmap data.
* @return {undefined}
* @see https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#images-2
*/
ImageBitmap.prototype.close = function() {};
/**
* @typedef {!CanvasImageSource | !Blob | !ImageData}
* @see https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#imagebitmapsource
*/
var ImageBitmapSource;
/**
* @typedef {{
* imageOrientation: (string|undefined),
* premultiplyAlpha: (string|undefined),
* colorSpaceConversion: (string|undefined),
* resizeWidth: (number|undefined),
* resizeHeight: (number|undefined),
* resizeQuality: (string|undefined)
* }}
* @see https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#images-2
*/
var ImageBitmapOptions;
/**
* @param {!ImageBitmapSource} image
* @param {(number|!ImageBitmapOptions)=} sxOrOptions
* @param {number=} sy
* @param {number=} sw
* @param {number=} sh
* @param {!ImageBitmapOptions=} options
* @return {!Promise<!ImageBitmap>}
* @see https://html.spec.whatwg.org/multipage/imagebitmap-and-animations.html#dom-createimagebitmap
* @see https://html.spec.whatwg.org/multipage/webappapis.html#windoworworkerglobalscope-mixin
*/
function createImageBitmap(image, sxOrOptions, sy, sw, sh, options) {}
/**
* @constructor
*/
function ClientInformation() {}
/** @type {boolean} */
ClientInformation.prototype.onLine;
/**
* @param {string} protocol
* @param {string} uri
* @param {string} title
* @return {undefined}
*/
ClientInformation.prototype.registerProtocolHandler = function(
protocol, uri, title) {};
/**
* @param {string} mimeType
* @param {string} uri
* @param {string} title
* @return {undefined}
*/
ClientInformation.prototype.registerContentHandler = function(
mimeType, uri, title) {};
// HTML5 Database objects
/**
* @constructor
*/
function Database() {}
/**
* @type {string}
*/
Database.prototype.version;
/**
* @param {function(!SQLTransaction) : void} callback
* @param {(function(!SQLError) : void)=} opt_errorCallback
* @param {Function=} opt_Callback
* @return {undefined}
*/
Database.prototype.transaction = function(
callback, opt_errorCallback, opt_Callback) {};
/**
* @param {function(!SQLTransaction) : void} callback
* @param {(function(!SQLError) : void)=} opt_errorCallback
* @param {Function=} opt_Callback
* @return {undefined}
*/
Database.prototype.readTransaction = function(
callback, opt_errorCallback, opt_Callback) {};
/**
* @param {string} oldVersion
* @param {string} newVersion
* @param {function(!SQLTransaction) : void} callback
* @param {function(!SQLError) : void} errorCallback
* @param {Function} successCallback
* @return {undefined}
*/
Database.prototype.changeVersion = function(
oldVersion, newVersion, callback, errorCallback, successCallback) {};
/**
* @interface
*/
function DatabaseCallback() {}
/**
* @param {!Database} db
* @return {undefined}
*/
DatabaseCallback.prototype.handleEvent = function(db) {};
/**
* @constructor
*/
function SQLError() {}
/**
* @type {number}
*/
SQLError.prototype.code;
/**
* @type {string}
*/
SQLError.prototype.message;
/**
* @constructor
*/
function SQLTransaction() {}
/**
* @param {string} sqlStatement
* @param {Array<*>=} opt_queryArgs
* @param {SQLStatementCallback=} opt_callback
* @param {(function(!SQLTransaction, !SQLError) : (boolean|void))=}
* opt_errorCallback
* @return {undefined}
*/
SQLTransaction.prototype.executeSql = function(
sqlStatement, opt_queryArgs, opt_callback, opt_errorCallback) {};
/**
* @typedef {(function(!SQLTransaction, !SQLResultSet) : void)}
*/
var SQLStatementCallback;
/**
* @constructor
*/
function SQLResultSet() {}
/**
* @type {number}
*/
SQLResultSet.prototype.insertId;
/**
* @type {number}
*/
SQLResultSet.prototype.rowsAffected;
/**
* @type {!SQLResultSetRowList}
*/
SQLResultSet.prototype.rows;
/**
* @constructor
* @implements {IArrayLike<!Object>}
* @see http://www.w3.org/TR/webdatabase/#sqlresultsetrowlist
*/
function SQLResultSetRowList() {}
/**
* @type {number}
*/
SQLResultSetRowList.prototype.length;
/**
* @param {number} index
* @return {Object}
* @nosideeffects
*/
SQLResultSetRowList.prototype.item = function(index) {};
/**
* @param {string} name
* @param {string} version
* @param {string} description
* @param {number} size
* @param {(DatabaseCallback|function(Database))=} opt_callback
* @return {!Database}
*/
function openDatabase(name, version, description, size, opt_callback) {}
/**
* @param {string} name
* @param {string} version
* @param {string} description
* @param {number} size
* @param {(DatabaseCallback|function(Database))=} opt_callback
* @return {!Database}
*/
Window.prototype.openDatabase =
function(name, version, description, size, opt_callback) {};
/**
* @type {boolean}
* @see https://www.w3.org/TR/html5/embedded-content-0.html#dom-img-complete
*/
HTMLImageElement.prototype.complete;
/**
* @type {number}
* @see https://www.w3.org/TR/html5/embedded-content-0.html#dom-img-naturalwidth
*/
HTMLImageElement.prototype.naturalWidth;
/**
* @type {number}
* @see https://www.w3.org/TR/html5/embedded-content-0.html#dom-img-naturalheight
*/
HTMLImageElement.prototype.naturalHeight;
/**
* @type {string}
* @see http://www.whatwg.org/specs/web-apps/current-work/multipage/embedded-content-1.html#attr-img-crossorigin
*/
HTMLImageElement.prototype.crossOrigin;
/**
* @type {string}
* @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-img-currentsrc
*/
HTMLImageElement.prototype.currentSrc;
/**
* @type {string}
* @see https://html.spec.whatwg.org/multipage/images.html#image-decoding-hint
*/
HTMLImageElement.prototype.decoding;
/**
* @return {!Promise<undefined>}
* @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-img-decode
*/
HTMLImageElement.prototype.decode;
/**
* This is a superposition of the Window and Worker postMessage methods.
* @param {*} message
* @param {(string|!Array<!Transferable>)=} opt_targetOriginOrTransfer
* @param {(string|!Array<!MessagePort>|!Array<!Transferable>)=}
* opt_targetOriginOrPortsOrTransfer
* @return {void}
*/
function postMessage(message, opt_targetOriginOrTransfer,
opt_targetOriginOrPortsOrTransfer) {}
/**
* @param {*} message
* @param {string=} targetOrigin
* @param {(!Array<!Transferable>)=} transfer
* @return {void}
* @see https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
*/
Window.prototype.postMessage = function(message, targetOrigin, transfer) {};
/**
* The postMessage method (as implemented in Opera).
* @param {string} message
*/
Document.prototype.postMessage = function(message) {};
/**
* Document head accessor.
* @see http://www.whatwg.org/specs/web-apps/current-work/multipage/dom.html#the-head-element-0
* @type {HTMLHeadElement}
*/
Document.prototype.head;
/**
* @type {string}
* @see https://html.spec.whatwg.org/multipage/dom.html#current-document-readiness
*/
Document.prototype.readyState;
/**
* @see https://html.spec.whatwg.org/#application-cache-api
* @constructor
* @implements {EventTarget}
*/
function ApplicationCache() {}
/** @override */
ApplicationCache.prototype.addEventListener = function(
type, listener, opt_options) {};
/** @override */
ApplicationCache.prototype.removeEventListener = function(
type, listener, opt_options) {};
/** @override */
ApplicationCache.prototype.dispatchEvent = function(evt) {};
/**
* The object isn't associated with an application cache. This can occur if the
* update process fails and there is no previous cache to revert to, or if there
* is no manifest file.
* @const {number}
*/
ApplicationCache.prototype.UNCACHED;
/**
* The object isn't associated with an application cache. This can occur if the
* update process fails and there is no previous cache to revert to, or if there
* is no manifest file.
* @const {number}
*/
ApplicationCache.UNCACHED;
/**
* The cache is idle.
* @const {number}
*/
ApplicationCache.prototype.IDLE;
/**
* The cache is idle.
* @const {number}
*/
ApplicationCache.IDLE;
/**
* The update has started but the resources are not downloaded yet - for
* example, this can happen when the manifest file is fetched.
* @const {number}
*/
ApplicationCache.prototype.CHECKING;
/**
* The update has started but the resources are not downloaded yet - for
* example, this can happen when the manifest file is fetched.
* @const {number}
*/
ApplicationCache.CHECKING;
/**
* The resources are being downloaded into the cache.
* @const {number}
*/
ApplicationCache.prototype.DOWNLOADING;
/**
* The resources are being downloaded into the cache.
* @const {number}
*/
ApplicationCache.DOWNLOADING;
/**
* Resources have finished downloading and the new cache is ready to be used.
* @const {number}
*/
ApplicationCache.prototype.UPDATEREADY;
/**
* Resources have finished downloading and the new cache is ready to be used.
* @const {number}
*/
ApplicationCache.UPDATEREADY;
/**
* The cache is obsolete.
* @const {number}
*/
ApplicationCache.prototype.OBSOLETE;
/**
* The cache is obsolete.
* @const {number}
*/
ApplicationCache.OBSOLETE;
/**
* The current status of the application cache.
* @type {number}
*/
ApplicationCache.prototype.status;
/**
* Sent when the update process finishes for the first time; that is, the first
* time an application cache is saved.
* @type {?function(!Event): void}
*/
ApplicationCache.prototype.oncached;
/**
* Sent when the cache update process begins.
* @type {?function(!Event): void}
*/
ApplicationCache.prototype.onchecking;
/**
* Sent when the update process begins downloading resources in the manifest
* file.
* @type {?function(!Event): void}
*/
ApplicationCache.prototype.ondownloading;
/**
* Sent when an error occurs.
* @type {?function(!Event): void}
*/
ApplicationCache.prototype.onerror;
/**
* Sent when the update process finishes but the manifest file does not change.
* @type {?function(!Event): void}
*/
ApplicationCache.prototype.onnoupdate;
/**
* Sent when each resource in the manifest file begins to download.
* @type {?function(!Event): void}
*/
ApplicationCache.prototype.onprogress;
/**
* Sent when there is an existing application cache, the update process
* finishes, and there is a new application cache ready for use.
* @type {?function(!Event): void}
*/
ApplicationCache.prototype.onupdateready;
/**
* Replaces the active cache with the latest version.
* @throws {DOMException}
* @return {undefined}
*/
ApplicationCache.prototype.swapCache = function() {};
/**
* Manually triggers the update process.
* @throws {DOMException}
* @return {undefined}
*/
ApplicationCache.prototype.update = function() {};
/** @type {?ApplicationCache} */
var applicationCache;
/** @type {ApplicationCache} */
Window.prototype.applicationCache;
/**
* @see https://developer.mozilla.org/En/DOM/Worker/Functions_available_to_workers
* @param {...!TrustedScriptURL|string} var_args
* @return {undefined}
*/
Window.prototype.importScripts = function(var_args) {};
/**
* Decodes a string of data which has been encoded using base-64 encoding.
*
* @param {string} encodedData
* @return {string}
* @nosideeffects
* @see https://html.spec.whatwg.org/multipage/webappapis.html#dom-atob
*/
function atob(encodedData) {}
/**
* @param {string} stringToEncode
* @return {string}
* @nosideeffects
* @see https://html.spec.whatwg.org/multipage/webappapis.html#dom-btoa
*/
function btoa(stringToEncode) {}
/**
* @see https://developer.mozilla.org/En/DOM/Worker/Functions_available_to_workers
* @param {...!TrustedScriptURL|string} var_args
* @return {undefined}
*/
function importScripts(var_args) {}
/**
* @see http://dev.w3.org/html5/workers/
* @param {!TrustedScriptURL|string} scriptURL
* @param {!WorkerOptions=} opt_options
* @constructor
* @implements {EventTarget}
*/
function Worker(scriptURL, opt_options) {}
/** @override */
Worker.prototype.addEventListener = function(type, listener, opt_options) {};
/** @override */
Worker.prototype.removeEventListener = function(type, listener, opt_options) {};
/** @override */
Worker.prototype.dispatchEvent = function(evt) {};
/**
* Stops the worker process
* @return {undefined}
*/
Worker.prototype.terminate = function() {};
/**
* Posts a message to the worker thread.
* @param {*} message
* @param {Array<!Transferable>=} opt_transfer
* @return {undefined}
*/
Worker.prototype.postMessage = function(message, opt_transfer) {};
/**
* Posts a message to the worker thread.
* @param {*} message
* @param {Array<!Transferable>=} opt_transfer
* @return {undefined}
*/
Worker.prototype.webkitPostMessage = function(message, opt_transfer) {};
/**
* Sent when the worker thread posts a message to its creator.
* @type {?function(!MessageEvent<*>): void}
*/
Worker.prototype.onmessage;
/**
* Sent when the worker thread encounters an error.
* @type {?function(!ErrorEvent): void}
*/
Worker.prototype.onerror;
/**
* @see http://dev.w3.org/html5/workers/
* @record
*/
function WorkerOptions() {}
/**
* Defines a name for the new global environment of the worker, primarily for
* debugging purposes.
* @type {string|undefined}
*/
WorkerOptions.prototype.name;
/**
* 'classic' or 'module'. Default: 'classic'.
* Specifying 'module' ensures the worker environment supports JavaScript
* modules.
* @type {string|undefined}
*/
WorkerOptions.prototype.type;
// WorkerOptions.prototype.credentials is defined in fetchapi.js.
// if type = 'module', it specifies how scriptURL is fetched.
/**
* @see http://dev.w3.org/html5/workers/
* @param {!TrustedScriptURL|string} scriptURL The URL of the script to run in
* the SharedWorker.
* @param {(string|!WorkerOptions)=} options A name that can
* later be used to obtain a reference to the same SharedWorker or a
* WorkerOptions object which can be be used to specify how scriptURL is
* fetched through the credentials option.
* @constructor
* @implements {EventTarget}
*/
function SharedWorker(scriptURL, options) {}
/** @override */
SharedWorker.prototype.addEventListener = function(
type, listener, opt_options) {};
/** @override */
SharedWorker.prototype.removeEventListener = function(
type, listener, opt_options) {};
/** @override */
SharedWorker.prototype.dispatchEvent = function(evt) {};
/**
* @type {!MessagePort}
*/
SharedWorker.prototype.port;
/**
* Called on network errors for loading the initial script.
* @type {?function(!ErrorEvent): void}
*/
SharedWorker.prototype.onerror;
/**
* @see http://dev.w3.org/html5/workers/
* @see http://www.w3.org/TR/url-1/#dom-urlutilsreadonly
* @interface
*/
function WorkerLocation() {}
/** @type {string} */
WorkerLocation.prototype.href;
/** @type {string} */
WorkerLocation.prototype.origin;
/** @type {string} */
WorkerLocation.prototype.protocol;
/** @type {string} */
WorkerLocation.prototype.host;
/** @type {string} */
WorkerLocation.prototype.hostname;
/** @type {string} */
WorkerLocation.prototype.port;
/** @type {string} */
WorkerLocation.prototype.pathname;
/** @type {string} */
WorkerLocation.prototype.search;
/** @type {string} */
WorkerLocation.prototype.hash;
/**
* @see http://dev.w3.org/html5/workers/
* @interface
* @extends {EventTarget}
*/
function WorkerGlobalScope() {}
/** @type {!WorkerGlobalScope} */
WorkerGlobalScope.prototype.self;
/** @type {!WorkerLocation} */
WorkerGlobalScope.prototype.location;
/**
* @const {string}
* @see https://html.spec.whatwg.org/#windoworworkerglobalscope-mixin
*/
WorkerGlobalScope.prototype.origin;
/**
* @const {string}
* Duplicate definition, since we don't model WindowOrWorkerGlobalScope.
* @see https://html.spec.whatwg.org/#windoworworkerglobalscope-mixin
*/
Window.prototype.origin;
/**
* Closes the worker represented by this WorkerGlobalScope.
* @return {undefined}
*/
WorkerGlobalScope.prototype.close = function() {};
/**
* Sent when the worker encounters an error.
* @type {?function(string, string, number, number, !Error): void}
*/
WorkerGlobalScope.prototype.onerror;
/**
* Sent when the worker goes offline.
* @type {?function(!Event): void}
*/
WorkerGlobalScope.prototype.onoffline;
/**
* Sent when the worker goes online.
* @type {?function(!Event): void}
*/
WorkerGlobalScope.prototype.ononline;
/** @type {!WorkerPerformance} */
WorkerGlobalScope.prototype.performance;
/** @type {!WorkerNavigator} */
WorkerGlobalScope.prototype.navigator;
/**
* Worker postMessage method.
* @param {*} message
* @param {(!Array<!Transferable>)=} transfer
* @return {void}
*/
WorkerGlobalScope.prototype.postMessage = function(message, transfer) {};
/**
* @see http://dev.w3.org/html5/workers/
* @interface
* @extends {WorkerGlobalScope}
*/
function DedicatedWorkerGlobalScope() {}
/**
* Posts a message to creator of this worker.
* @param {*} message
* @param {Array<!Transferable>=} opt_transfer
* @return {undefined}
*/
DedicatedWorkerGlobalScope.prototype.postMessage =
function(message, opt_transfer) {};
/**
* Posts a message to creator of this worker.
* @param {*} message
* @param {Array<!Transferable>=} opt_transfer
* @return {undefined}
*/
DedicatedWorkerGlobalScope.prototype.webkitPostMessage =
function(message, opt_transfer) {};
/**
* Sent when the creator posts a message to this worker.
* @type {?function(!MessageEvent<*>): void}
*/
DedicatedWorkerGlobalScope.prototype.onmessage;
/**
* @see http://dev.w3.org/html5/workers/
* @interface
* @extends {WorkerGlobalScope}
*/
function SharedWorkerGlobalScope() {}
/** @type {string} */
SharedWorkerGlobalScope.prototype.name;
/**
* Sent when a connection to this worker is opened.
* @type {?function(!Event)}
*/
SharedWorkerGlobalScope.prototype.onconnect;
/** @type {!Array<string>|undefined} */
HTMLElement.observedAttributes;
/**
* @param {!Document} oldDocument
* @param {!Document} newDocument
*/
HTMLElement.prototype.adoptedCallback = function(oldDocument, newDocument) {};
/**
* @param {!ShadowRootInit} options
* @return {!ShadowRoot}
*/
HTMLElement.prototype.attachShadow = function(options) {};
/**
* @param {string} attributeName
* @param {?string} oldValue
* @param {?string} newValue
* @param {?string} namespace
*/
HTMLElement.prototype.attributeChangedCallback = function(attributeName, oldValue, newValue, namespace) {};
/** @type {function()|undefined} */
HTMLElement.prototype.connectedCallback;
/** @type {Element} */
HTMLElement.prototype.contextMenu;
/** @type {function()|undefined} */
HTMLElement.prototype.disconnectedCallback;
/** @type {boolean} */
HTMLElement.prototype.draggable;
/**
* This is actually a DOMSettableTokenList property. However since that
* interface isn't currently defined and no known browsers implement this
* feature, just define the property for now.
*
* @const {Object}
*/
HTMLElement.prototype.dropzone;
/** @type {boolean} */
HTMLElement.prototype.hidden;
/** @type {boolean} */
HTMLElement.prototype.inert;
/** @type {boolean} */
HTMLElement.prototype.spellcheck;
/**
* @see https://dom.spec.whatwg.org/#dictdef-getrootnodeoptions
* @typedef {{
* composed: boolean
* }}
*/
var GetRootNodeOptions;
/**
* @see https://dom.spec.whatwg.org/#dom-node-getrootnode
* @param {GetRootNodeOptions=} opt_options
* @return {!Node}
*/
Node.prototype.getRootNode = function(opt_options) {};
/**
* @see http://www.w3.org/TR/components-intro/
* @return {!ShadowRoot}
*/
HTMLElement.prototype.createShadowRoot;
/**
* @see http://www.w3.org/TR/components-intro/
* @return {!ShadowRoot}
*/
HTMLElement.prototype.webkitCreateShadowRoot;
/**
* @see http://www.w3.org/TR/shadow-dom/
* @type {ShadowRoot}
*/
HTMLElement.prototype.shadowRoot;
/**
* @see http://www.w3.org/TR/shadow-dom/
* @return {!NodeList<!Node>}
*/
HTMLElement.prototype.getDestinationInsertionPoints = function() {};
/**
* @see http://www.w3.org/TR/components-intro/
* @type {function()}
*/
HTMLElement.prototype.createdCallback;
/**
* @see http://w3c.github.io/webcomponents/explainer/#lifecycle-callbacks
* @type {function()}
*/
HTMLElement.prototype.attachedCallback;
/**
* @see http://w3c.github.io/webcomponents/explainer/#lifecycle-callbacks
* @type {function()}
*/
HTMLElement.prototype.detachedCallback;
/**
* Cryptographic nonce used by Content Security Policy.
* @see https://html.spec.whatwg.org/multipage/dom.html#elements-in-the-dom:noncedelement
* @type {?string}
*/
HTMLElement.prototype.nonce;
/** @type {string} */
HTMLAnchorElement.prototype.download;
/** @type {string} */
HTMLAnchorElement.prototype.hash;
/** @type {string} */
HTMLAnchorElement.prototype.host;
/** @type {string} */
HTMLAnchorElement.prototype.hostname;
/** @type {string} */
HTMLAnchorElement.prototype.pathname;
/**
* The 'ping' attribute is known to be supported in recent versions (as of
* mid-2014) of Chrome, Safari, and Firefox, and is not supported in any
* current version of Internet Explorer.
*
* @type {string}
* @see http://www.whatwg.org/specs/web-apps/current-work/multipage/semantics.html#hyperlink-auditing
*/
HTMLAnchorElement.prototype.ping;
/** @type {string} */
HTMLAnchorElement.prototype.port;
/** @type {string} */
HTMLAnchorElement.prototype.protocol;
/** @type {!DOMTokenList} */
HTMLAnchorElement.prototype.relList;
/** @type {string} */
HTMLAnchorElement.prototype.search;
/** @type {string} */
HTMLAreaElement.prototype.download;
/**
* @type {string}
* @see http://www.whatwg.org/specs/web-apps/current-work/multipage/semantics.html#hyperlink-auditing
*/
HTMLAreaElement.prototype.ping;
/**
* @type {string}
* @implicitCast
* @see http://www.w3.org/TR/html-markup/iframe.html#iframe.attrs.srcdoc
*/
HTMLIFrameElement.prototype.srcdoc;
/**
* @type {?DOMTokenList}
* @see http://www.w3.org/TR/2012/WD-html5-20121025/the-iframe-element.html#attr-iframe-sandbox
*/
HTMLIFrameElement.prototype.sandbox;
/**
* @type {string}
* @see https://html.spec.whatwg.org/multipage/iframe-embed-object.html#attr-iframe-allow
*/
HTMLIFrameElement.prototype.allow;
/**
* @type {Window}
* @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLIFrameElement/contentWindow
*/
HTMLIFrameElement.prototype.contentWindow;
/** @type {string} */
HTMLInputElement.prototype.autocomplete;
/** @type {string} */
HTMLInputElement.prototype.dirname;
/** @type {FileList} */
HTMLInputElement.prototype.files;
/**
* @type {boolean}
* @see https://www.w3.org/TR/html5/forms.html#dom-input-indeterminate
*/
HTMLInputElement.prototype.indeterminate;
/** @type {string} */
HTMLInputElement.prototype.list;
/** @implicitCast @type {string} */
HTMLInputElement.prototype.max;
/** @implicitCast @type {string} */
HTMLInputElement.prototype.min;
/** @type {string} */
HTMLInputElement.prototype.pattern;
/** @type {boolean} */
HTMLInputElement.prototype.multiple;
/** @type {string} */
HTMLInputElement.prototype.placeholder;
/** @type {boolean} */
HTMLInputElement.prototype.required;
/** @implicitCast @type {string} */
HTMLInputElement.prototype.step;
/** @type {Date} */
HTMLInputElement.prototype.valueAsDate;
/** @type {number} */
HTMLInputElement.prototype.valueAsNumber;
/**
* Changes the form control's value by the value given in the step attribute
* multiplied by opt_n.
* @param {number=} opt_n step multiplier. Defaults to 1.
* @return {undefined}
*/
HTMLInputElement.prototype.stepDown = function(opt_n) {};
/**
* Changes the form control's value by the value given in the step attribute
* multiplied by opt_n.
* @param {number=} opt_n step multiplier. Defaults to 1.
* @return {undefined}
*/
HTMLInputElement.prototype.stepUp = function(opt_n) {};
/**
* @constructor
* @extends {HTMLElement}
* @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement
*/
function HTMLMediaElement() {}
/**
* @see https://html.spec.whatwg.org/multipage/media.html#dom-media-network_empty
* @const {number}
*/
HTMLMediaElement.NETWORK_EMPTY;
/**
* @see https://html.spec.whatwg.org/multipage/media.html#dom-media-network_empty
* @const {number}
*/
HTMLMediaElement.prototype.NETWORK_EMPTY;
/**
* @see https://html.spec.whatwg.org/multipage/media.html#dom-media-network_idle
* @const {number}
*/
HTMLMediaElement.NETWORK_IDLE;
/**
* @see https://html.spec.whatwg.org/multipage/media.html#dom-media-network_idle
* @const {number}
*/
HTMLMediaElement.prototype.NETWORK_IDLE;
/**
* @see https://html.spec.whatwg.org/multipage/media.html#dom-media-network_loading
* @const {number}
*/
HTMLMediaElement.NETWORK_LOADING;
/**
* @see https://html.spec.whatwg.org/multipage/media.html#dom-media-network_loading
* @const {number}
*/
HTMLMediaElement.prototype.NETWORK_LOADING;
/**
* @see https://html.spec.whatwg.org/multipage/media.html#dom-media-network_no_source
* @const {number}
*/
HTMLMediaElement.NETWORK_NO_SOURCE;
/**
* @see https://html.spec.whatwg.org/multipage/media.html#dom-media-network_no_source
* @const {number}
*/
HTMLMediaElement.prototype.NETWORK_NO_SOURCE;
/**
* @see https://html.spec.whatwg.org/multipage/media.html#dom-media-have_nothing
* @const {number}
*/
HTMLMediaElement.HAVE_NOTHING;
/**
* @see https://html.spec.whatwg.org/multipage/media.html#dom-media-have_nothing
* @const {number}
*/
HTMLMediaElement.prototype.HAVE_NOTHING;
/**
* @see https://html.spec.whatwg.org/multipage/media.html#dom-media-have_metadata
* @const {number}
*/
HTMLMediaElement.HAVE_METADATA;
/**
* @see https://html.spec.whatwg.org/multipage/media.html#dom-media-have_metadata
* @const {number}
*/
HTMLMediaElement.prototype.HAVE_METADATA;
/**
* @see https://html.spec.whatwg.org/multipage/media.html#dom-media-have_current_data
* @const {number}
*/
HTMLMediaElement.HAVE_CURRENT_DATA;
/**
* @see https://html.spec.whatwg.org/multipage/media.html#dom-media-have_current_data
* @const {number}
*/
HTMLMediaElement.prototype.HAVE_CURRENT_DATA;
/**
* @see https://html.spec.whatwg.org/multipage/media.html#dom-media-have_future_data
* @const {number}
*/
HTMLMediaElement.HAVE_FUTURE_DATA;
/**
* @see https://html.spec.whatwg.org/multipage/media.html#dom-media-have_future_data
* @const {number}
*/
HTMLMediaElement.prototype.HAVE_FUTURE_DATA;
/**
* @see https://html.spec.whatwg.org/multipage/media.html#dom-media-have_enough_data
* @const {number}
*/
HTMLMediaElement.HAVE_ENOUGH_DATA;
/**
* @see https://html.spec.whatwg.org/multipage/media.html#dom-media-have_enough_data
* @const {number}
*/
HTMLMediaElement.prototype.HAVE_ENOUGH_DATA;
/** @type {MediaError} */
HTMLMediaElement.prototype.error;
/** @type {string} @implicitCast */
HTMLMediaElement.prototype.src;
/** @type {string} */
HTMLMediaElement.prototype.currentSrc;
/** @type {number} */
HTMLMediaElement.prototype.networkState;
/** @type {boolean} */
HTMLMediaElement.prototype.autobuffer;
/** @type {!TimeRanges} */
HTMLMediaElement.prototype.buffered;
/** @type {?MediaStream} */
HTMLMediaElement.prototype.srcObject;
/**
* Loads the media element.
* @return {undefined}
*/
HTMLMediaElement.prototype.load = function() {};
/**
* @param {string} type Type of the element in question in question.
* @return {string} Whether it can play the type.
* @nosideeffects
*/
HTMLMediaElement.prototype.canPlayType = function(type) {};
/** Event handlers */
/** @type {?function(Event)} */
HTMLMediaElement.prototype.onabort;
/** @type {?function(!Event)} */
HTMLMediaElement.prototype.oncanplay;
/** @type {?function(!Event)} */
HTMLMediaElement.prototype.oncanplaythrough;
/** @type {?function(!Event)} */
HTMLMediaElement.prototype.ondurationchange;
/** @type {?function(!Event)} */
HTMLMediaElement.prototype.onemptied;
/** @type {?function(!Event)} */
HTMLMediaElement.prototype.onended;
/** @type {?function(Event)} */
HTMLMediaElement.prototype.onerror;
/** @type {?function(!Event)} */
HTMLMediaElement.prototype.onloadeddata;
/** @type {?function(!Event)} */
HTMLMediaElement.prototype.onloadedmetadata;
/** @type {?function(!Event)} */
HTMLMediaElement.prototype.onloadstart;
/** @type {?function(!Event)} */
HTMLMediaElement.prototype.onpause;
/** @type {?function(!Event)} */
HTMLMediaElement.prototype.onplay;
/** @type {?function(!Event)} */
HTMLMediaElement.prototype.onplaying;
/** @type {?function(!Event)} */
HTMLMediaElement.prototype.onprogress;
/** @type {?function(!Event)} */
HTMLMediaElement.prototype.onratechange;
/** @type {?function(!Event)} */
HTMLMediaElement.prototype.onseeked;
/** @type {?function(!Event)} */
HTMLMediaElement.prototype.onseeking;
/** @type {?function(!Event)} */
HTMLMediaElement.prototype.onstalled;
/** @type {?function(!Event)} */
HTMLMediaElement.prototype.onsuspend;
/** @type {?function(!Event)} */
HTMLMediaElement.prototype.ontimeupdate;
/** @type {?function(!Event)} */
HTMLMediaElement.prototype.onvolumechange;
/** @type {?function(!Event)} */
HTMLMediaElement.prototype.onwaiting;
/** @type {?function(Event)} */
HTMLImageElement.prototype.onload;
/** @type {?function(Event)} */
HTMLImageElement.prototype.onerror;
/** @type {string} */
HTMLMediaElement.prototype.preload;
/** @type {number} */
HTMLMediaElement.prototype.readyState;
/** @type {boolean} */
HTMLMediaElement.prototype.seeking;
/**
* @type {string}
* @see https://html.spec.whatwg.org/multipage/media.html#dom-media-crossorigin
*/
HTMLMediaElement.prototype.crossOrigin;
/**
* The current time, in seconds.
* @type {number}
*/
HTMLMediaElement.prototype.currentTime;
/**
* The absolute timeline offset.
* @return {!Date}
*/
HTMLMediaElement.prototype.getStartDate = function() {};
/**
* The length of the media in seconds.
* @type {number}
*/
HTMLMediaElement.prototype.duration;
/** @type {boolean} */
HTMLMediaElement.prototype.paused;
/** @type {number} */
HTMLMediaElement.prototype.defaultPlaybackRate;
/** @type {number} */
HTMLMediaElement.prototype.playbackRate;
/** @type {TimeRanges} */
HTMLMediaElement.prototype.played;
/** @type {TimeRanges} */
HTMLMediaElement.prototype.seekable;
/** @type {boolean} */
HTMLMediaElement.prototype.ended;
/** @type {boolean} */
HTMLMediaElement.prototype.autoplay;
/** @type {boolean} */
HTMLMediaElement.prototype.loop;
/**
* Starts playing the media.
* @return {?Promise<undefined>} This is a *nullable* Promise on purpose unlike
* the HTML5 spec because supported older browsers (incl. Smart TVs) don't
* return a Promise.
*/
HTMLMediaElement.prototype.play = function() {};
/**
* Pauses the media.
* @return {undefined}
*/
HTMLMediaElement.prototype.pause = function() {};
/** @type {boolean} */
HTMLMediaElement.prototype.controls;
/**
* The audio volume, from 0.0 (silent) to 1.0 (loudest).
* @type {number}
*/
HTMLMediaElement.prototype.volume;
/** @type {boolean} */
HTMLMediaElement.prototype.muted;
/**
* @see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#dom-media-addtexttrack
* @param {string} kind Kind of the text track.
* @param {string=} opt_label Label of the text track.
* @param {string=} opt_language Language of the text track.
* @return {!TextTrack} TextTrack object added to the media element.
*/
HTMLMediaElement.prototype.addTextTrack =
function(kind, opt_label, opt_language) {};
/** @type {!TextTrackList} */
HTMLMediaElement.prototype.textTracks;
/**
* The ID of the audio device through which output is being delivered, or an
* empty string if using the default device.
*
* Implemented as a draft spec in Chrome 49+.
*
* @see https://w3c.github.io/mediacapture-output/#htmlmediaelement-extensions
* @type {string}
*/
HTMLMediaElement.prototype.sinkId;
/**
* Sets the audio device through which output should be delivered.
*
* Implemented as a draft spec in Chrome 49+.
*
* @param {string} sinkId The ID of the audio output device, or empty string
* for default device.
*
* @see https://w3c.github.io/mediacapture-output/#htmlmediaelement-extensions
* @return {!Promise<void>}
*/
HTMLMediaElement.prototype.setSinkId = function(sinkId) {};
/**
* Produces a real-time capture of the media that is rendered to the media
* element.
* @return {!MediaStream}
* @see https://w3c.github.io/mediacapture-fromelement/#html-media-element-media-capture-extensions
*/
HTMLMediaElement.prototype.captureStream = function() {};
/**
* The Firefox flavor of captureStream.
* @return {!MediaStream}
* @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/captureStream#Browser_compatibility
*/
HTMLMediaElement.prototype.mozCaptureStream = function() {};
/**
* @constructor
* @extends {HTMLElement}
* @see https://html.spec.whatwg.org/multipage/dom.html#htmlunknownelement
* @see https://html.spec.whatwg.org/multipage/scripting.html#customized-built-in-element-restrictions
* @see https://w3c.github.io/webcomponents/spec/custom/#custom-elements-api
*/
function HTMLUnknownElement() {}
/**
* @see http://www.w3.org/TR/shadow-dom/
* @return {!NodeList<!Node>}
*/
Text.prototype.getDestinationInsertionPoints = function() {};
/**
* @see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#texttracklist
* @constructor
* @implements {EventTarget}
* @implements {IArrayLike<!TextTrack>}
*/
function TextTrackList() {}
/** @type {number} */
TextTrackList.prototype.length;
/**
* @param {string} id
* @return {TextTrack}
*/
TextTrackList.prototype.getTrackById = function(id) {};
/** @override */
TextTrackList.prototype.addEventListener = function(
type, listener, opt_useCapture) {};
/** @override */
TextTrackList.prototype.dispatchEvent = function(evt) {};
/** @override */
TextTrackList.prototype.removeEventListener = function(
type, listener, opt_options) {};
/**
* @see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#texttrack
* @constructor
* @implements {EventTarget}
*/
function TextTrack() {}
/**
* @param {TextTrackCue} cue
* @return {undefined}
*/
TextTrack.prototype.addCue = function(cue) {};
/**
* @param {TextTrackCue} cue
* @return {undefined}
*/
TextTrack.prototype.removeCue = function(cue) {};
/**
* @const {TextTrackCueList}
*/
TextTrack.prototype.activeCues;
/**
* @const {TextTrackCueList}
*/
TextTrack.prototype.cues;
/**
* @type {string}
*/
TextTrack.prototype.mode;
/** @override */
TextTrack.prototype.addEventListener = function(
type, listener, opt_useCapture) {};
/** @override */
TextTrack.prototype.dispatchEvent = function(evt) {};
/** @override */
TextTrack.prototype.removeEventListener = function(
type, listener, opt_options) {};
/**
* @see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#texttrackcuelist
* @constructor
* @implements {IArrayLike<!TextTrackCue>}
*/
function TextTrackCueList() {}
/** @const {number} */
TextTrackCueList.prototype.length;
/**
* @param {string} id
* @return {TextTrackCue}
*/
TextTrackCueList.prototype.getCueById = function(id) {};
/**
* @see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#texttrackcue
* @constructor
* @param {number} startTime
* @param {number} endTime
* @param {string} text
*/
function TextTrackCue(startTime, endTime, text) {}
/** @type {string} */
TextTrackCue.prototype.id;
/** @type {number} */
TextTrackCue.prototype.startTime;
/** @type {number} */
TextTrackCue.prototype.endTime;
/** @type {string} */
TextTrackCue.prototype.text;
/**
* @see https://w3c.github.io/webvtt/#vttregion
* @constructor
*/
function VTTRegion() {}
/** @type {string} */
VTTRegion.prototype.id;
/** @type {number} */
VTTRegion.prototype.width;
/** @type {number} */
VTTRegion.prototype.lines;
/** @type {number} */
VTTRegion.prototype.regionAnchorX;
/** @type {number} */
VTTRegion.prototype.regionAnchorY;
/** @type {number} */
VTTRegion.prototype.viewportAnchorX;
/** @type {number} */
VTTRegion.prototype.viewportAnchorY;
/**
* @see https://w3c.github.io/webvtt/#enumdef-scrollsetting
* @type {string}
*/
VTTRegion.prototype.scroll;
/**
* @see http://dev.w3.org/html5/webvtt/#the-vttcue-interface
* @constructor
* @extends {TextTrackCue}
* @param {number} startTime
* @param {number} endTime
* @param {string} text
*/
function VTTCue(startTime, endTime, text) {}
/** @type {?VTTRegion} */
VTTCue.prototype.region;
/**
* @see https://w3c.github.io/webvtt/#enumdef-directionsetting
* @type {string}
*/
VTTCue.prototype.vertical;
/** @type {boolean} */
VTTCue.prototype.snapToLines;
/** @type {(number|string)} */
VTTCue.prototype.line;
/**
* @see https://w3c.github.io/webvtt/#enumdef-linealignsetting
* @type {string}
*/
VTTCue.prototype.lineAlign;
/** @type {(number|string)} */
VTTCue.prototype.position;
/**
* @see https://w3c.github.io/webvtt/#enumdef-positionalignsetting
* @type {string}
*/
VTTCue.prototype.positionAlign;
/** @type {number} */
VTTCue.prototype.size;
/**
* @see https://w3c.github.io/webvtt/#enumdef-alignsetting
* @type {string}
*/
VTTCue.prototype.align;
/** @type {string} */
VTTCue.prototype.text;
/** @return {!DocumentFragment} */
VTTCue.prototype.getCueAsHTML = function() {};
/**
* @constructor
* @extends {HTMLMediaElement}
*/
function HTMLAudioElement() {}
/**
* @constructor
* @extends {HTMLMediaElement}
* The webkit-prefixed attributes are defined in
* https://cs.chromium.org/chromium/src/third_party/WebKit/Source/core/html/media/HTMLMediaElement.idl
*/
function HTMLVideoElement() {}
/**
* Starts displaying the video in full screen mode.
* @return {undefined}
*/
HTMLVideoElement.prototype.webkitEnterFullscreen = function() {};
/**
* Starts displaying the video in full screen mode.
* @return {undefined}
*/
HTMLVideoElement.prototype.webkitEnterFullScreen = function() {};
/**
* Stops displaying the video in full screen mode.
* @return {undefined}
*/
HTMLVideoElement.prototype.webkitExitFullscreen = function() {};
/**
* Stops displaying the video in full screen mode.
* @return {undefined}
*/
HTMLVideoElement.prototype.webkitExitFullScreen = function() {};
/** @type {number} */
HTMLVideoElement.prototype.width;
/** @type {number} */
HTMLVideoElement.prototype.height;
/** @type {number} */
HTMLVideoElement.prototype.videoWidth;
/** @type {number} */
HTMLVideoElement.prototype.videoHeight;
/** @type {string} */
HTMLVideoElement.prototype.poster;
/** @type {boolean} */
HTMLVideoElement.prototype.webkitSupportsFullscreen;
/** @type {boolean} */
HTMLVideoElement.prototype.webkitDisplayingFullscreen;
/** @type {number} */
HTMLVideoElement.prototype.webkitDecodedFrameCount;
/** @type {number} */
HTMLVideoElement.prototype.webkitDroppedFrameCount;
/**
* @typedef {{
* creationTime: number,
* totalVideoFrames: number,
* droppedVideoFrames: number,
* corruptedVideoFrames: number,
* totalFrameDelay: number,
* displayCompositedVideoFrames: (number|undefined)
* }}
*/
var VideoPlaybackQuality;
/**
* @see https://w3c.github.io/media-source/#htmlvideoelement-extensions
* @return {!VideoPlaybackQuality} Stats about the current playback.
*/
HTMLVideoElement.prototype.getVideoPlaybackQuality = function() {};
/**
* The metadata provided by the callback given to
* HTMLVideoElement.requestVideoFrameCallback().
*
* See https://wicg.github.io/video-rvfc/#video-frame-metadata
*
* @record
*/
function VideoFrameMetadata() {};
/**
* The time at which the user agent submitted the frame for composition.
* @const {number}
*/
VideoFrameMetadata.prototype.presentationTime;
/**
* The time at which the user agent expects the frame to be visible.
* @const {number}
*/
VideoFrameMetadata.prototype.expectedDisplayTime;
/**
* The width of the video frame, in media pixels.
* @const {number}
*/
VideoFrameMetadata.prototype.width;
/**
* The height of the video frame, in media pixels.
* @const {number}
*/
VideoFrameMetadata.prototype.height;
/**
* The media presentation timestamp (PTS) in seconds of the frame presented
* (e.g. its timestamp on the video.currentTime timeline).
* @const {number}
*/
VideoFrameMetadata.prototype.mediaTime;
/**
* A count of the number of frames submitted for composition.
* @const {number}
*/
VideoFrameMetadata.prototype.presentedFrames;
/**
* The elapsed duration in seconds from submission of the encoded packet with
* the same presentation timestamp (PTS) as this frame (e.g. same as the
* mediaTime) to the decoder until the decoded frame was ready for presentation.
* @const {number|undefined}
*/
VideoFrameMetadata.prototype.processingDuration;
/**
* For video frames coming from either a local or remote source, this is the
* time at which the frame was captured by the camera.
* @const {number|undefined}
*/
VideoFrameMetadata.prototype.captureTime;
/**
* For video frames coming from a remote source, this is the time the encoded
* frame was received by the platform, i.e., the time at which the last packet
* belonging to this frame was received over the network.
* @const {number|undefined}
*/
VideoFrameMetadata.prototype.receiveTime;
/**
* The RTP timestamp associated with this video frame.
* @const {number|undefined}
*/
VideoFrameMetadata.prototype.rtpTimestamp;
/**
* @typedef {function(number, ?VideoFrameMetadata): undefined}
* @see https://wicg.github.io/video-rvfc/#dom-htmlvideoelement-requestvideoframecallback
*/
var VideoFrameRequestCallback;
/**
* Registers a callback to be fired the next time a frame is presented to the
* compositor.
* @param {!VideoFrameRequestCallback} callback
* @return {number}
*/
HTMLVideoElement.prototype.requestVideoFrameCallback = function(callback) {};
/**
* Cancels an existing video frame request callback given its handle.
* @param {number} handle
* @return {undefined}
*/
HTMLVideoElement.prototype.cancelVideoFrameCallback = function(handle) {};
/**
* @constructor
* @see https://html.spec.whatwg.org/multipage/media.html#error-codes
*/
function MediaError() {}
/** @type {number} */
MediaError.prototype.code;
/** @type {string} */
MediaError.prototype.message;
/**
* The fetching process for the media resource was aborted by the user agent at
* the user's request.
* @const {number}
*/
MediaError.MEDIA_ERR_ABORTED;
/**
* A network error of some description caused the user agent to stop fetching
* the media resource, after the resource was established to be usable.
* @const {number}
*/
MediaError.MEDIA_ERR_NETWORK;
/**
* An error of some description occurred while decoding the media resource,
* after the resource was established to be usable.
* @const {number}
*/
MediaError.MEDIA_ERR_DECODE;
/**
* The media resource indicated by the src attribute was not suitable.
* @const {number}
*/
MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED;
// HTML5 MessageChannel
/**
* @see http://dev.w3.org/html5/spec/comms.html#messagechannel
* @constructor
*/
function MessageChannel() {}
/**
* Returns the first port.
* @type {!MessagePort}
*/
MessageChannel.prototype.port1;
/**
* Returns the second port.
* @type {!MessagePort}
*/
MessageChannel.prototype.port2;
// HTML5 MessagePort
/**
* @see http://dev.w3.org/html5/spec/comms.html#messageport
* @constructor
* @implements {EventTarget}
* @implements {Transferable}
*/
function MessagePort() {}
/** @override */
MessagePort.prototype.addEventListener = function(type, listener, opt_options) {
};
/** @override */
MessagePort.prototype.removeEventListener = function(
type, listener, opt_options) {};
/** @override */
MessagePort.prototype.dispatchEvent = function(evt) {};
/**
* Posts a message through the channel, optionally with the given
* Array of Transferables.
* @param {*} message
* @param {Array<!Transferable>=} opt_transfer
* @return {undefined}
*/
MessagePort.prototype.postMessage = function(message, opt_transfer) {
};
/**
* Begins dispatching messages received on the port.
* @return {undefined}
*/
MessagePort.prototype.start = function() {};
/**
* Disconnects the port, so that it is no longer active.
* @return {undefined}
*/
MessagePort.prototype.close = function() {};
/**
* TODO(blickly): Change this to MessageEvent<*> and add casts as needed
* @type {?function(!MessageEvent<?>): void}
*/
MessagePort.prototype.onmessage;
// HTML5 MessageEvent class
/**
* @typedef {Window|MessagePort|ServiceWorker}
* @see https://html.spec.whatwg.org/multipage/comms.html#messageeventsource
*/
var MessageEventSource;
/**
* @record
* @extends {EventInit}
* @template T
* @see https://html.spec.whatwg.org/multipage/comms.html#messageeventinit
*/
function MessageEventInit() {}
/** @type {T|undefined} */
MessageEventInit.prototype.data;
/** @type {(string|undefined)} */
MessageEventInit.prototype.origin;
/** @type {(string|undefined)} */
MessageEventInit.prototype.lastEventId;
/** @type {(?MessageEventSource|undefined)} */
MessageEventInit.prototype.source;
/** @type {(!Array<MessagePort>|undefined)} */
MessageEventInit.prototype.ports;
/**
* @see https://html.spec.whatwg.org/multipage/comms.html#messageevent
* @constructor
* @extends {Event}
* @param {string} type
* @param {MessageEventInit<T>=} opt_eventInitDict
* @template T
*/
function MessageEvent(type, opt_eventInitDict) {}
/**
* The data payload of the message.
* @type {T}
*/
MessageEvent.prototype.data;
/**
* The origin of the message, for server-sent events and cross-document
* messaging.
* @type {string}
*/
MessageEvent.prototype.origin;
/**
* The last event ID, for server-sent events.
* @type {string}
*/
MessageEvent.prototype.lastEventId;
/**
* The window that dispatched the event.
* @type {Window}
*/
MessageEvent.prototype.source;
/**
* The Array of MessagePorts sent with the message, for cross-document
* messaging and channel messaging.
* @type {!Array<MessagePort>}
*/
MessageEvent.prototype.ports;
/**
* Initializes the event in a manner analogous to the similarly-named methods in
* the DOM Events interfaces.
* @param {string} typeArg
* @param {boolean=} canBubbleArg
* @param {boolean=} cancelableArg
* @param {T=} dataArg
* @param {string=} originArg
* @param {string=} lastEventIdArg
* @param {?MessageEventSource=} sourceArg
* @param {!Array<MessagePort>=} portsArg
* @return {undefined}
*/
MessageEvent.prototype.initMessageEvent = function(typeArg, canBubbleArg,
cancelableArg, dataArg, originArg, lastEventIdArg, sourceArg, portsArg) {};
/**
* Initializes the event in a manner analogous to the similarly-named methods in
* the DOM Events interfaces.
* @param {string} namespaceURI
* @param {string=} typeArg
* @param {boolean=} canBubbleArg
* @param {boolean=} cancelableArg
* @param {T=} dataArg
* @param {string=} originArg
* @param {string=} lastEventIdArg
* @param {?MessageEventSource=} sourceArg
* @param {!Array<MessagePort>=} portsArg
* @return {undefined}
*/
MessageEvent.prototype.initMessageEventNS = function(namespaceURI, typeArg,
canBubbleArg, cancelableArg, dataArg, originArg, lastEventIdArg, sourceArg,
portsArg) {};
/**
* @record
* @extends {EventInit}
* @see https://html.spec.whatwg.org/multipage/web-sockets.html#the-closeevent-interface
*/
function CloseEventInit() {}
/**
* @type {undefined|boolean}
*/
CloseEventInit.prototype.wasClean;
/**
* @type {undefined|number}
*/
CloseEventInit.prototype.code;
/**
* @type {undefined|string}
*/
CloseEventInit.prototype.reason;
/**
* @constructor
* @extends {Event}
* @param {string} type
* @param {!CloseEventInit=} opt_init
*/
var CloseEvent = function(type, opt_init) {};
/**
* @type {boolean}
*/
CloseEvent.prototype.wasClean;
/**
* @type {number}
*/
CloseEvent.prototype.code;
/**
* @type {string}
*/
CloseEvent.prototype.reason;
/**
* HTML5 BroadcastChannel class.
* @param {string} channelName
* @see https://developer.mozilla.org/en-US/docs/Web/API/BroadcastChannel
* @see https://html.spec.whatwg.org/multipage/comms.html#dom-broadcastchannel
* @implements {EventTarget}
* @constructor
*/
function BroadcastChannel(channelName) {}
/**
* Sends the message, of any type of object, to each BroadcastChannel object
* listening to the same channel.
* @param {*} message
*/
BroadcastChannel.prototype.postMessage = function(message) {};
/**
* Closes the channel object, indicating it won't get any new messages, and
* allowing it to be, eventually, garbage collected.
* @return {void}
*/
BroadcastChannel.prototype.close = function() {};
/** @override */
BroadcastChannel.prototype.addEventListener = function(
type, listener, opt_options) {};
/** @override */
BroadcastChannel.prototype.dispatchEvent = function(evt) {};
/** @override */
BroadcastChannel.prototype.removeEventListener = function(
type, listener, opt_options) {};
/**
* An EventHandler property that specifies the function to execute when a
* message event is fired on this object.
* @type {?function(!MessageEvent<*>)}
*/
BroadcastChannel.prototype.onmessage;
/**
* The name of the channel.
* @type {string}
*/
BroadcastChannel.prototype.name;
/**
* HTML5 DataTransfer class.
*
* @see http://www.w3.org/TR/2011/WD-html5-20110113/dnd.html
* @see http://www.whatwg.org/specs/web-apps/current-work/multipage/dnd.html
* @see http://developers.whatwg.org/dnd.html#datatransferitem
* @constructor
*/
function DataTransfer() {}
/** @type {string} */
DataTransfer.prototype.dropEffect;
/** @type {string} */
DataTransfer.prototype.effectAllowed;
/** @type {!Array<string>} */
DataTransfer.prototype.types;
/** @type {!FileList} */
DataTransfer.prototype.files;
/**
* @param {string=} opt_format Format for which to remove data.
* @return {undefined}
*/
DataTransfer.prototype.clearData = function(opt_format) {};
/**
* @param {string} format Format for which to set data.
* @param {string} data Data to add.
* @return {boolean}
*/
DataTransfer.prototype.setData = function(format, data) {};
/**
* @param {string} format Format for which to set data.
* @return {string} Data for the given format.
*/
DataTransfer.prototype.getData = function(format) { return ''; };
/**
* @param {HTMLElement} img The image to use when dragging.
* @param {number} x Horizontal position of the cursor.
* @param {number} y Vertical position of the cursor.
* @return {undefined}
*/
DataTransfer.prototype.setDragImage = function(img, x, y) {};
/**
* @param {HTMLElement} elem Element to receive drag result events.
* @return {undefined}
*/
DataTransfer.prototype.addElement = function(elem) {};
/**
* Addition for accessing clipboard file data that are part of the proposed
* HTML5 spec.
* @type {DataTransfer}
*/
MouseEvent.prototype.dataTransfer;
/**
* @record
* @extends {MouseEventInit}
* @see https://w3c.github.io/uievents/#idl-wheeleventinit
*/
function WheelEventInit() {}
/** @type {undefined|number} */
WheelEventInit.prototype.deltaX;
/** @type {undefined|number} */
WheelEventInit.prototype.deltaY;
/** @type {undefined|number} */
WheelEventInit.prototype.deltaZ;
/** @type {undefined|number} */
WheelEventInit.prototype.deltaMode;
/**
* @param {string} type
* @param {WheelEventInit=} opt_eventInitDict
* @see http://www.w3.org/TR/DOM-Level-3-Events/#interface-WheelEvent
* @constructor
* @extends {MouseEvent}
*/
function WheelEvent(type, opt_eventInitDict) {}
/** @const {number} */
WheelEvent.DOM_DELTA_PIXEL;
/** @const {number} */
WheelEvent.DOM_DELTA_LINE;
/** @const {number} */
WheelEvent.DOM_DELTA_PAGE;
/** @const {number} */
WheelEvent.prototype.deltaX;
/** @const {number} */
WheelEvent.prototype.deltaY;
/** @const {number} */
WheelEvent.prototype.deltaZ;
/** @const {number} */
WheelEvent.prototype.deltaMode;
/**
* HTML5 DataTransferItem class.
*
* @see http://www.w3.org/TR/2011/WD-html5-20110113/dnd.html
* @see http://www.whatwg.org/specs/web-apps/current-work/multipage/dnd.html
* @see http://developers.whatwg.org/dnd.html#datatransferitem
* @constructor
*/
function DataTransferItem() {}
/** @type {string} */
DataTransferItem.prototype.kind;
/** @type {string} */
DataTransferItem.prototype.type;
/**
* @param {function(string)} callback
* @return {undefined}
*/
DataTransferItem.prototype.getAsString = function(callback) {};
/**
* @return {?File} The file corresponding to this item, or null.
* @nosideeffects
*/
DataTransferItem.prototype.getAsFile = function() { return null; };
/**
* HTML5 DataTransferItemList class. There are some discrepancies in the docs
* on the whatwg.org site. When in doubt, these prototypes match what is
* implemented as of Chrome 30.
*
* @see http://www.w3.org/TR/2011/WD-html5-20110113/dnd.html
* @see http://www.whatwg.org/specs/web-apps/current-work/multipage/dnd.html
* @see http://developers.whatwg.org/dnd.html#datatransferitem
* @constructor
* @implements {IArrayLike<!DataTransferItem>}
*/
function DataTransferItemList() {}
/** @type {number} */
DataTransferItemList.prototype.length;
/**
* @param {number} i File to return from the list.
* @return {DataTransferItem} The ith DataTransferItem in the list, or null.
* @nosideeffects
*/
DataTransferItemList.prototype.item = function(i) { return null; };
/**
* Adds an item to the list.
* @param {string|!File} data Data for the item being added.
* @param {string=} opt_type Mime type of the item being added. MUST be present
* if the {@code data} parameter is a string.
* @return {DataTransferItem}
*/
DataTransferItemList.prototype.add = function(data, opt_type) {};
/**
* Removes an item from the list.
* @param {number} i File to remove from the list.
* @return {undefined}
*/
DataTransferItemList.prototype.remove = function(i) {};
/**
* Removes all items from the list.
* @return {undefined}
*/
DataTransferItemList.prototype.clear = function() {};
/** @type {!DataTransferItemList} */
DataTransfer.prototype.items;
/**
* @record
* @extends {MouseEventInit}
* @see http://w3c.github.io/html/editing.html#dictdef-drageventinit
*/
function DragEventInit() {}
/** @type {undefined|?DataTransfer} */
DragEventInit.prototype.dataTransfer;
/**
* @see http://www.whatwg.org/specs/web-apps/current-work/multipage/dnd.html#the-dragevent-interface
* @constructor
* @extends {MouseEvent}
* @param {string} type
* @param {DragEventInit=} opt_eventInitDict
*/
function DragEvent(type, opt_eventInitDict) {}
/** @type {DataTransfer} */
DragEvent.prototype.dataTransfer;
/**
* @record
* @extends {EventInit}
* @see https://www.w3.org/TR/progress-events/#progresseventinit
*/
function ProgressEventInit() {}
/** @type {undefined|boolean} */
ProgressEventInit.prototype.lengthComputable;
/** @type {undefined|number} */
ProgressEventInit.prototype.loaded;
/** @type {undefined|number} */
ProgressEventInit.prototype.total;
/**
* @constructor
* @template TARGET
* @param {string} type
* @param {ProgressEventInit=} opt_progressEventInitDict
* @extends {Event}
* @see https://developer.mozilla.org/en-US/docs/Web/API/ProgressEvent
*/
function ProgressEvent(type, opt_progressEventInitDict) {}
/**
* @override
* @type {TARGET}
*/
ProgressEvent.prototype.target;
/** @type {number} */
ProgressEvent.prototype.total;
/** @type {number} */
ProgressEvent.prototype.loaded;
/** @type {boolean} */
ProgressEvent.prototype.lengthComputable;
/**
* @constructor
*/
function TimeRanges() {}
/** @type {number} */
TimeRanges.prototype.length;
/**
* @param {number} index The index.
* @return {number} The start time of the range at index.
* @throws {DOMException}
*/
TimeRanges.prototype.start = function(index) { return 0; };
/**
* @param {number} index The index.
* @return {number} The end time of the range at index.
* @throws {DOMException}
*/
TimeRanges.prototype.end = function(index) { return 0; };
// HTML5 Web Socket class
/**
* @see https://html.spec.whatwg.org/multipage/web-sockets.html
* @constructor
* @param {string} url
* @param {(string|!Array<string>)=} opt_protocol
* @implements {EventTarget}
*/
function WebSocket(url, opt_protocol) {}
/**
* The connection has not yet been established.
* @const {number}
*/
WebSocket.CONNECTING;
/**
* The connection has not yet been established.
* @const {number}
*/
WebSocket.prototype.CONNECTING;
/**
* The WebSocket connection is established and communication is possible.
* @const {number}
*/
WebSocket.OPEN;
/**
* The WebSocket connection is established and communication is possible.
* @const {number}
*/
WebSocket.prototype.OPEN;
/**
* The connection is going through the closing handshake, or the close() method has been invoked.
* @const {number}
*/
WebSocket.CLOSING;
/**
* The connection is going through the closing handshake, or the close() method has been invoked.
* @const {number}
*/
WebSocket.prototype.CLOSING;
/**
* The connection has been closed or could not be opened.
* @const {number}
*/
WebSocket.CLOSED;
/**
* The connection has been closed or could not be opened.
* @const {number}
*/
WebSocket.prototype.CLOSED;
/** @override */
WebSocket.prototype.addEventListener = function(type, listener, opt_options) {};
/** @override */
WebSocket.prototype.removeEventListener = function(
type, listener, opt_options) {};
/** @override */
WebSocket.prototype.dispatchEvent = function(evt) {};
/**
* Returns the URL value that was passed to the constructor.
* @type {string}
*/
WebSocket.prototype.url;
/**
* Represents the state of the connection.
* @type {number}
*/
WebSocket.prototype.readyState;
/**
* Returns the number of bytes that have been queued but not yet sent.
* @type {number}
*/
WebSocket.prototype.bufferedAmount;
/**
* An event handler called on error event.
* @type {?function(!Event): void}
*/
WebSocket.prototype.onerror;
/**
* An event handler called on open event.
* @type {?function(!Event): void}
*/
WebSocket.prototype.onopen;
/**
* An event handler called on message event.
* @type {?function(!MessageEvent<string|!ArrayBuffer|!Blob>): void}
*/
WebSocket.prototype.onmessage;
/**
* An event handler called on close event.
* @type {?function(!CloseEvent): void}
*/
WebSocket.prototype.onclose;
/**
* Transmits data using the connection.
* @param {string|!ArrayBuffer|!ArrayBufferView|!Blob} data
* @return {void}
*/
WebSocket.prototype.send = function(data) {};
/**
* Closes the Web Socket connection or connection attempt, if any.
* @param {number=} opt_code
* @param {string=} opt_reason
* @return {undefined}
*/
WebSocket.prototype.close = function(opt_code, opt_reason) {};
/**
* @type {string} Sets the type of data (blob or arraybuffer) for binary data.
*/
WebSocket.prototype.binaryType;
// HTML5 History
/**
* @constructor
* @see http://w3c.github.io/html/browsers.html#the-history-interface
*/
function History() {}
/**
* Goes back one step in the joint session history.
* If there is no previous page, does nothing.
*
* @see https://html.spec.whatwg.org/multipage/history.html#dom-history-back
*
* @return {undefined}
*/
History.prototype.back = function() {};
/**
* Goes forward one step in the joint session history.
* If there is no next page, does nothing.
*
* @return {undefined}
*/
History.prototype.forward = function() {};
/**
* The number of entries in the joint session history.
*
* @type {number}
*/
History.prototype.length;
/**
* Goes back or forward the specified number of steps in the joint session
* history. A zero delta will reload the current page. If the delta is out of
* range, does nothing.
*
* @param {number} delta The number of entries to go back.
* @return {undefined}
*/
History.prototype.go = function(delta) {};
/**
* Pushes a new state into the session history.
* @see http://www.w3.org/TR/html5/history.html#the-history-interface
* @param {*} data New state.
* @param {string} title The title for a new session history entry.
* @param {string=} opt_url The URL for a new session history entry.
* @return {undefined}
*/
History.prototype.pushState = function(data, title, opt_url) {};
/**
* Replaces the current state in the session history.
* @see http://www.w3.org/TR/html5/history.html#the-history-interface
* @param {*} data New state.
* @param {string} title The title for a session history entry.
* @param {string=} opt_url The URL for a new session history entry.
* @return {undefined}
*/
History.prototype.replaceState = function(data, title, opt_url) {};
/**
* Pending state object.
* @see https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history#Reading_the_current_state
* @type {*}
*/
History.prototype.state;
/**
* Allows web applications to explicitly set default scroll restoration behavior
* on history navigation. This property can be either auto or manual.
*
* Non-standard. Only supported in Chrome 46+.
*
* @see https://developer.mozilla.org/en-US/docs/Web/API/History
* @see https://majido.github.io/scroll-restoration-proposal/history-based-api.html
* @type {string}
*/
History.prototype.scrollRestoration;
/**
* Add history property to Window.
*
* @type {!History}
*/
Window.prototype.history;
/**
* @constructor
* @see https://html.spec.whatwg.org/multipage/history.html#the-location-interface
*/
function Location() {}
/**
* Returns the Location object's URL. Can be set, to navigate to the given URL.
* @implicitCast
* @type {string}
* @see https://html.spec.whatwg.org/multipage/history.html#dom-location-href
*/
Location.prototype.href;
/**
* Returns the Location object's URL's origin.
* @const {string}
* @see https://html.spec.whatwg.org/multipage/history.html#dom-location-origin
*/
Location.prototype.origin;
/**
* Returns the Location object's URL's scheme. Can be set, to navigate to the
* same URL with a changed scheme.
* @type {string}
* @see https://html.spec.whatwg.org/multipage/history.html#dom-location-protocol
*/
Location.prototype.protocol;
/**
* Returns the Location object's URL's host and port (if different from the
* default port for the scheme). Can be set, to navigate to the same URL with
* a changed host and port.
* @type {string}
* @see https://html.spec.whatwg.org/multipage/history.html#dom-location-host
*/
Location.prototype.host;
/**
* Returns the Location object's URL's host. Can be set, to navigate to the
* same URL with a changed host.
* @type {string}
* @see https://html.spec.whatwg.org/multipage/history.html#dom-location-hostname
*/
Location.prototype.hostname;
/**
* Returns the Location object's URL's port. Can be set, to navigate to the
* same URL with a changed port.
* @type {string}
* @see https://html.spec.whatwg.org/multipage/history.html#the-location-interface:dom-location-port
*/
Location.prototype.port;
/**
* Returns the Location object's URL's path. Can be set, to navigate to the
* same URL with a changed path.
* @type {string}
* @see https://html.spec.whatwg.org/multipage/history.html#dom-location-pathname
*/
Location.prototype.pathname;
/**
* Returns the Location object's URL's query (includes leading "?" if
* non-empty). Can be set, to navigate to the same URL with a changed query
* (ignores leading "?").
* @type {string}
* @see https://html.spec.whatwg.org/multipage/history.html#dom-location-search
*/
Location.prototype.search;
/**
* Returns the Location object's URL's fragment (includes leading "#" if
* non-empty). Can be set, to navigate to the same URL with a changed fragment
* (ignores leading "#").
* @type {string}
* @see https://html.spec.whatwg.org/multipage/history.html#dom-location-hash
*/
Location.prototype.hash;
/**
* Navigates to the given page.
* @param {string} url
* @return {undefined}
* @see https://html.spec.whatwg.org/multipage/history.html#dom-location-assign
*/
Location.prototype.assign = function(url) {};
/**
* Removes the current page from the session history and navigates to the given
* page.
* @param {string} url
* @return {undefined}
* @see https://html.spec.whatwg.org/multipage/history.html#dom-location-replace
*/
Location.prototype.replace = function(url) {};
/**
* Reloads the current page.
* @param {boolean=} forceReload If true, reloads the page from
* the server. Defaults to false.
* @return {undefined}
* @see https://html.spec.whatwg.org/multipage/history.html#dom-location-reload
*/
Location.prototype.reload = function(forceReload) {};
/**
* Returns a DOMStringList object listing the origins of the ancestor browsing
* contexts, from the parent browsing context to the top-level browsing
* context.
* @type {DOMStringList}
* @see https://html.spec.whatwg.org/multipage/history.html#dom-location-ancestororigins
*/
Location.prototype.ancestorOrigins;
/**
* @see http://www.whatwg.org/specs/web-apps/current-work/#popstateevent
* @constructor
* @extends {Event}
*
* @param {string} type
* @param {{state: *}=} opt_eventInitDict
*/
function PopStateEvent(type, opt_eventInitDict) {}
/**
* @type {*}
*/
PopStateEvent.prototype.state;
/**
* Initializes the event after it has been created with document.createEvent
* @param {string} typeArg
* @param {boolean} canBubbleArg
* @param {boolean} cancelableArg
* @param {*} stateArg
* @return {undefined}
*/
PopStateEvent.prototype.initPopStateEvent = function(typeArg, canBubbleArg,
cancelableArg, stateArg) {};
/**
* @see http://www.whatwg.org/specs/web-apps/current-work/#hashchangeevent
* @constructor
* @extends {Event}
*
* @param {string} type
* @param {{oldURL: string, newURL: string}=} opt_eventInitDict
*/
function HashChangeEvent(type, opt_eventInitDict) {}
/** @type {string} */
HashChangeEvent.prototype.oldURL;
/** @type {string} */
HashChangeEvent.prototype.newURL;
/**
* Initializes the event after it has been created with document.createEvent
* @param {string} typeArg
* @param {boolean} canBubbleArg
* @param {boolean} cancelableArg
* @param {string} oldURLArg
* @param {string} newURLArg
* @return {undefined}
*/
HashChangeEvent.prototype.initHashChangeEvent = function(typeArg, canBubbleArg,
cancelableArg, oldURLArg, newURLArg) {};
/**
* @see http://www.whatwg.org/specs/web-apps/current-work/#pagetransitionevent
* @constructor
* @extends {Event}
*
* @param {string} type
* @param {{persisted: boolean}=} opt_eventInitDict
*/
function PageTransitionEvent(type, opt_eventInitDict) {}
/** @type {boolean} */
PageTransitionEvent.prototype.persisted;
/**
* Initializes the event after it has been created with document.createEvent
* @param {string} typeArg
* @param {boolean} canBubbleArg
* @param {boolean} cancelableArg
* @param {*} persistedArg
* @return {undefined}
*/
PageTransitionEvent.prototype.initPageTransitionEvent = function(typeArg,
canBubbleArg, cancelableArg, persistedArg) {};
/**
* @constructor
* @implements {IArrayLike<!File>}
*/
function FileList() {}
/** @type {number} */
FileList.prototype.length;
/**
* @param {number} i File to return from the list.
* @return {File} The ith file in the list.
* @nosideeffects
*/
FileList.prototype.item = function(i) { return null; };
/**
* @type {boolean}
* @see http://dev.w3.org/2006/webapi/XMLHttpRequest-2/#withcredentials
*/
XMLHttpRequest.prototype.withCredentials;
/**
* @type {?function(!ProgressEvent): void}
* @see https://xhr.spec.whatwg.org/#handler-xhr-onloadstart
*/
XMLHttpRequest.prototype.onloadstart;
/**
* @type {?function(!ProgressEvent): void}
* @see https://dvcs.w3.org/hg/xhr/raw-file/tip/Overview.html#handler-xhr-onprogress
*/
XMLHttpRequest.prototype.onprogress;
/**
* @type {?function(!ProgressEvent): void}
* @see https://xhr.spec.whatwg.org/#handler-xhr-onabort
*/
XMLHttpRequest.prototype.onabort;
/**
* @type {?function(!ProgressEvent): void}
* @see https://xhr.spec.whatwg.org/#handler-xhr-onload
*/
XMLHttpRequest.prototype.onload;
/**
* @type {?function(!ProgressEvent): void}
* @see https://xhr.spec.whatwg.org/#handler-xhr-ontimeout
*/
XMLHttpRequest.prototype.ontimeout;
/**
* @type {?function(!ProgressEvent): void}
* @see https://xhr.spec.whatwg.org/#handler-xhr-onloadend
*/
XMLHttpRequest.prototype.onloadend;
/**
* @type {XMLHttpRequestUpload}
* @see http://dev.w3.org/2006/webapi/XMLHttpRequest-2/#the-upload-attribute
*/
XMLHttpRequest.prototype.upload;
/**
* @param {string} mimeType The mime type to override with.
* @return {undefined}
*/
XMLHttpRequest.prototype.overrideMimeType = function(mimeType) {};
/**
* @type {string}
* @see http://dev.w3.org/2006/webapi/XMLHttpRequest-2/#the-responsetype-attribute
*/
XMLHttpRequest.prototype.responseType;
/**
* @type {?(ArrayBuffer|Blob|Document|Object|string)}
* @see http://dev.w3.org/2006/webapi/XMLHttpRequest-2/#the-response-attribute
*/
XMLHttpRequest.prototype.response;
/**
* @type {ArrayBuffer}
* Implemented as a draft spec in Firefox 4 as the way to get a requested array
* buffer from an XMLHttpRequest.
* @see https://developer.mozilla.org/En/Using_XMLHttpRequest#Receiving_binary_data_using_JavaScript_typed_arrays
*
* This property is not used anymore and should be removed.
* @see https://github.com/google/closure-compiler/pull/1389
*/
XMLHttpRequest.prototype.mozResponseArrayBuffer;
/**
* XMLHttpRequestEventTarget defines events for checking the status of a data
* transfer between a client and a server. This should be a common base class
* for XMLHttpRequest and XMLHttpRequestUpload.
*
* @constructor
* @implements {EventTarget}
*/
function XMLHttpRequestEventTarget() {}
/** @override */
XMLHttpRequestEventTarget.prototype.addEventListener = function(
type, listener, opt_options) {};
/** @override */
XMLHttpRequestEventTarget.prototype.removeEventListener = function(
type, listener, opt_options) {};
/** @override */
XMLHttpRequestEventTarget.prototype.dispatchEvent = function(evt) {};
/**
* An event target to track the status of an upload.
*
* @constructor
* @extends {XMLHttpRequestEventTarget}
*/
function XMLHttpRequestUpload() {}
/**
* @type {?function(!ProgressEvent): void}
* @see https://dvcs.w3.org/hg/xhr/raw-file/tip/Overview.html#handler-xhr-onprogress
*/
XMLHttpRequestUpload.prototype.onprogress;
/**
* @param {number=} opt_width
* @param {number=} opt_height
* @constructor
* @extends {HTMLImageElement}
*/
function Image(opt_width, opt_height) {}
/**
* Dataset collection.
* This is really a DOMStringMap but it behaves close enough to an object to
* pass as an object.
* @const {!Object<string, string>}
*/
HTMLElement.prototype.dataset;
/**
* @constructor
* @implements {IArrayLike<string>}
* @see https://dom.spec.whatwg.org/#interface-domtokenlist
*/
function DOMTokenList() {}
/**
* Returns the number of CSS classes applied to this Element.
* @type {number}
*/
DOMTokenList.prototype.length;
/**
* Returns the string value applied to this Element.
* @type {string|undefined}
*/
DOMTokenList.prototype.value;
/**
* @param {number} index The index of the item to return.
* @return {string} The CSS class at the specified index.
* @nosideeffects
*/
DOMTokenList.prototype.item = function(index) {};
/**
* @param {string} token The CSS class to check for.
* @return {boolean} Whether the CSS class has been applied to the Element.
* @nosideeffects
*/
DOMTokenList.prototype.contains = function(token) {};
/**
* @param {...string} var_args The CSS class(es) to add to this element.
* @return {undefined}
*/
DOMTokenList.prototype.add = function(var_args) {};
/**
* @param {...string} var_args The CSS class(es) to remove from this element.
* @return {undefined}
*/
DOMTokenList.prototype.remove = function(var_args) {};
/**
* Replaces token with newToken.
* @param {string} token The CSS class to replace.
* @param {string} newToken The new CSS class to use.
* @return {undefined}
*/
DOMTokenList.prototype.replace = function(token, newToken) {};
/**
* @param {string} token The token to query for.
* @return {boolean} Whether the token was found.
* @see https://developer.mozilla.org/en-US/docs/Web/API/DOMTokenList/supports
* @nosideeffects
*/
DOMTokenList.prototype.supports = function(token) {};
/**
* @param {string} token The CSS class to toggle from this element.
* @param {boolean=} opt_force True to add the class whether it exists
* or not. False to remove the class whether it exists or not.
* This argument is not supported on IE 10 and below, according to
* the MDN page linked below.
* @return {boolean} False if the token was removed; True otherwise.
* @see https://developer.mozilla.org/en-US/docs/Web/API/Element.classList
*/
DOMTokenList.prototype.toggle = function(token, opt_force) {};
/**
* @return {string} A stringified representation of CSS classes.
* @nosideeffects
* @override
*/
DOMTokenList.prototype.toString = function() {};
/**
* @return {!IteratorIterable<string>} An iterator to go through all values of
* the key/value pairs contained in this object.
* @nosideeffects
* @see https://developer.mozilla.org/en-US/docs/Web/API/DOMTokenList/values
*/
DOMTokenList.prototype.values = function() {};
/**
* A better interface to CSS classes than className.
* @const {!DOMTokenList}
* @see https://developer.mozilla.org/en-US/docs/Web/API/Element/classList
*/
Element.prototype.classList;
/**
* Constraint Validation API properties and methods
* @see http://www.w3.org/TR/2009/WD-html5-20090423/forms.html#the-constraint-validation-api
*/
/** @return {boolean} */
HTMLFormElement.prototype.checkValidity = function() {};
/** @return {boolean} */
HTMLFormElement.prototype.reportValidity = function() {};
/** @type {boolean} */
HTMLFormElement.prototype.noValidate;
/** @constructor */
function ValidityState() {}
/** @type {boolean} */
ValidityState.prototype.badInput;
/** @type {boolean} */
ValidityState.prototype.customError;
/** @type {boolean} */
ValidityState.prototype.patternMismatch;
/** @type {boolean} */
ValidityState.prototype.rangeOverflow;
/** @type {boolean} */
ValidityState.prototype.rangeUnderflow;
/** @type {boolean} */
ValidityState.prototype.stepMismatch;
/** @type {boolean} */
ValidityState.prototype.typeMismatch;
/** @type {boolean} */
ValidityState.prototype.tooLong;
/** @type {boolean} */
ValidityState.prototype.tooShort;
/** @type {boolean} */
ValidityState.prototype.valid;
/** @type {boolean} */
ValidityState.prototype.valueMissing;
/** @type {boolean} */
HTMLButtonElement.prototype.autofocus;
/**
* Can return null when hidden.
* See https://html.spec.whatwg.org/multipage/forms.html#dom-lfe-labels
* @const {?NodeList<!HTMLLabelElement>}
*/
HTMLButtonElement.prototype.labels;
/** @type {string} */
HTMLButtonElement.prototype.validationMessage;
/**
* @const {ValidityState}
*/
HTMLButtonElement.prototype.validity;
/** @type {boolean} */
HTMLButtonElement.prototype.willValidate;
/** @return {boolean} */
HTMLButtonElement.prototype.checkValidity = function() {};
/** @return {boolean} */
HTMLButtonElement.prototype.reportValidity = function() {};
/**
* @param {string} message
* @return {undefined}
*/
HTMLButtonElement.prototype.setCustomValidity = function(message) {};
/**
* @type {string}
* @implicitCast
* @see http://www.w3.org/TR/html5/forms.html#attr-fs-formaction
*/
HTMLButtonElement.prototype.formAction;
/**
* @type {string}
* @see http://www.w3.org/TR/html5/forms.html#attr-fs-formenctype
*/
HTMLButtonElement.prototype.formEnctype;
/**
* @type {string}
* @see http://www.w3.org/TR/html5/forms.html#attr-fs-formmethod
*/
HTMLButtonElement.prototype.formMethod;
/**
* @type {string}
* @see http://www.w3.org/TR/html5/forms.html#attr-fs-formtarget
*/
HTMLButtonElement.prototype.formTarget;
/** @type {boolean} */
HTMLInputElement.prototype.autofocus;
/** @type {boolean} */
HTMLInputElement.prototype.formNoValidate;
/**
* @type {string}
* @implicitCast
* @see http://www.w3.org/TR/html5/forms.html#attr-fs-formaction
*/
HTMLInputElement.prototype.formAction;
/**
* @type {string}
* @see http://www.w3.org/TR/html5/forms.html#attr-fs-formenctype
*/
HTMLInputElement.prototype.formEnctype;
/**
* @type {string}
* @see http://www.w3.org/TR/html5/forms.html#attr-fs-formmethod
*/
HTMLInputElement.prototype.formMethod;
/**
* @type {string}
* @see http://www.w3.org/TR/html5/forms.html#attr-fs-formtarget
*/
HTMLInputElement.prototype.formTarget;
/**
* Can return null when hidden.
* See https://html.spec.whatwg.org/multipage/forms.html#dom-lfe-labels
* @const {?NodeList<!HTMLLabelElement>}
*/
HTMLInputElement.prototype.labels;
/** @type {string} */
HTMLInputElement.prototype.validationMessage;
/**
* @type {number}
* @implicitCast
*/
HTMLInputElement.prototype.selectionStart;
/**
* @type {number}
* @implicitCast
*/
HTMLInputElement.prototype.selectionEnd;
/** @type {string} */
HTMLInputElement.prototype.selectionDirection;
/**
* @param {number} start
* @param {number} end
* @param {string=} direction
* @see https://html.spec.whatwg.org/#dom-textarea/input-setselectionrange
* @return {undefined}
*/
HTMLInputElement.prototype.setSelectionRange = function(start, end, direction) {};
/**
* @param {string} replacement
* @param {number=} start
* @param {number=} end
* @param {string=} selectionMode
* @see https://html.spec.whatwg.org/#dom-textarea/input-setrangetext
* @return {undefined}
*/
HTMLInputElement.prototype.setRangeText =
function(replacement, start, end, selectionMode) {};
/**
* @const {ValidityState}
*/
HTMLInputElement.prototype.validity;
/** @type {boolean} */
HTMLInputElement.prototype.willValidate;
/** @return {boolean} */
HTMLInputElement.prototype.checkValidity = function() {};
/** @return {boolean} */
HTMLInputElement.prototype.reportValidity = function() {};
/**
* @param {string} message
* @return {undefined}
*/
HTMLInputElement.prototype.setCustomValidity = function(message) {};
/** @type {Element} */
HTMLLabelElement.prototype.control;
/** @type {boolean} */
HTMLSelectElement.prototype.autofocus;
/**
* Can return null when hidden.
* See https://html.spec.whatwg.org/multipage/forms.html#dom-lfe-labels
* @const {?NodeList<!HTMLLabelElement>}
*/
HTMLSelectElement.prototype.labels;
/** @type {boolean} */
HTMLSelectElement.prototype.required;
/** @type {HTMLCollection<!HTMLOptionElement>} */
HTMLSelectElement.prototype.selectedOptions;
/** @type {string} */
HTMLSelectElement.prototype.validationMessage;
/**
* @const {ValidityState}
*/
HTMLSelectElement.prototype.validity;
/** @type {boolean} */
HTMLSelectElement.prototype.willValidate;
/** @return {boolean} */
HTMLSelectElement.prototype.checkValidity = function() {};
/** @return {boolean} */
HTMLSelectElement.prototype.reportValidity = function() {};
/**
* @param {string} message
* @return {undefined}
*/
HTMLSelectElement.prototype.setCustomValidity = function(message) {};
/** @type {boolean} */
HTMLTextAreaElement.prototype.autofocus;
/**
* Can return null when hidden.
* See https://html.spec.whatwg.org/multipage/forms.html#dom-lfe-labels
* @const {?NodeList<!HTMLLabelElement>}
*/
HTMLTextAreaElement.prototype.labels;
/** @type {number} */
HTMLTextAreaElement.prototype.maxLength;
/** @type {number} */
HTMLTextAreaElement.prototype.minLength;
/** @type {string} */
HTMLTextAreaElement.prototype.placeholder;
/** @type {number} */
HTMLTextAreaElement.prototype.textLength;
/** @type {string} */
HTMLTextAreaElement.prototype.validationMessage;
/**
* @const {ValidityState}
*/
HTMLTextAreaElement.prototype.validity;
/** @type {boolean} */
HTMLTextAreaElement.prototype.willValidate;
/** @return {boolean} */
HTMLTextAreaElement.prototype.checkValidity = function() {};
/** @return {boolean} */
HTMLTextAreaElement.prototype.reportValidity = function() {};
/**
* @param {string} message
* @return {undefined}
*/
HTMLTextAreaElement.prototype.setCustomValidity = function(message) {};
/**
* @constructor
* @extends {HTMLElement}
* @see http://www.w3.org/TR/html5/the-embed-element.html#htmlembedelement
*/
function HTMLEmbedElement() {}
/**
* @type {string}
* @see http://www.w3.org/TR/html5/dimension-attributes.html#dom-dim-width
*/
HTMLEmbedElement.prototype.width;
/**
* @type {string}
* @see http://www.w3.org/TR/html5/dimension-attributes.html#dom-dim-height
*/
HTMLEmbedElement.prototype.height;
/**
* @type {string}
* @implicitCast
* @see http://www.w3.org/TR/html5/the-embed-element.html#dom-embed-src
*/
HTMLEmbedElement.prototype.src;
/**
* @type {string}
* @see http://www.w3.org/TR/html5/the-embed-element.html#dom-embed-type
*/
HTMLEmbedElement.prototype.type;
// Fullscreen APIs.
/**
* @record
* @see https://fullscreen.spec.whatwg.org/#dictdef-fullscreenoptions
*/
function FullscreenOptions() {}
/** @type {string} */
FullscreenOptions.prototype.navigationUI;
/**
* @see https://fullscreen.spec.whatwg.org/#dom-element-requestfullscreen
* @param {!FullscreenOptions=} options
* @return {!Promise<undefined>}
*/
Element.prototype.requestFullscreen = function(options) {};
/**
* @type {boolean}
* @see http://www.w3.org/TR/2012/WD-fullscreen-20120703/#dom-document-fullscreenenabled
*/
Document.prototype.fullscreenEnabled;
/**
* @type {Element}
* @see http://www.w3.org/TR/2012/WD-fullscreen-20120703/#dom-document-fullscreenelement
*/
Document.prototype.fullscreenElement;
/**
* @see http://www.w3.org/TR/2012/WD-fullscreen-20120703/#dom-document-exitfullscreen
* @return {undefined}
*/
Document.prototype.exitFullscreen = function() {};
// Externs definitions of browser current implementations.
// Firefox 10 implementation.
Element.prototype.mozRequestFullScreen = function() {};
Element.prototype.mozRequestFullScreenWithKeys = function() {};
/** @type {boolean} */
Document.prototype.mozFullScreen;
Document.prototype.mozCancelFullScreen = function() {};
/** @type {Element} */
Document.prototype.mozFullScreenElement;
/** @type {boolean} */
Document.prototype.mozFullScreenEnabled;
// Chrome 21 implementation.
/**
* The current fullscreen element for the document is set to this element.
* Valid only for Webkit browsers.
* @param {number=} opt_allowKeyboardInput Whether keyboard input is desired.
* Should use ALLOW_KEYBOARD_INPUT constant.
* @return {undefined}
*/
Element.prototype.webkitRequestFullScreen = function(opt_allowKeyboardInput) {};
/**
* The current fullscreen element for the document is set to this element.
* Valid only for Webkit browsers.
* @param {number=} opt_allowKeyboardInput Whether keyboard input is desired.
* Should use ALLOW_KEYBOARD_INPUT constant.
* @return {undefined}
*/
Element.prototype.webkitRequestFullscreen = function(opt_allowKeyboardInput) {};
/** @type {boolean} */
Document.prototype.webkitIsFullScreen;
Document.prototype.webkitCancelFullScreen = function() {};
/** @type {boolean} */
Document.prototype.webkitFullscreenEnabled;
/** @type {Element} */
Document.prototype.webkitCurrentFullScreenElement;
/** @type {Element} */
Document.prototype.webkitFullscreenElement;
/** @type {boolean} */
Document.prototype.webkitFullScreenKeyboardInputAllowed;
// IE 11 implementation.
// http://msdn.microsoft.com/en-us/library/ie/dn265028(v=vs.85).aspx
/** @return {void} */
Element.prototype.msRequestFullscreen = function() {};
/** @return {void} */
Document.prototype.msExitFullscreen = function() {};
/** @type {boolean} */
Document.prototype.msFullscreenEnabled;
/** @type {Element} */
Document.prototype.msFullscreenElement;
/** @const {number} */
Element.ALLOW_KEYBOARD_INPUT;
/** @const {number} */
Element.prototype.ALLOW_KEYBOARD_INPUT;
/**
* @typedef {{
* childList: (boolean|undefined),
* attributes: (boolean|undefined),
* characterData: (boolean|undefined),
* subtree: (boolean|undefined),
* attributeOldValue: (boolean|undefined),
* characterDataOldValue: (boolean|undefined),
* attributeFilter: (!Array<string>|undefined)
* }}
*/
var MutationObserverInit;
/** @constructor */
function MutationRecord() {}
/** @type {string} */
MutationRecord.prototype.type;
/** @type {Node} */
MutationRecord.prototype.target;
/** @type {!NodeList<!Node>} */
MutationRecord.prototype.addedNodes;
/** @type {!NodeList<!Node>} */
MutationRecord.prototype.removedNodes;
/** @type {?Node} */
MutationRecord.prototype.previousSibling;
/** @type {?Node} */
MutationRecord.prototype.nextSibling;
/** @type {?string} */
MutationRecord.prototype.attributeName;
/** @type {?string} */
MutationRecord.prototype.attributeNamespace;
/** @type {?string} */
MutationRecord.prototype.oldValue;
/**
* @see http://www.w3.org/TR/domcore/#mutation-observers
* @param {function(!Array<!MutationRecord>, !MutationObserver)} callback
* @constructor
*/
function MutationObserver(callback) {}
/**
* @param {Node} target
* @param {MutationObserverInit=} options
* @return {undefined}
*/
MutationObserver.prototype.observe = function(target, options) {};
MutationObserver.prototype.disconnect = function() {};
/**
* @return {!Array<!MutationRecord>}
*/
MutationObserver.prototype.takeRecords = function() {};
/**
* @type {function(new:MutationObserver, function(Array<MutationRecord>))}
*/
Window.prototype.WebKitMutationObserver;
/**
* @type {function(new:MutationObserver, function(Array<MutationRecord>))}
*/
Window.prototype.MozMutationObserver;
/**
* @see http://www.w3.org/TR/page-visibility/
* @type {VisibilityState}
*/
Document.prototype.visibilityState;
/**
* @type {string}
*/
Document.prototype.mozVisibilityState;
/**
* @type {string}
*/
Document.prototype.webkitVisibilityState;
/**
* @type {string}
*/
Document.prototype.msVisibilityState;
/**
* @see http://www.w3.org/TR/page-visibility/
* @type {boolean}
*/
Document.prototype.hidden;
/**
* @type {boolean}
*/
Document.prototype.mozHidden;
/**
* @type {boolean}
*/
Document.prototype.webkitHidden;
/**
* @type {boolean}
*/
Document.prototype.msHidden;
/**
* @see http://www.w3.org/TR/components-intro/
* @see http://w3c.github.io/webcomponents/spec/custom/#extensions-to-document-interface-to-register
* @param {string} type
* @param {{extends: (string|undefined), prototype: (Object|undefined)}=}
* options
* @return {function(new:Element, ...*)} a constructor for the new tag.
* @deprecated document.registerElement() is deprecated in favor of
* customElements.define()
*/
Document.prototype.registerElement = function(type, options) {};
/**
* @see http://www.w3.org/TR/components-intro/
* @see http://w3c.github.io/webcomponents/spec/custom/#extensions-to-document-interface-to-register
* @param {string} type
* @param {{extends: (string|undefined), prototype: (Object|undefined)}} options
* @deprecated This method has been removed and will be removed soon from this file.
*/
Document.prototype.register = function(type, options) {};
/**
* @type {!FontFaceSet}
* @see http://dev.w3.org/csswg/css-font-loading/#dom-fontfacesource-fonts
*/
Document.prototype.fonts;
/**
* @type {?HTMLScriptElement}
* @see https://developer.mozilla.org/en-US/docs/Web/API/Document/currentScript
*/
Document.prototype.currentScript;
/**
* Definition of ShadowRoot interface,
* @see http://www.w3.org/TR/shadow-dom/#api-shadow-root
* @constructor
* @extends {DocumentFragment}
*/
function ShadowRoot() {}
/**
* The host element that a ShadowRoot is attached to.
* Note: this is not yet W3C standard but is undergoing development.
* W3C feature tracking bug:
* https://www.w3.org/Bugs/Public/show_bug.cgi?id=22399
* Draft specification:
* https://dvcs.w3.org/hg/webcomponents/raw-file/6743f1ace623/spec/shadow/index.html#shadow-root-object
* @type {!Element}
*/
ShadowRoot.prototype.host;
/**
* @param {string} id id.
* @return {HTMLElement}
* @nosideeffects
*/
ShadowRoot.prototype.getElementById = function(id) {};
/**
* @return {Selection}
* @nosideeffects
*/
ShadowRoot.prototype.getSelection = function() {};
/**
* @param {number} x
* @param {number} y
* @return {Element}
* @nosideeffects
*/
ShadowRoot.prototype.elementFromPoint = function(x, y) {};
/**
* @param {number} x
* @param {number} y
* @return {!IArrayLike<!Element>}
* @nosideeffects
*/
ShadowRoot.prototype.elementsFromPoint = function(x, y) {};
/**
* @type {?Element}
*/
ShadowRoot.prototype.activeElement;
/**
* @type {!ShadowRootMode}
*/
ShadowRoot.prototype.mode;
/**
* @type {?ShadowRoot}
* @deprecated
*/
ShadowRoot.prototype.olderShadowRoot;
/**
* @type {string}
* @implicitCast
*/
ShadowRoot.prototype.innerHTML;
/**
* @type {!StyleSheetList}
*/
ShadowRoot.prototype.styleSheets;
/**
* @typedef {string}
* @see https://dom.spec.whatwg.org/#enumdef-shadowrootmode
*/
var ShadowRootMode;
/**
* @typedef {string}
* @see https://dom.spec.whatwg.org/#enumdef-slotassignmentmode
*/
var SlotAssignmentMode;
/**
* @record
* @see https://dom.spec.whatwg.org/#dictdef-shadowrootinit
*/
function ShadowRootInit() {}
/** @type {!ShadowRootMode} */
ShadowRootInit.prototype.mode;
/** @type {(undefined|boolean)} */
ShadowRootInit.prototype.delegatesFocus;
/** @type {(undefined|SlotAssignmentMode)} */
ShadowRootInit.prototype.slotAssignment;
/**
* @see http://www.w3.org/TR/shadow-dom/#the-content-element
* @constructor
* @extends {HTMLElement}
*/
function HTMLContentElement() {}
/**
* @type {string}
*/
HTMLContentElement.prototype.select;
/**
* @return {!NodeList<!Node>}
*/
HTMLContentElement.prototype.getDistributedNodes = function() {};
/**
* @see http://www.w3.org/TR/shadow-dom/#the-shadow-element
* @constructor
* @extends {HTMLElement}
*/
function HTMLShadowElement() {}
/**
* @return {!NodeList<!Node>}
*/
HTMLShadowElement.prototype.getDistributedNodes = function() {};
/**
* @see http://www.w3.org/TR/html5/webappapis.html#the-errorevent-interface
*
* @constructor
* @extends {Event}
*
* @param {string} type
* @param {ErrorEventInit=} opt_eventInitDict
*/
function ErrorEvent(type, opt_eventInitDict) {}
/** @const {string} */
ErrorEvent.prototype.message;
/** @const {string} */
ErrorEvent.prototype.filename;
/** @const {number} */
ErrorEvent.prototype.lineno;
/** @const {number} */
ErrorEvent.prototype.colno;
/** @const {*} */
ErrorEvent.prototype.error;
/**
* @record
* @extends {EventInit}
* @see https://www.w3.org/TR/html5/webappapis.html#erroreventinit
*/
function ErrorEventInit() {}
/** @type {undefined|string} */
ErrorEventInit.prototype.message;
/** @type {undefined|string} */
ErrorEventInit.prototype.filename;
/** @type {undefined|number} */
ErrorEventInit.prototype.lineno;
/** @type {undefined|number} */
ErrorEventInit.prototype.colno;
/** @type {*} */
ErrorEventInit.prototype.error;
/**
* @see http://dom.spec.whatwg.org/#dom-domimplementation-createhtmldocument
* @param {string=} opt_title A title to give the new HTML document
* @return {!HTMLDocument}
*/
DOMImplementation.prototype.createHTMLDocument = function(opt_title) {};
/**
* @constructor
* @see https://html.spec.whatwg.org/multipage/embedded-content.html#the-picture-element
* @extends {HTMLElement}
*/
function HTMLPictureElement() {}
/**
* @constructor
* @see https://html.spec.whatwg.org/multipage/embedded-content.html#the-picture-element
* @extends {HTMLElement}
*/
function HTMLSourceElement() {}
/** @type {string} */
HTMLSourceElement.prototype.media;
/** @type {string} */
HTMLSourceElement.prototype.sizes;
/** @type {string} @implicitCast */
HTMLSourceElement.prototype.src;
/** @type {string} */
HTMLSourceElement.prototype.srcset;
/** @type {string} */
HTMLSourceElement.prototype.type;
/** @type {string} */
HTMLImageElement.prototype.sizes;
/** @type {string} */
HTMLImageElement.prototype.srcset;
/**
* 4.11 Interactive elements
* @see http://www.w3.org/html/wg/drafts/html/master/interactive-elements.html
*/
/**
* @see http://www.w3.org/html/wg/drafts/html/master/interactive-elements.html#the-details-element
* @constructor
* @extends {HTMLElement}
*/
function HTMLDetailsElement() {}
/**
* @see http://www.w3.org/html/wg/drafts/html/master/interactive-elements.html#dom-details-open
* @type {boolean}
*/
HTMLDetailsElement.prototype.open;
// As of 2/20/2015, <summary> has no special web IDL interface nor global
// constructor (i.e. HTMLSummaryElement).
/**
* @see http://www.w3.org/html/wg/drafts/html/master/interactive-elements.html#dom-menu-type
* @type {string}
*/
HTMLMenuElement.prototype.type;
/**
* @see http://www.w3.org/html/wg/drafts/html/master/interactive-elements.html#dom-menu-label
* @type {string}
*/
HTMLMenuElement.prototype.label;
/**
* @see http://www.w3.org/html/wg/drafts/html/master/interactive-elements.html#the-menuitem-element
* @constructor
* @extends {HTMLElement}
*/
function HTMLMenuItemElement() {}
/**
* @see http://www.w3.org/html/wg/drafts/html/master/interactive-elements.html#dom-menuitem-type
* @type {string}
*/
HTMLMenuItemElement.prototype.type;
/**
* @see http://www.w3.org/html/wg/drafts/html/master/interactive-elements.html#dom-menuitem-label
* @type {string}
*/
HTMLMenuItemElement.prototype.label;
/**
* @see http://www.w3.org/html/wg/drafts/html/master/interactive-elements.html#dom-menuitem-icon
* @type {string}
*/
HTMLMenuItemElement.prototype.icon;
/**
* @see http://www.w3.org/html/wg/drafts/html/master/interactive-elements.html#dom-menuitem-disabled
* @type {boolean}
*/
HTMLMenuItemElement.prototype.disabled;
/**
* @see http://www.w3.org/html/wg/drafts/html/master/interactive-elements.html#dom-menuitem-checked
* @type {boolean}
*/
HTMLMenuItemElement.prototype.checked;
/**
* @see http://www.w3.org/html/wg/drafts/html/master/interactive-elements.html#dom-menuitem-radiogroup
* @type {string}
*/
HTMLMenuItemElement.prototype.radiogroup;
/**
* @see http://www.w3.org/html/wg/drafts/html/master/interactive-elements.html#dom-menuitem-default
* @type {boolean}
*/
HTMLMenuItemElement.prototype.default;
// TODO(dbeam): add HTMLMenuItemElement.prototype.command if it's implemented.
/**
* @see http://www.w3.org/html/wg/drafts/html/master/interactive-elements.html#relatedevent
* @param {string} type
* @param {{relatedTarget: (EventTarget|undefined)}=} opt_eventInitDict
* @constructor
* @extends {Event}
*/
function RelatedEvent(type, opt_eventInitDict) {}
/**
* @see http://www.w3.org/html/wg/drafts/html/master/interactive-elements.html#dom-relatedevent-relatedtarget
* @type {EventTarget|undefined}
*/
RelatedEvent.prototype.relatedTarget;
/**
* @see http://www.w3.org/html/wg/drafts/html/master/interactive-elements.html#the-dialog-element
* @constructor
* @extends {HTMLElement}
*/
function HTMLDialogElement() {}
/**
* @see http://www.w3.org/html/wg/drafts/html/master/interactive-elements.html#dom-dialog-open
* @type {boolean}
*/
HTMLDialogElement.prototype.open;
/**
* @see http://www.w3.org/html/wg/drafts/html/master/interactive-elements.html#dom-dialog-returnvalue
* @type {string}
*/
HTMLDialogElement.prototype.returnValue;
/**
* @see http://www.w3.org/html/wg/drafts/html/master/interactive-elements.html#dom-dialog-show
* @param {(MouseEvent|Element)=} opt_anchor
* @return {undefined}
*/
HTMLDialogElement.prototype.show = function(opt_anchor) {};
/**
* @see http://www.w3.org/html/wg/drafts/html/master/interactive-elements.html#dom-dialog-showmodal
* @param {(MouseEvent|Element)=} opt_anchor
* @return {undefined}
*/
HTMLDialogElement.prototype.showModal = function(opt_anchor) {};
/**
* @see http://www.w3.org/html/wg/drafts/html/master/interactive-elements.html#dom-dialog-close
* @param {string=} opt_returnValue
* @return {undefined}
*/
HTMLDialogElement.prototype.close = function(opt_returnValue) {};
/**
* @see https://html.spec.whatwg.org/multipage/scripting.html#the-template-element
* @constructor
* @extends {HTMLElement}
*/
function HTMLTemplateElement() {}
/**
* @see https://html.spec.whatwg.org/multipage/scripting.html#the-template-element
* @type {!DocumentFragment}
*/
HTMLTemplateElement.prototype.content;
/**
* @type {?Document}
* @see w3c_dom2.js
* @see http://www.w3.org/TR/html-imports/#interface-import
*/
HTMLLinkElement.prototype.import;
/**
* @type {string}
* @see https://html.spec.whatwg.org/#attr-link-as
* @see https://w3c.github.io/preload/#as-attribute
*/
HTMLLinkElement.prototype.as;
/**
* @see https://html.spec.whatwg.org/#attr-link-crossorigin
* @type {string}
*/
HTMLLinkElement.prototype.crossOrigin;
/**
* @return {boolean}
* @see https://www.w3.org/TR/html5/forms.html#dom-fieldset-elements
*/
HTMLFieldSetElement.prototype.checkValidity = function() {};
/**
* @type {HTMLCollection}
* @see https://www.w3.org/TR/html5/forms.html#dom-fieldset-elements
*/
HTMLFieldSetElement.prototype.elements;
/**
* @type {string}
* @see https://www.w3.org/TR/html5/forms.html#the-fieldset-element
*/
HTMLFieldSetElement.prototype.name;
/**
* @param {string} message
* @see https://www.w3.org/TR/html5/forms.html#dom-fieldset-elements
* @return {undefined}
*/
HTMLFieldSetElement.prototype.setCustomValidity = function(message) {};
/**
* @type {string}
* @see https://www.w3.org/TR/html5/forms.html#dom-fieldset-type
*/
HTMLFieldSetElement.prototype.type;
/**
* @type {string}
* @see https://www.w3.org/TR/html5/forms.html#the-fieldset-element
*/
HTMLFieldSetElement.prototype.validationMessage;
/**
* @type {ValidityState}
* @see https://www.w3.org/TR/html5/forms.html#the-fieldset-element
*/
HTMLFieldSetElement.prototype.validity;
/**
* @type {boolean}
* @see https://www.w3.org/TR/html5/forms.html#the-fieldset-element
*/
HTMLFieldSetElement.prototype.willValidate;
/**
* @constructor
* @extends {NodeList<T>}
* @template T
* @see https://html.spec.whatwg.org/multipage/infrastructure.html#radionodelist
*/
function RadioNodeList() {}
/**
* @type {string}
* @see https://html.spec.whatwg.org/multipage/infrastructure.html#radionodelist
*/
RadioNodeList.prototype.value;
/**
* @see https://html.spec.whatwg.org/multipage/forms.html#the-datalist-element
* @constructor
* @extends {HTMLElement}
*/
function HTMLDataListElement() {}
/** @type {HTMLCollection<!HTMLOptionElement>} */
HTMLDataListElement.prototype.options;
/**
* @return {boolean}
* @see https://html.spec.whatwg.org/multipage/iframe-embed-object.html#the-object-element
*/
HTMLObjectElement.prototype.checkValidity;
/**
* @param {string} message
* @see https://html.spec.whatwg.org/multipage/iframe-embed-object.html#the-object-element
* @return {undefined}
*/
HTMLObjectElement.prototype.setCustomValidity;
/**
* @type {string}
* @see https://html.spec.whatwg.org/multipage/iframe-embed-object.html#the-object-element
*/
HTMLObjectElement.prototype.validationMessage;
/**
* @type {!ValidityState}
* @see https://html.spec.whatwg.org/multipage/iframe-embed-object.html#the-object-element
*/
HTMLObjectElement.prototype.validity;
/**
* @type {boolean}
* @see https://html.spec.whatwg.org/multipage/iframe-embed-object.html#the-object-element
*/
HTMLObjectElement.prototype.willValidate;
/**
* @see https://html.spec.whatwg.org/multipage/forms.html#the-output-element
* @constructor
* @extends {HTMLElement}
*/
function HTMLOutputElement() {}
/**
* @const {!DOMTokenList}
*/
HTMLOutputElement.prototype.htmlFor;
/**
* @type {HTMLFormElement}
*/
HTMLOutputElement.prototype.form;
/**
* @type {string}
*/
HTMLOutputElement.prototype.name;
/**
* @const {string}
*/
HTMLOutputElement.prototype.type;
/**
* @type {string}
*/
HTMLOutputElement.prototype.defaultValue;
/**
* @type {string}
*/
HTMLOutputElement.prototype.value;
/**
* @const {?NodeList<!HTMLLabelElement>}
*/
HTMLOutputElement.prototype.labels;
/** @type {string} */
HTMLOutputElement.prototype.validationMessage;
/**
* @const {ValidityState}
*/
HTMLOutputElement.prototype.validity;
/** @type {boolean} */
HTMLOutputElement.prototype.willValidate;
/** @return {boolean} */
HTMLOutputElement.prototype.checkValidity = function() {};
/** @return {boolean} */
HTMLOutputElement.prototype.reportValidity = function() {};
/** @param {string} message */
HTMLOutputElement.prototype.setCustomValidity = function(message) {};
/**
* @see https://html.spec.whatwg.org/multipage/forms.html#the-progress-element
* @constructor
* @extends {HTMLElement}
*/
function HTMLProgressElement() {}
/** @type {number} */
HTMLProgressElement.prototype.value;
/** @type {number} */
HTMLProgressElement.prototype.max;
/** @type {number} */
HTMLProgressElement.prototype.position;
/** @type {?NodeList<!Node>} */
HTMLProgressElement.prototype.labels;
/**
* @see https://html.spec.whatwg.org/multipage/embedded-content.html#the-track-element
* @constructor
* @extends {HTMLElement}
*/
function HTMLTrackElement() {}
/** @type {string} */
HTMLTrackElement.prototype.kind;
/** @type {string} @implicitCast */
HTMLTrackElement.prototype.src;
/** @type {string} */
HTMLTrackElement.prototype.srclang;
/** @type {string} */
HTMLTrackElement.prototype.label;
/** @type {boolean} */
HTMLTrackElement.prototype.default;
/** @const {number} */
HTMLTrackElement.prototype.readyState;
/** @const {!TextTrack} */
HTMLTrackElement.prototype.track;
/**
* @see https://html.spec.whatwg.org/multipage/forms.html#the-meter-element
* @constructor
* @extends {HTMLElement}
*/
function HTMLMeterElement() {}
/** @type {number} */
HTMLMeterElement.prototype.value;
/** @type {number} */
HTMLMeterElement.prototype.min;
/** @type {number} */
HTMLMeterElement.prototype.max;
/** @type {number} */
HTMLMeterElement.prototype.low;
/** @type {number} */
HTMLMeterElement.prototype.high;
/** @type {number} */
HTMLMeterElement.prototype.optimum;
/** @type {?NodeList<!Node>} */
HTMLMeterElement.prototype.labels;
/**
* @interface
* @see https://storage.spec.whatwg.org/#api
*/
function NavigatorStorage() {};
/**
* @type {!StorageManager}
*/
NavigatorStorage.prototype.storage;
/**
* @constructor
* @implements NavigatorStorage
* @see https://www.w3.org/TR/html5/webappapis.html#navigator
*/
function Navigator() {}
/**
* @type {string}
* @see https://www.w3.org/TR/html5/webappapis.html#dom-navigator-appcodename
*/
Navigator.prototype.appCodeName;
/**
* @type {string}
* @see https://www.w3.org/TR/html5/webappapis.html#dom-navigator-appname
*/
Navigator.prototype.appName;
/**
* @type {string}
* @see https://www.w3.org/TR/html5/webappapis.html#dom-navigator-appversion
*/
Navigator.prototype.appVersion;
/**
* @type {string}
* @see https://www.w3.org/TR/html5/webappapis.html#dom-navigator-platform
*/
Navigator.prototype.platform;
/**
* @type {string}
* @see https://www.w3.org/TR/html5/webappapis.html#dom-navigator-product
*/
Navigator.prototype.product;
/**
* @type {string}
* @see https://www.w3.org/TR/html5/webappapis.html#dom-navigator-useragent
*/
Navigator.prototype.userAgent;
/**
* @return {boolean}
* @see https://www.w3.org/TR/html5/webappapis.html#dom-navigator-taintenabled
*/
Navigator.prototype.taintEnabled = function() {};
/**
* @type {string}
* @see https://www.w3.org/TR/html5/webappapis.html#dom-navigator-language
*/
Navigator.prototype.language;
/**
* @type {boolean}
* @see https://www.w3.org/TR/html5/browsers.html#navigatoronline
*/
Navigator.prototype.onLine;
/**
* @type {boolean}
* @see https://www.w3.org/TR/html5/webappapis.html#dom-navigator-cookieenabled
*/
Navigator.prototype.cookieEnabled;
/**
* @param {string} scheme
* @param {string} url
* @param {string} title
* @return {undefined}
*/
Navigator.prototype.registerProtocolHandler = function(scheme, url, title) {}
/**
* @param {string} mimeType
* @param {string} url
* @param {string} title
* @return {undefined}
*/
Navigator.prototype.registerContentHandler = function(mimeType, url, title) {}
/**
* @param {string} scheme
* @param {string} url
* @return {undefined}
*/
Navigator.prototype.unregisterProtocolHandler = function(scheme, url) {}
/**
* @param {string} mimeType
* @param {string} url
* @return {undefined}
*/
Navigator.prototype.unregisterContentHandler = function(mimeType, url) {}
/**
* @type {!MimeTypeArray}
* @see https://www.w3.org/TR/html5/webappapis.html#dom-navigator-mimetypes
*/
Navigator.prototype.mimeTypes;
/**
* @type {!PluginArray}
* @see https://www.w3.org/TR/html5/webappapis.html#dom-navigator-plugins
*/
Navigator.prototype.plugins;
/**
* @return {boolean}
* @see https://www.w3.org/TR/html5/webappapis.html#dom-navigator-javaenabled
* @nosideeffects
*/
Navigator.prototype.javaEnabled = function() {};
/**
* @type {number}
* @see https://developers.google.com/web/updates/2017/12/device-memory
* https://github.com/w3c/device-memory
*/
Navigator.prototype.deviceMemory;
/**
* @type {!StorageManager}
* @see https://storage.spec.whatwg.org
*/
Navigator.prototype.storage;
/**
* @param {!ShareData=} data
* @return {boolean}
* @see https://developer.mozilla.org/en-US/docs/Web/API/Navigator/canShare
*/
Navigator.prototype.canShare = function(data) {};
/**
* @param {!ShareData=} data
* @return {!Promise<undefined>}
* @see https://wicg.github.io/web-share/#share-method
*/
Navigator.prototype.share = function(data) {};
/**
* @type {number}
* @see https://developer.mozilla.org/en-US/docs/Web/API/NavigatorConcurrentHardware/hardwareConcurrency
*/
Navigator.prototype.hardwareConcurrency;
/**
* @constructor
* @implements NavigatorStorage
* @see https://html.spec.whatwg.org/multipage/workers.html#the-workernavigator-object
*/
function WorkerNavigator() {}
/**
* @type {number}
* @see https://developers.google.com/web/updates/2017/12/device-memory
* https://github.com/w3c/device-memory
*/
WorkerNavigator.prototype.deviceMemory;
/**
* @type {number}
* @see https://developer.mozilla.org/en-US/docs/Web/API/NavigatorConcurrentHardware/hardwareConcurrency
*/
WorkerNavigator.prototype.hardwareConcurrency;
/**
* @type {!StorageManager}
* @see https://storage.spec.whatwg.org
*/
WorkerNavigator.prototype.storage;
/**
* @record
* @see https://wicg.github.io/web-share/#sharedata-dictionary
*/
function ShareData() {}
/** @type {string|undefined} */
ShareData.prototype.title;
/** @type {string|undefined} */
ShareData.prototype.text;
/** @type {string|undefined} */
ShareData.prototype.url;
/**
* @constructor
* @implements {IObject<(string|number),!Plugin>}
* @implements {IArrayLike<!Plugin>}
* @see https://www.w3.org/TR/html5/webappapis.html#pluginarray
*/
function PluginArray() {}
/** @type {number} */
PluginArray.prototype.length;
/**
* @param {number} index
* @return {Plugin}
*/
PluginArray.prototype.item = function(index) {};
/**
* @param {string} name
* @return {Plugin}
*/
PluginArray.prototype.namedItem = function(name) {};
/**
* @param {boolean=} reloadDocuments
* @return {undefined}
*/
PluginArray.prototype.refresh = function(reloadDocuments) {};
/**
* @constructor
* @implements {IObject<(string|number),!MimeType>}
* @implements {IArrayLike<!MimeType>}
* @see https://www.w3.org/TR/html5/webappapis.html#mimetypearray
*/
function MimeTypeArray() {}
/**
* @param {number} index
* @return {MimeType}
*/
MimeTypeArray.prototype.item = function(index) {};
/**
* @type {number}
* @see https://developer.mozilla.org/en/DOM/window.navigator.mimeTypes
*/
MimeTypeArray.prototype.length;
/**
* @param {string} name
* @return {MimeType}
*/
MimeTypeArray.prototype.namedItem = function(name) {};
/**
* @constructor
* @see https://www.w3.org/TR/html5/webappapis.html#mimetype
*/
function MimeType() {}
/** @type {string} */
MimeType.prototype.description;
/** @type {Plugin} */
MimeType.prototype.enabledPlugin;
/** @type {string} */
MimeType.prototype.suffixes;
/** @type {string} */
MimeType.prototype.type;
/**
* @constructor
* @see https://www.w3.org/TR/html5/webappapis.html#dom-plugin
*/
function Plugin() {}
/** @type {string} */
Plugin.prototype.description;
/** @type {string} */
Plugin.prototype.filename;
/** @type {number} */
Plugin.prototype.length;
/** @type {string} */
Plugin.prototype.name;
/**
* @see https://html.spec.whatwg.org/multipage/custom-elements.html#customelementregistry
* @constructor
*/
function CustomElementRegistry() {}
/**
* @param {string} tagName
* @param {function(new:HTMLElement)} klass
* @param {{extends: string}=} options
* @return {undefined}
*/
CustomElementRegistry.prototype.define = function (tagName, klass, options) {};
/**
* @param {string} tagName
* @return {function(new:HTMLElement)|undefined}
*/
CustomElementRegistry.prototype.get = function(tagName) {};
/**
* @param {string} tagName
* @return {!Promise<undefined>}
*/
CustomElementRegistry.prototype.whenDefined = function(tagName) {};
/**
* @param {!Node} root
* @return {undefined}
*/
CustomElementRegistry.prototype.upgrade = function(root) {};
/** @type {!CustomElementRegistry} */
var customElements;
/**
* @constructor
* @extends {HTMLElement}
*/
function HTMLSlotElement() {}
/** @typedef {{flatten: boolean}} */
var AssignedNodesOptions;
/**
* @param {!AssignedNodesOptions=} options
* @return {!Array<!Node>}
*/
HTMLSlotElement.prototype.assignedNodes = function(options) {};
/**
* @param {!AssignedNodesOptions=} options
* @return {!Array<!HTMLElement>}
*/
HTMLSlotElement.prototype.assignedElements = function(options) {};
/** @type {boolean} */
Event.prototype.composed;
/**
* @return {!Array<!EventTarget>}
* @see https://developer.mozilla.org/en-US/docs/Web/API/Event/composedPath
*/
Event.prototype.composedPath = function() {};
/**
* @constructor
* @param {{
* firesTouchEvents: (string|undefined),
* pointerMovementScrolls: (string|undefined)
* }=} opt_options
*/
function InputDeviceCapabilities(opt_options){}
/** @type {boolean} */
InputDeviceCapabilities.prototype.firesTouchEvents;
/** @type {boolean} */
InputDeviceCapabilities.prototype.pointerMovementScrolls;
/** @type {?InputDeviceCapabilities} */
UIEvent.prototype.sourceCapabilities;
/**
* @see https://developer.mozilla.org/en-US/docs/Web/API/VisualViewport
* @constructor
* @implements {EventTarget}
*/
function VisualViewport() {}
/** @type {number} */
VisualViewport.prototype.offsetLeft;
/** @type {number} */
VisualViewport.prototype.offsetTop;
/** @type {number} */
VisualViewport.prototype.pageLeft;
/** @type {number} */
VisualViewport.prototype.pageTop;
/** @type {number} */
VisualViewport.prototype.width;
/** @type {number} */
VisualViewport.prototype.height;
/** @type {number} */
VisualViewport.prototype.scale;
/** @override */
VisualViewport.prototype.addEventListener = function(type, listener,
opt_options) {};
/** @override */
VisualViewport.prototype.removeEventListener = function(type, listener,
opt_options) {};
/** @override */
VisualViewport.prototype.dispatchEvent = function(evt) {};
/** @type {?function(!Event)} */
VisualViewport.prototype.onresize;
/** @type {?function(!Event)} */
VisualViewport.prototype.onscroll;
/**
* @see https://storage.spec.whatwg.org/
* @constructor
*/
function StorageManager() {}
/** @return {!Promise<boolean>} */
StorageManager.prototype.persisted = function() {};
/** @return {!Promise<boolean>} */
StorageManager.prototype.persist = function() {};
/** @return {!Promise<StorageEstimate>} */
StorageManager.prototype.estimate = function() {};
/**
* @see https://storage.spec.whatwg.org/
* @typedef {{
* usage: number,
* quota: number
* }}
*/
var StorageEstimate;
/*
* Focus Management APIs
*
* See https://html.spec.whatwg.org/multipage/interaction.html#focus-management-apis
*/
/**
* @type {?Element}
* @see https://html.spec.whatwg.org/multipage/interaction.html#dom-document-activeelement
*/
Document.prototype.activeElement;
/**
* @see https://html.spec.whatwg.org/multipage/interaction.html#dom-document-hasfocus
* @return {boolean}
*/
Document.prototype.hasFocus = function() {};
/**
* @param {{preventScroll: boolean}=} options
* @return {undefined}
* @see https://html.spec.whatwg.org/multipage/interaction.html#dom-focus
*/
Element.prototype.focus = function(options) {};
/**
* @return {undefined}
* @see https://html.spec.whatwg.org/multipage/interaction.html#dom-blur
*/
Element.prototype.blur = function() {};
/**
* @see https://www.w3.org/TR/CSP3/#securitypolicyviolationevent
*
* @constructor
* @extends {Event}
*
* @param {string} type
* @param {SecurityPolicyViolationEventInit=}
* opt_securityPolicyViolationEventInitDict
*/
function SecurityPolicyViolationEvent(
type, opt_securityPolicyViolationEventInitDict) {}
/** @const {string} */
SecurityPolicyViolationEvent.prototype.documentURI;
/** @const {string} */
SecurityPolicyViolationEvent.prototype.referrer;
/** @const {string} */
SecurityPolicyViolationEvent.prototype.blockedURI;
/** @const {string} */
SecurityPolicyViolationEvent.prototype.effectiveDirective;
/** @const {string} */
SecurityPolicyViolationEvent.prototype.violatedDirective;
/** @const {string} */
SecurityPolicyViolationEvent.prototype.originalPolicy;
/** @const {string} */
SecurityPolicyViolationEvent.prototype.sourceFile;
/** @const {string} */
SecurityPolicyViolationEvent.prototype.sample;
/**
* @see https://www.w3.org/TR/CSP3/#enumdef-securitypolicyviolationeventdisposition
* @const {string}
*/
SecurityPolicyViolationEvent.prototype.disposition;
/** @const {number} */
SecurityPolicyViolationEvent.prototype.statusCode;
/** @const {number} */
SecurityPolicyViolationEvent.prototype.lineNumber;
/** @const {number} */
SecurityPolicyViolationEvent.prototype.columnNumber;
/**
* @record
* @extends {EventInit}
* @see https://www.w3.org/TR/CSP3/#dictdef-securitypolicyviolationeventinit
*/
function SecurityPolicyViolationEventInit() {}
/** @type {string} */
SecurityPolicyViolationEventInit.prototype.documentURI;
/** @type {undefined|string} */
SecurityPolicyViolationEventInit.prototype.referrer;
/** @type {undefined|string} */
SecurityPolicyViolationEventInit.prototype.blockedURI;
/** @type {string} */
SecurityPolicyViolationEventInit.prototype.disposition;
/** @type {string} */
SecurityPolicyViolationEventInit.prototype.effectiveDirective;
/** @type {string} */
SecurityPolicyViolationEventInit.prototype.violatedDirective;
/** @type {string} */
SecurityPolicyViolationEventInit.prototype.originalPolicy;
/** @type {undefined|string} */
SecurityPolicyViolationEventInit.prototype.sourceFile;
/** @type {undefined|string} */
SecurityPolicyViolationEventInit.prototype.sample;
/** @type {number} */
SecurityPolicyViolationEventInit.prototype.statusCode;
/** @type {undefined|number} */
SecurityPolicyViolationEventInit.prototype.lineNumber;
/** @type {undefined|number} */
SecurityPolicyViolationEventInit.prototype.columnNumber;
/**
* @see https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#formdataevent
*
* @constructor
* @extends {Event}
*
* @param {string} type
* @param {FormDataEventInit=} eventInitDict
*/
function FormDataEvent(type, eventInitDict) {}
/** @const {!FormData} */
FormDataEvent.prototype.formData;
/**
* @see https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#formdataeventinit
*
* @record
* @extends {EventInit}
*/
function FormDataEventInit() {}
/** @type {!FormData} */
FormDataEventInit.prototype.formData;
/**
* @see https://html.spec.whatwg.org/multipage/indices.html#event-formdata
* @type {?function(FormDataEvent)}
*/
HTMLFormElement.prototype.onformdata;
| Add crossOriginIsolated field to window
PiperOrigin-RevId: 413705617
| externs/browser/html5.js | Add crossOriginIsolated field to window | <ide><path>xterns/browser/html5.js
<ide> * @type {?function(FormDataEvent)}
<ide> */
<ide> HTMLFormElement.prototype.onformdata;
<add>
<add>/**
<add> * @const {boolean}
<add> * Whether the document has opted in to cross-origin isolation.
<add> * @see https://html.spec.whatwg.org/multipage/webappapis.html#dom-crossoriginisolated
<add> */
<add>Window.prototype.crossOriginIsolated; |
|
JavaScript | cc0-1.0 | 52fc17c90c9091dfea3f277138b3f33095e09b34 | 0 | iterami/SpeedButton.htm,iterami/SpeedButton.htm | 'use strict';
function click_button(clicked_button_id){
if(core_menu_open){
return;
}
core_audio_start({
'id': 'boop',
});
randomize_buttons(clicked_button_id);
}
function decisecond(){
if(!game_running){
return;
}
time = (core_storage_data['game-mode'] === 1
&& core_storage_data['max'] > 0)
? (Number.parseFloat(time) - .1).toFixed(1)
: (Number.parseFloat(time) + .1).toFixed(1);
document.getElementById('time').innerHTML = time;
// If in max-time mode and time is less than or equal to 0 and max-time isn't 0...
if(core_storage_data['game-mode'] === 1
&& time <= 0
&& core_storage_data['max'] > 0){
stop();
// ...else if in max-points mode and score is not greater than max-points and max-points is not equal to 0.
}else if(core_storage_data['game-mode'] === 0
&& core_storage_data['max'] !== 0
&& score >= core_storage_data['max']){
stop();
}
}
function randomize_buttons(clicked_button_id){
if(game_running){
// Stop game if clicking on a negative button ends the game and clicked on a negative button.
if(document.getElementById('negative-onclick').value == 1
&& document.getElementById(clicked_button_id).value.lastIndexOf('-', 0) === 0){
stop();
return;
}
}
// Increase or decrease time based on settings value for clicked button.
score = score
+ (document.getElementById(clicked_button_id).value.lastIndexOf('+', 0) === 0
? core_storage_data['positive-points']
: core_storage_data['negative-points']);
document.getElementById('score').innerHTML = score;
// Reset buttons to disabled, value=-, and black backgrounds if game has not ended with this click.
let game_ended = !(core_storage_data['game-mode'] === 1
|| core_storage_data['max'] === 0
|| score < core_storage_data['max']);
let loop_counter = grid_dimensions_squared - 1;
do{
let element = document.getElementById(loop_counter);
element.disabled = true;
if(game_ended){
continue;
}
element.style.background = '#2a2a2a';
element.value = ' ';
}while(loop_counter--);
if(game_ended){
return;
}
let space_taken = 0;
// Randomize locations of and setup positive buttons that currently exist.
if(core_storage_data['positive-frequency'] > 0){
loop_counter = core_storage_data['positive-frequency'] > grid_dimensions_squared - 1
? grid_dimensions_squared - 1
: core_storage_data['positive-frequency'] - 1;
space_taken = loop_counter + 1;
do{
let button = '';
do{
button = core_random_integer({
'max': grid_dimensions_squared,
});
}while(!document.getElementById(button).disabled);
let element = document.getElementById(button);
element.style.background = core_storage_data['color-positive'];
element.disabled = false;
element.value = core_storage_data['positive-points'] > 0
? '+'
: '-';
}while(loop_counter--);
}
// If there are no positive buttons or space for negative buttons is available.
if(core_storage_data['positive-frequency'] == 0
|| (core_storage_data['grid-dimensions'] > 1
&& grid_dimensions_squared - space_taken > 0)
){
// Create and randomize enough negative buttons to fill available space or just number of negative buttons.
loop_counter = core_storage_data['negative-frequency'] > grid_dimensions_squared - space_taken - 1
? grid_dimensions_squared - space_taken - 1
: core_storage_data['negative-frequency'] - 1;
if(loop_counter >= 0){
do{
let button = '';
do{
button = core_random_integer({
'max': grid_dimensions_squared,
});
}while(!document.getElementById(button).disabled);
let element = document.getElementById(button);
element.style.background = core_storage_data['color-negative'];
element.disabled = false;
element.value = core_storage_data['negative-points'] > 0
? '+'
: '-';
}while(loop_counter--);
}
}
}
function start(){
grid_dimensions_squared = Math.max(
core_storage_data['grid-dimensions'] * core_storage_data['grid-dimensions'],
1
);
// Create game-div buttons.
let output = '';
for(let loop_counter = 0; loop_counter < grid_dimensions_squared; loop_counter++){
if(loop_counter % core_storage_data['grid-dimensions'] === 0
&& loop_counter !== 0){
output += '<br>';
}
output += '<input class=gridbuttonclickable disabled id=' + loop_counter
+ ' onclick=click_button(' + loop_counter
+ ') type=button value=" ">';
}
document.getElementById('game-div').innerHTML = output + '<br>';
let loop_counter = grid_dimensions_squared - 1;
do{
document.getElementById(loop_counter).style.background = '#2a2a2a';
}while(loop_counter--);
// Reset game buttons.
loop_counter = grid_dimensions_squared - 1;
do{
let element = document.getElementById(loop_counter);
element.disabled = true;
element.style.background = '#2a2a2a';
element.value = ' ';
}while(loop_counter--);
document.getElementById('score-max').innerHTML = '';
document.getElementById('time-max').innerHTML = '';
// Generate positive and negative buttons.
randomize_buttons(
core_random_integer({
'max': grid_dimensions_squared,
})
);
score = 0;
time = 0;
document.getElementById('score').innerHTML = score;
document.getElementById('time').innerHTML = 0;
// Setup max-time or max-points displays.
if(core_storage_data['game-mode'] === 1){
time = core_storage_data['max'] >= 0
? (core_storage_data['max'] === ''
? 0
: core_storage_data['max']
)
: 30;
if(core_storage_data['max'] > 0){
document.getElementById('time-max').innerHTML = ' / ' + core_storage_data['max'];
}
}else if(core_storage_data['max'] > 0){
document.getElementById('score-max').innerHTML = ' / ' + core_storage_data['max'];
}
game_running = true;
core_interval_modify({
'id': 'interval',
'interval': 100,
'todo': decisecond,
});
}
function stop(){
core_interval_pause_all();
game_running = false;
// Disable buttons to prevent further clicks.
let loop_counter = grid_dimensions_squared - 1;
do{
document.getElementById(loop_counter).disabled = true;
}while(loop_counter--);
}
| js/data.js | 'use strict';
function click_button(clicked_button_id){
if(core_menu_open){
return;
}
core_audio_start({
'id': 'boop',
});
randomize_buttons(clicked_button_id);
}
function decisecond(){
time = (core_storage_data['game-mode'] === 1
&& core_storage_data['max'] > 0)
? (Number.parseFloat(time) - .1).toFixed(1)
: (Number.parseFloat(time) + .1).toFixed(1);
document.getElementById('time').innerHTML = time;
// If in max-time mode and time is less than or equal to 0 and max-time isn't 0...
if(core_storage_data['game-mode'] === 1
&& time <= 0
&& core_storage_data['max'] > 0){
stop();
// ...else if in max-points mode and score is not greater than max-points and max-points is not equal to 0.
}else if(core_storage_data['game-mode'] === 0
&& core_storage_data['max'] !== 0
&& score >= core_storage_data['max']){
stop();
}
}
function randomize_buttons(clicked_button_id){
if(game_running){
// Stop game if clicking on a negative button ends the game and clicked on a negative button.
if(document.getElementById('negative-onclick').value == 1
&& document.getElementById(clicked_button_id).value.lastIndexOf('-', 0) === 0){
stop();
return;
}
}
// Increase or decrease time based on settings value for clicked button.
score = score
+ (document.getElementById(clicked_button_id).value.lastIndexOf('+', 0) === 0
? core_storage_data['positive-points']
: core_storage_data['negative-points']);
document.getElementById('score').innerHTML = score;
// Reset buttons to disabled, value=-, and black backgrounds if game has not ended with this click.
let game_ended = !(core_storage_data['game-mode'] === 1
|| core_storage_data['max'] === 0
|| score < core_storage_data['max']);
let loop_counter = grid_dimensions_squared - 1;
do{
let element = document.getElementById(loop_counter);
element.disabled = true;
if(game_ended){
continue;
}
element.style.background = '#2a2a2a';
element.value = ' ';
}while(loop_counter--);
if(game_ended){
return;
}
let space_taken = 0;
// Randomize locations of and setup positive buttons that currently exist.
if(core_storage_data['positive-frequency'] > 0){
loop_counter = core_storage_data['positive-frequency'] > grid_dimensions_squared - 1
? grid_dimensions_squared - 1
: core_storage_data['positive-frequency'] - 1;
space_taken = loop_counter + 1;
do{
let button = '';
do{
button = core_random_integer({
'max': grid_dimensions_squared,
});
}while(!document.getElementById(button).disabled);
let element = document.getElementById(button);
element.style.background = core_storage_data['color-positive'];
element.disabled = false;
element.value = core_storage_data['positive-points'] > 0
? '+'
: '-';
}while(loop_counter--);
}
// If there are no positive buttons or space for negative buttons is available.
if(core_storage_data['positive-frequency'] == 0
|| (core_storage_data['grid-dimensions'] > 1
&& grid_dimensions_squared - space_taken > 0)
){
// Create and randomize enough negative buttons to fill available space or just number of negative buttons.
loop_counter = core_storage_data['negative-frequency'] > grid_dimensions_squared - space_taken - 1
? grid_dimensions_squared - space_taken - 1
: core_storage_data['negative-frequency'] - 1;
if(loop_counter >= 0){
do{
let button = '';
do{
button = core_random_integer({
'max': grid_dimensions_squared,
});
}while(!document.getElementById(button).disabled);
let element = document.getElementById(button);
element.style.background = core_storage_data['color-negative'];
element.disabled = false;
element.value = core_storage_data['negative-points'] > 0
? '+'
: '-';
}while(loop_counter--);
}
}
}
function start(){
grid_dimensions_squared = Math.max(
core_storage_data['grid-dimensions'] * core_storage_data['grid-dimensions'],
1
);
// Create game-div buttons.
let output = '';
for(let loop_counter = 0; loop_counter < grid_dimensions_squared; loop_counter++){
if(loop_counter % core_storage_data['grid-dimensions'] === 0
&& loop_counter !== 0){
output += '<br>';
}
output += '<input class=gridbuttonclickable disabled id=' + loop_counter
+ ' onclick=click_button(' + loop_counter
+ ') type=button value=" ">';
}
document.getElementById('game-div').innerHTML = output + '<br>';
let loop_counter = grid_dimensions_squared - 1;
do{
document.getElementById(loop_counter).style.background = '#2a2a2a';
}while(loop_counter--);
// Reset game buttons.
loop_counter = grid_dimensions_squared - 1;
do{
let element = document.getElementById(loop_counter);
element.disabled = true;
element.style.background = '#2a2a2a';
element.value = ' ';
}while(loop_counter--);
document.getElementById('score-max').innerHTML = '';
document.getElementById('time-max').innerHTML = '';
// Generate positive and negative buttons.
randomize_buttons(
core_random_integer({
'max': grid_dimensions_squared,
})
);
score = 0;
time = 0;
document.getElementById('score').innerHTML = score;
document.getElementById('time').innerHTML = 0;
// Setup max-time or max-points displays.
if(core_storage_data['game-mode'] === 1){
time = core_storage_data['max'] >= 0
? (core_storage_data['max'] === ''
? 0
: core_storage_data['max']
)
: 30;
if(core_storage_data['max'] > 0){
document.getElementById('time-max').innerHTML = ' / ' + core_storage_data['max'];
}
}else if(core_storage_data['max'] > 0){
document.getElementById('score-max').innerHTML = ' / ' + core_storage_data['max'];
}
game_running = true;
core_interval_modify({
'id': 'interval',
'interval': 100,
'todo': decisecond,
});
}
function stop(){
core_interval_pause_all();
game_running = false;
// Disable buttons to prevent further clicks.
let loop_counter = grid_dimensions_squared - 1;
do{
document.getElementById(loop_counter).disabled = true;
}while(loop_counter--);
}
| prevented timer from decreasing after game ends
| js/data.js | prevented timer from decreasing after game ends | <ide><path>s/data.js
<ide> }
<ide>
<ide> function decisecond(){
<add> if(!game_running){
<add> return;
<add> }
<add>
<ide> time = (core_storage_data['game-mode'] === 1
<ide> && core_storage_data['max'] > 0)
<ide> ? (Number.parseFloat(time) - .1).toFixed(1) |
|
Java | apache-2.0 | 02adb28c09a6d5a05a3458689a4444394966e7fd | 0 | davebarnes97/geode,masaki-yamakawa/geode,smanvi-pivotal/geode,jdeppe-pivotal/geode,masaki-yamakawa/geode,davinash/geode,smanvi-pivotal/geode,masaki-yamakawa/geode,shankarh/geode,deepakddixit/incubator-geode,jdeppe-pivotal/geode,davinash/geode,deepakddixit/incubator-geode,PurelyApplied/geode,davebarnes97/geode,deepakddixit/incubator-geode,pivotal-amurmann/geode,pivotal-amurmann/geode,davinash/geode,smgoller/geode,PurelyApplied/geode,jdeppe-pivotal/geode,davinash/geode,smanvi-pivotal/geode,PurelyApplied/geode,PurelyApplied/geode,smgoller/geode,smanvi-pivotal/geode,jdeppe-pivotal/geode,charliemblack/geode,charliemblack/geode,pivotal-amurmann/geode,davebarnes97/geode,pdxrunner/geode,deepakddixit/incubator-geode,deepakddixit/incubator-geode,deepakddixit/incubator-geode,masaki-yamakawa/geode,smgoller/geode,shankarh/geode,davebarnes97/geode,PurelyApplied/geode,pivotal-amurmann/geode,davebarnes97/geode,pdxrunner/geode,smgoller/geode,pdxrunner/geode,smanvi-pivotal/geode,masaki-yamakawa/geode,smgoller/geode,shankarh/geode,pdxrunner/geode,davebarnes97/geode,masaki-yamakawa/geode,shankarh/geode,jdeppe-pivotal/geode,shankarh/geode,charliemblack/geode,jdeppe-pivotal/geode,jdeppe-pivotal/geode,PurelyApplied/geode,charliemblack/geode,smgoller/geode,masaki-yamakawa/geode,PurelyApplied/geode,smgoller/geode,pdxrunner/geode,deepakddixit/incubator-geode,davinash/geode,davebarnes97/geode,charliemblack/geode,pdxrunner/geode,davinash/geode,pivotal-amurmann/geode,davinash/geode,pdxrunner/geode | /*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.apache.geode.internal.jta;
import static org.junit.Assert.*;
import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import javax.transaction.Status;
import org.apache.geode.GemFireException;
import org.apache.geode.cache.Cache;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.RegionShortcut;
import org.apache.geode.cache.client.ClientCache;
import org.apache.geode.cache.client.ClientCacheFactory;
import org.apache.geode.cache.client.ClientRegionShortcut;
import org.apache.geode.cache.server.CacheServer;
import org.apache.geode.internal.AvailablePortHelper;
import org.apache.geode.internal.cache.TXManagerImpl;
import org.apache.geode.internal.cache.TXStateProxyImpl;
import org.apache.geode.internal.cache.tx.ClientTXStateStub;
import org.apache.geode.internal.logging.LogService;
import org.apache.geode.test.dunit.Assert;
import org.apache.geode.test.dunit.Host;
import org.apache.geode.test.dunit.VM;
import org.apache.geode.test.dunit.cache.internal.JUnit4CacheTestCase;
import org.apache.geode.test.junit.categories.DistributedTest;
import org.awaitility.Awaitility;
import org.junit.Test;
import org.junit.experimental.categories.Category;
@Category({DistributedTest.class})
public class ClientServerJTADUnitTest extends JUnit4CacheTestCase {
private String key = "key";
private String value = "value";
private String newValue = "newValue";
final Host host = Host.getHost(0);
final VM server = host.getVM(0);
final VM client = host.getVM(1);
@Test
public void testClientTXStateStubBeforeCompletion() throws Exception {
final String regionName = getUniqueName();
getBlackboard().initBlackboard();
final Properties properties = getDistributedSystemProperties();
final int port = server.invoke("create cache", () -> {
Cache cache = getCache(properties);
CacheServer cacheServer = createCacheServer(cache, 0);
Region region = cache.createRegionFactory(RegionShortcut.REPLICATE).create(regionName);
region.put(key, value);
return cacheServer.getPort();
});
client.invoke(() -> createClientRegion(host, port, regionName));
createClientRegion(host, port, regionName);
Region region = getCache().getRegion(regionName);
assertTrue(region.get(key).equals(value));
String first = "one";
String second = "two";
client.invokeAsync(() -> commitTxWithBeforeCompletion(regionName, true, first, second));
getBlackboard().waitForGate(first, 30, TimeUnit.SECONDS);
TXManagerImpl mgr = (TXManagerImpl) getCache().getCacheTransactionManager();
mgr.begin();
region.put(key, newValue);
TXStateProxyImpl tx = (TXStateProxyImpl) mgr.internalSuspend();
ClientTXStateStub txStub = (ClientTXStateStub) tx.getRealDeal(null, null);
mgr.internalResume(tx);
try {
txStub.beforeCompletion();
fail("expected to get CommitConflictException");
} catch (GemFireException e) {
// expected commit conflict exception thrown from server
mgr.setTXState(null);
getBlackboard().signalGate(second);
}
// GEODE commit apply the tx change to cache before releasing the locks held, so
// the region could have the new value but still hold the locks.
// Add the wait to check new JTA tx can be committed.
Awaitility.await().pollInterval(10, TimeUnit.MILLISECONDS).pollDelay(10, TimeUnit.MILLISECONDS)
.atMost(30, TimeUnit.SECONDS).until(() -> ableToCommitNewTx(regionName, mgr));
}
private boolean expectionLogged = false;
private boolean ableToCommitNewTx(final String regionName, TXManagerImpl mgr) {
try {
commitTxWithBeforeCompletion(regionName, false, null, null);
} catch (Exception e) {
if (!expectionLogged) {
LogService.getLogger().info("got exception stack trace", e);
expectionLogged = true;
}
mgr.setTXState(null);
return false;
}
return true;
}
private CacheServer createCacheServer(Cache cache, int maxThreads) {
CacheServer server = cache.addCacheServer();
server.setMaxThreads(maxThreads);
server.setPort(AvailablePortHelper.getRandomAvailableTCPPort());
try {
server.start();
} catch (IOException e) {
Assert.fail("got exception", e);
}
return server;
}
private void createClientRegion(final Host host, final int port0, String regionName) {
ClientCacheFactory cf = new ClientCacheFactory();
cf.addPoolServer(host.getHostName(), port0);
ClientCache cache = getClientCache(cf);
cache.createClientRegionFactory(ClientRegionShortcut.PROXY).create(regionName);
}
private void commitTxWithBeforeCompletion(String regionName, boolean withWait, String first,
String second) throws TimeoutException, InterruptedException {
Region region = getCache().getRegion(regionName);
TXManagerImpl mgr = (TXManagerImpl) getCache().getCacheTransactionManager();
mgr.begin();
region.put(key, newValue);
TXStateProxyImpl tx = (TXStateProxyImpl) mgr.internalSuspend();
ClientTXStateStub txStub = (ClientTXStateStub) tx.getRealDeal(null, null);
mgr.internalResume(tx);
txStub.beforeCompletion();
if (withWait) {
getBlackboard().signalGate(first);
getBlackboard().waitForGate(second, 30, TimeUnit.SECONDS);
}
txStub.afterCompletion(Status.STATUS_COMMITTED);
}
@Test
public void testJTAMaxThreads() throws TimeoutException, InterruptedException {
testJTAWithMaxThreads(1);
}
@Test
public void testJTANoMaxThreadsSetting() throws TimeoutException, InterruptedException {
testJTAWithMaxThreads(0);
}
private void testJTAWithMaxThreads(int maxThreads) {
final String regionName = getUniqueName();
getBlackboard().initBlackboard();
final Properties properties = getDistributedSystemProperties();
final int port = server.invoke("create cache", () -> {
Cache cache = getCache(properties);
CacheServer cacheServer = createCacheServer(cache, maxThreads);
Region region = cache.createRegionFactory(RegionShortcut.REPLICATE).create(regionName);
region.put(key, value);
return cacheServer.getPort();
});
createClientRegion(host, port, regionName);
Region region = getCache().getRegion(regionName);
assertTrue(region.get(key).equals(value));
try {
commitTxWithBeforeCompletion(regionName, false, null, null);
} catch (Exception e) {
Assert.fail("got unexpected exception", e);
}
assertTrue(region.get(key).equals(newValue));
}
}
| geode-core/src/test/java/org/apache/geode/internal/jta/ClientServerJTADUnitTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.apache.geode.internal.jta;
import static org.junit.Assert.*;
import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import javax.transaction.Status;
import org.apache.geode.GemFireException;
import org.apache.geode.cache.Cache;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.RegionShortcut;
import org.apache.geode.cache.client.ClientCache;
import org.apache.geode.cache.client.ClientCacheFactory;
import org.apache.geode.cache.client.ClientRegionShortcut;
import org.apache.geode.cache.server.CacheServer;
import org.apache.geode.internal.AvailablePortHelper;
import org.apache.geode.internal.cache.TXManagerImpl;
import org.apache.geode.internal.cache.TXStateProxyImpl;
import org.apache.geode.internal.cache.tx.ClientTXStateStub;
import org.apache.geode.test.dunit.Assert;
import org.apache.geode.test.dunit.Host;
import org.apache.geode.test.dunit.VM;
import org.apache.geode.test.dunit.cache.internal.JUnit4CacheTestCase;
import org.apache.geode.test.junit.categories.DistributedTest;
import org.awaitility.Awaitility;
import org.junit.Test;
import org.junit.experimental.categories.Category;
@Category({DistributedTest.class})
public class ClientServerJTADUnitTest extends JUnit4CacheTestCase {
private String key = "key";
private String value = "value";
private String newValue = "newValue";
final Host host = Host.getHost(0);
final VM server = host.getVM(0);
final VM client = host.getVM(1);
@Test
public void testClientTXStateStubBeforeCompletion() throws Exception {
final String regionName = getUniqueName();
getBlackboard().initBlackboard();
final Properties properties = getDistributedSystemProperties();
final int port = server.invoke("create cache", () -> {
Cache cache = getCache(properties);
CacheServer cacheServer = createCacheServer(cache, 0);
Region region = cache.createRegionFactory(RegionShortcut.REPLICATE).create(regionName);
region.put(key, value);
return cacheServer.getPort();
});
client.invoke(() -> createClientRegion(host, port, regionName));
createClientRegion(host, port, regionName);
Region region = getCache().getRegion(regionName);
assertTrue(region.get(key).equals(value));
String first = "one";
String second = "two";
client.invokeAsync(() -> commitTxWithBeforeCompletion(regionName, true, first, second));
getBlackboard().waitForGate(first, 30, TimeUnit.SECONDS);
TXManagerImpl mgr = (TXManagerImpl) getCache().getCacheTransactionManager();
mgr.begin();
region.put(key, newValue);
TXStateProxyImpl tx = (TXStateProxyImpl) mgr.internalSuspend();
ClientTXStateStub txStub = (ClientTXStateStub) tx.getRealDeal(null, null);
mgr.internalResume(tx);
try {
txStub.beforeCompletion();
fail("expected to get CommitConflictException");
} catch (GemFireException e) {
// expected commit conflict exception thrown from server
mgr.setTXState(null);
getBlackboard().signalGate(second);
}
Awaitility.await().pollInterval(10, TimeUnit.MILLISECONDS).pollDelay(10, TimeUnit.MILLISECONDS)
.atMost(30, TimeUnit.SECONDS).until(() -> region.get(key).equals(newValue));
try {
commitTxWithBeforeCompletion(regionName, false, first, second);
} catch (Exception e) {
Assert.fail("got unexpected exception", e);
}
}
private CacheServer createCacheServer(Cache cache, int maxThreads) {
CacheServer server = cache.addCacheServer();
server.setMaxThreads(maxThreads);
server.setPort(AvailablePortHelper.getRandomAvailableTCPPort());
try {
server.start();
} catch (IOException e) {
Assert.fail("got exception", e);
}
return server;
}
private void createClientRegion(final Host host, final int port0, String regionName) {
ClientCacheFactory cf = new ClientCacheFactory();
cf.addPoolServer(host.getHostName(), port0);
ClientCache cache = getClientCache(cf);
cache.createClientRegionFactory(ClientRegionShortcut.PROXY).create(regionName);
}
private void commitTxWithBeforeCompletion(String regionName, boolean withWait, String first,
String second) throws TimeoutException, InterruptedException {
Region region = getCache().getRegion(regionName);
TXManagerImpl mgr = (TXManagerImpl) getCache().getCacheTransactionManager();
mgr.begin();
region.put(key, newValue);
TXStateProxyImpl tx = (TXStateProxyImpl) mgr.internalSuspend();
ClientTXStateStub txStub = (ClientTXStateStub) tx.getRealDeal(null, null);
mgr.internalResume(tx);
txStub.beforeCompletion();
if (withWait) {
getBlackboard().signalGate(first);
getBlackboard().waitForGate(second, 30, TimeUnit.SECONDS);
}
txStub.afterCompletion(Status.STATUS_COMMITTED);
}
@Test
public void testJTAMaxThreads() throws TimeoutException, InterruptedException {
testJTAWithMaxThreads(1);
}
@Test
public void testJTANoMaxThreadsSetting() throws TimeoutException, InterruptedException {
testJTAWithMaxThreads(0);
}
private void testJTAWithMaxThreads(int maxThreads) {
final String regionName = getUniqueName();
getBlackboard().initBlackboard();
final Properties properties = getDistributedSystemProperties();
final int port = server.invoke("create cache", () -> {
Cache cache = getCache(properties);
CacheServer cacheServer = createCacheServer(cache, maxThreads);
Region region = cache.createRegionFactory(RegionShortcut.REPLICATE).create(regionName);
region.put(key, value);
return cacheServer.getPort();
});
createClientRegion(host, port, regionName);
Region region = getCache().getRegion(regionName);
assertTrue(region.get(key).equals(value));
try {
commitTxWithBeforeCompletion(regionName, false, null, null);
} catch (Exception e) {
Assert.fail("got unexpected exception", e);
}
assertTrue(region.get(key).equals(newValue));
}
}
| GEODE-3178: Fix a flaky JTA test by adding retry.
| geode-core/src/test/java/org/apache/geode/internal/jta/ClientServerJTADUnitTest.java | GEODE-3178: Fix a flaky JTA test by adding retry. | <ide><path>eode-core/src/test/java/org/apache/geode/internal/jta/ClientServerJTADUnitTest.java
<ide> import org.apache.geode.internal.cache.TXManagerImpl;
<ide> import org.apache.geode.internal.cache.TXStateProxyImpl;
<ide> import org.apache.geode.internal.cache.tx.ClientTXStateStub;
<add>import org.apache.geode.internal.logging.LogService;
<ide> import org.apache.geode.test.dunit.Assert;
<ide> import org.apache.geode.test.dunit.Host;
<ide> import org.apache.geode.test.dunit.VM;
<ide> getBlackboard().signalGate(second);
<ide> }
<ide>
<add> // GEODE commit apply the tx change to cache before releasing the locks held, so
<add> // the region could have the new value but still hold the locks.
<add> // Add the wait to check new JTA tx can be committed.
<ide> Awaitility.await().pollInterval(10, TimeUnit.MILLISECONDS).pollDelay(10, TimeUnit.MILLISECONDS)
<del> .atMost(30, TimeUnit.SECONDS).until(() -> region.get(key).equals(newValue));
<add> .atMost(30, TimeUnit.SECONDS).until(() -> ableToCommitNewTx(regionName, mgr));
<add> }
<ide>
<add> private boolean expectionLogged = false;
<add>
<add> private boolean ableToCommitNewTx(final String regionName, TXManagerImpl mgr) {
<ide> try {
<del> commitTxWithBeforeCompletion(regionName, false, first, second);
<add> commitTxWithBeforeCompletion(regionName, false, null, null);
<ide> } catch (Exception e) {
<del> Assert.fail("got unexpected exception", e);
<add> if (!expectionLogged) {
<add> LogService.getLogger().info("got exception stack trace", e);
<add> expectionLogged = true;
<add> }
<add> mgr.setTXState(null);
<add> return false;
<ide> }
<add> return true;
<ide> }
<ide>
<ide> private CacheServer createCacheServer(Cache cache, int maxThreads) { |
|
Java | apache-2.0 | 8827f6a3b7eab347b24090545ce91517efcd1e72 | 0 | real-logic/Aeron,mikeb01/Aeron,oleksiyp/Aeron,real-logic/Aeron,mikeb01/Aeron,galderz/Aeron,mikeb01/Aeron,EvilMcJerkface/Aeron,oleksiyp/Aeron,oleksiyp/Aeron,galderz/Aeron,EvilMcJerkface/Aeron,galderz/Aeron,EvilMcJerkface/Aeron,real-logic/Aeron,mikeb01/Aeron,EvilMcJerkface/Aeron,real-logic/Aeron,galderz/Aeron | /*
* Copyright 2014 - 2017 Real Logic Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package io.aeron.archiver;
import io.aeron.ExclusivePublication;
import io.aeron.archiver.codecs.*;
import io.aeron.logbuffer.ExclusiveBufferClaim;
import org.agrona.*;
import org.agrona.concurrent.UnsafeBuffer;
import java.io.IOException;
import java.nio.ByteBuffer;
import static org.agrona.BitUtil.CACHE_LINE_LENGTH;
class ListRecordingsSession implements ArchiveConductor.Session
{
private static final int HEADER_LENGTH = MessageHeaderEncoder.ENCODED_LENGTH;
private static final long NOT_FOUND_HEADER;
private static final long DESCRIPTOR_HEADER;
static
{
// TODO: How will this cope on a Big Endian machine?
// create constant header values to avoid recalculation on each message sent
final MessageHeaderEncoder encoder = new MessageHeaderEncoder();
encoder.wrap(new UnsafeBuffer(new byte[HEADER_LENGTH]), 0);
encoder.schemaId(RecordingNotFoundResponseEncoder.SCHEMA_ID);
encoder.version(RecordingNotFoundResponseEncoder.SCHEMA_VERSION);
encoder.blockLength(RecordingNotFoundResponseEncoder.BLOCK_LENGTH);
encoder.templateId(RecordingNotFoundResponseEncoder.TEMPLATE_ID);
NOT_FOUND_HEADER = encoder.buffer().getLong(0);
encoder.schemaId(RecordingDescriptorEncoder.SCHEMA_ID);
encoder.version(RecordingDescriptorEncoder.SCHEMA_VERSION);
encoder.blockLength(RecordingDescriptorEncoder.BLOCK_LENGTH);
encoder.templateId(RecordingDescriptorEncoder.TEMPLATE_ID);
DESCRIPTOR_HEADER = encoder.buffer().getLong(0);
}
private enum State
{
INIT,
SENDING,
CLOSE,
DONE
}
private final ByteBuffer byteBuffer =
BufferUtil.allocateDirectAligned(Catalog.RECORD_LENGTH, CACHE_LINE_LENGTH);
private final UnsafeBuffer unsafeBuffer = new UnsafeBuffer(byteBuffer);
private final ExclusiveBufferClaim bufferClaim = new ExclusiveBufferClaim();
private final ExclusivePublication reply;
private final int fromId;
private final int toId;
private final Catalog index;
private final ClientSessionProxy proxy;
private final int correlationId;
private int recordingId;
private State state = State.INIT;
ListRecordingsSession(
final int correlationId, final ExclusivePublication reply,
final int fromId,
final int toId,
final Catalog index,
final ClientSessionProxy proxy)
{
this.reply = reply;
recordingId = fromId;
this.fromId = fromId;
this.toId = toId;
this.index = index;
this.proxy = proxy;
this.correlationId = correlationId;
}
public void abort()
{
state = State.CLOSE;
}
public boolean isDone()
{
return state == State.DONE;
}
public void remove(final ArchiveConductor conductor)
{
}
public int doWork()
{
int workDone = 0;
switch (state)
{
case INIT:
workDone += init();
break;
case SENDING:
workDone += sendDescriptors();
break;
case CLOSE:
workDone += close();
break;
}
return workDone;
}
private int close()
{
state = State.DONE;
return 1;
}
private int sendDescriptors()
{
final int limit = Math.min(recordingId + 4, toId);
for (; recordingId <= limit; recordingId++)
{
final RecordingSession session = index.getRecordingSession(recordingId);
if (session == null)
{
byteBuffer.clear();
unsafeBuffer.wrap(byteBuffer);
try
{
if (!index.readDescriptor(recordingId, byteBuffer))
{
// return relevant error
if (reply.tryClaim(
HEADER_LENGTH + RecordingNotFoundResponseDecoder.BLOCK_LENGTH, bufferClaim) > 0L)
{
final MutableDirectBuffer buffer = bufferClaim.buffer();
final int offset = bufferClaim.offset();
buffer.putLong(offset, NOT_FOUND_HEADER);
buffer.putInt(offset + 8, recordingId);
buffer.putInt(offset + 12, index.maxRecordingId());
buffer.putInt(offset + 16, correlationId);
bufferClaim.commit();
state = State.CLOSE;
}
return 0;
}
}
catch (final IOException ex)
{
state = State.CLOSE;
LangUtil.rethrowUnchecked(ex);
}
}
else
{
unsafeBuffer.wrap(session.metaDataBuffer());
}
final int length = unsafeBuffer.getInt(0);
unsafeBuffer.putLong(Catalog.CATALOG_FRAME_LENGTH - HEADER_LENGTH, DESCRIPTOR_HEADER);
unsafeBuffer.putInt(
Catalog.CATALOG_FRAME_LENGTH + RecordingDescriptorDecoder.correlationIdEncodingOffset(),
correlationId);
reply.offer(unsafeBuffer, Catalog.CATALOG_FRAME_LENGTH - HEADER_LENGTH, length + HEADER_LENGTH);
}
if (recordingId > toId)
{
state = State.CLOSE;
}
return 1;
}
private int init()
{
if (fromId > toId)
{
proxy.sendResponse(reply, "Requested range is reversed (to < from)", correlationId);
state = State.CLOSE;
}
else if (toId > index.maxRecordingId())
{
proxy.sendResponse(reply, "Requested range exceeds available range (to > max)", correlationId);
state = State.CLOSE;
}
else
{
state = State.SENDING;
}
return 1;
}
}
| aeron-archiver/src/main/java/io/aeron/archiver/ListRecordingsSession.java | /*
* Copyright 2014 - 2017 Real Logic Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package io.aeron.archiver;
import io.aeron.ExclusivePublication;
import io.aeron.archiver.codecs.*;
import io.aeron.logbuffer.ExclusiveBufferClaim;
import org.agrona.*;
import org.agrona.concurrent.UnsafeBuffer;
import java.io.IOException;
import java.nio.ByteBuffer;
import static org.agrona.BitUtil.CACHE_LINE_LENGTH;
class ListRecordingsSession implements ArchiveConductor.Session
{
private static final int HEADER_LENGTH = MessageHeaderEncoder.ENCODED_LENGTH;
private static final long NOT_FOUND_HEADER;
private static final long DESCRIPTOR_HEADER;
static
{
// create constant header values to avoid recalculation on each message sent
final MessageHeaderEncoder encoder = new MessageHeaderEncoder();
encoder.wrap(new UnsafeBuffer(new byte[HEADER_LENGTH]), 0);
encoder.schemaId(RecordingNotFoundResponseEncoder.SCHEMA_ID);
encoder.version(RecordingNotFoundResponseEncoder.SCHEMA_VERSION);
encoder.blockLength(RecordingNotFoundResponseEncoder.BLOCK_LENGTH);
encoder.templateId(RecordingNotFoundResponseEncoder.TEMPLATE_ID);
NOT_FOUND_HEADER = encoder.buffer().getLong(0);
encoder.schemaId(RecordingDescriptorEncoder.SCHEMA_ID);
encoder.version(RecordingDescriptorEncoder.SCHEMA_VERSION);
encoder.blockLength(RecordingDescriptorEncoder.BLOCK_LENGTH);
encoder.templateId(RecordingDescriptorEncoder.TEMPLATE_ID);
DESCRIPTOR_HEADER = encoder.buffer().getLong(0);
}
private enum State
{
INIT,
SENDING,
CLOSE,
DONE
}
private final ByteBuffer byteBuffer =
BufferUtil.allocateDirectAligned(Catalog.RECORD_LENGTH, CACHE_LINE_LENGTH);
private final UnsafeBuffer unsafeBuffer = new UnsafeBuffer(byteBuffer);
private final ExclusiveBufferClaim bufferClaim = new ExclusiveBufferClaim();
private final ExclusivePublication reply;
private final int fromId;
private final int toId;
private final Catalog index;
private final ClientSessionProxy proxy;
private final int correlationId;
private int recordingId;
private State state = State.INIT;
ListRecordingsSession(
final int correlationId, final ExclusivePublication reply,
final int fromId,
final int toId,
final Catalog index,
final ClientSessionProxy proxy)
{
this.reply = reply;
recordingId = fromId;
this.fromId = fromId;
this.toId = toId;
this.index = index;
this.proxy = proxy;
this.correlationId = correlationId;
}
public void abort()
{
state = State.CLOSE;
}
public boolean isDone()
{
return state == State.DONE;
}
public void remove(final ArchiveConductor conductor)
{
}
public int doWork()
{
int workDone = 0;
switch (state)
{
case INIT:
workDone += init();
break;
case SENDING:
workDone += sendDescriptors();
break;
case CLOSE:
workDone += close();
break;
}
return workDone;
}
private int close()
{
state = State.DONE;
return 1;
}
private int sendDescriptors()
{
final int limit = Math.min(recordingId + 4, toId);
for (; recordingId <= limit; recordingId++)
{
final RecordingSession session = index.getRecordingSession(recordingId);
if (session == null)
{
byteBuffer.clear();
unsafeBuffer.wrap(byteBuffer);
try
{
if (!index.readDescriptor(recordingId, byteBuffer))
{
// return relevant error
if (reply.tryClaim(
HEADER_LENGTH + RecordingNotFoundResponseDecoder.BLOCK_LENGTH, bufferClaim) > 0L)
{
final MutableDirectBuffer buffer = bufferClaim.buffer();
final int offset = bufferClaim.offset();
buffer.putLong(offset, NOT_FOUND_HEADER);
buffer.putInt(offset + 8, recordingId);
buffer.putInt(offset + 12, index.maxRecordingId());
buffer.putInt(offset + 16, correlationId);
bufferClaim.commit();
state = State.CLOSE;
}
return 0;
}
}
catch (final IOException ex)
{
state = State.CLOSE;
LangUtil.rethrowUnchecked(ex);
}
}
else
{
unsafeBuffer.wrap(session.metaDataBuffer());
}
final int length = unsafeBuffer.getInt(0);
unsafeBuffer.putLong(Catalog.CATALOG_FRAME_LENGTH - HEADER_LENGTH, DESCRIPTOR_HEADER);
unsafeBuffer.putInt(
Catalog.CATALOG_FRAME_LENGTH + RecordingDescriptorDecoder.correlationIdEncodingOffset(),
correlationId);
reply.offer(unsafeBuffer, Catalog.CATALOG_FRAME_LENGTH - HEADER_LENGTH, length + HEADER_LENGTH);
}
if (recordingId > toId)
{
state = State.CLOSE;
}
return 1;
}
private int init()
{
if (fromId > toId)
{
proxy.sendResponse(reply, "Requested range is reversed (to < from)", correlationId);
state = State.CLOSE;
}
else if (toId > index.maxRecordingId())
{
proxy.sendResponse(reply, "Requested range exceeds available range (to > max)", correlationId);
state = State.CLOSE;
}
else
{
state = State.SENDING;
}
return 1;
}
}
| [Java] Add TODO.
| aeron-archiver/src/main/java/io/aeron/archiver/ListRecordingsSession.java | [Java] Add TODO. | <ide><path>eron-archiver/src/main/java/io/aeron/archiver/ListRecordingsSession.java
<ide>
<ide> static
<ide> {
<add> // TODO: How will this cope on a Big Endian machine?
<add>
<ide> // create constant header values to avoid recalculation on each message sent
<ide> final MessageHeaderEncoder encoder = new MessageHeaderEncoder();
<ide> encoder.wrap(new UnsafeBuffer(new byte[HEADER_LENGTH]), 0); |
|
JavaScript | mit | 283147f57588b5172497dfad9791d046e87a24d3 | 0 | mjec/rc-niceties,mjec/rc-niceties,mjec/rc-niceties | import React from 'react';
import $ from 'jquery';
import SaveButton from './SaveButton';
const AdminNicety = React.createClass({
getInitialState: function() {
return {
text: this.props.nicety.text,
noSave: true
};
},
saveNicety: function() {
const data = {
text: this.state.text,
author_id: this.props.nicety.author_id,
target_id: this.props.target_id
}
$.ajax({
url: this.props.admin_edit_api,
data: data,
dataType: 'json',
type: 'POST',
cache: false,
success: function() {
this.setState({noSave: true});
}.bind(this),
error: function(xhr, status, err) {
console.log(err)
}
});
},
textareaChange: function(event) {
this.setState({ text: event.target.value , noSave: false });
},
render: function() {
let nicetyName;
if ('name' in this.props.nicety) {
nicetyName = this.props.nicety.name;
} else {
nicetyName = 'Anonymous';
}
let noRead = null;
if (this.props.nicety.no_read === true) {
noRead = "Don't Read At Ceremony, Please";
}
let nicetyReturn = null;
if (this.props.nicety.text !== '' && this.props.nicety.text !== null) {
const textStyle = {
width: '75%'
}
nicetyReturn = (
<div>
<h4>From {nicetyName}</h4>
<h5>{noRead}</h5>
<textarea
defaultValue={this.state.text}
onChange={this.textareaChange}
rows="6"
style={textStyle} />
<SaveButton
noSave={this.state.noSave}
onClick={this.saveNicety}>
Save
</SaveButton>
<br />
</div>
);
}
return nicetyReturn;
}
});
export default AdminNicety;
| src/components/AdminNicety.js | import React from 'react';
import $ from 'jquery';
import SaveButton from './SaveButton';
const AdminNicety = React.createClass({
getInitialState: function() {
return {
text: this.props.nicety.text,
noSave: true
};
},
saveNicety: function() {
const data = {
text: this.state.text,
author_id: this.props.nicety.author_id,
target_id: this.props.target_id
}
$.ajax({
url: this.props.admin_edit_api,
data: data,
dataType: 'json',
type: 'POST',
cache: false,
success: function() {
this.setState({noSave: true});
}.bind(this),
error: function(xhr, status, err) {
console.log(err)
}
});
},
textareaChange: function() {
this.setState({ text: event.target.value , noSave: false });
},
render: function() {
let nicetyName;
if ('name' in this.props.nicety) {
nicetyName = this.props.nicety.name;
} else {
nicetyName = 'Anonymous';
}
let noRead = null;
if (this.props.nicety.no_read === true) {
noRead = "Don't Read At Ceremony, Please";
}
let nicetyReturn = null;
if (this.props.nicety.text !== '' && this.props.nicety.text !== null) {
const textStyle = {
width: '75%'
}
nicetyReturn = (
<div>
<h4>From {nicetyName}</h4>
<h5>{noRead}</h5>
<textarea
defaultValue={this.state.text}
onChange={this.textareaChange}
rows="6"
style={textStyle} />
<SaveButton
noSave={this.state.noSave}
onClick={this.saveNicety}>
Save
</SaveButton>
<br />
</div>
);
}
return nicetyReturn;
}
});
export default AdminNicety;
| Add explicit event argument to handler
The onChange handler for <AdminNicety> was missing its event argument,
and instead used the current event via the global event. This works, but
is fairly surprising behavior, and a future version[1] of react-scripts
will stop the build on encountering a no-restricted-globals[2] linter
error. The documentation for this error specifically calls this
situation out:
For instance, early Internet Explorer versions exposed the current
DOM event as a global variable event, but using this variable has
been considered as a bad practice for a long time. Restricting this
will make sure this variable isn't used in browser code.
Add the event argument to the function definition, so that the variable
referred to is the passed-in argument rather than the global.
[1] https://github.com/facebook/create-react-app/blob/master/CHANGELOG-1.x.md#confusing-window-globals-can-no-longer-be-used-without-window-qualifier
[2] https://eslint.org/docs/rules/no-restricted-globals
Issue #18 Upgrade React
| src/components/AdminNicety.js | Add explicit event argument to handler | <ide><path>rc/components/AdminNicety.js
<ide> });
<ide> },
<ide>
<del> textareaChange: function() {
<add> textareaChange: function(event) {
<ide> this.setState({ text: event.target.value , noSave: false });
<ide> },
<ide> |
|
JavaScript | apache-2.0 | a225f8ab2e6888ec30f5afd087b455b36066a68e | 0 | jmnarloch/falcor-router,jontewks/falcor-router,mitel/falcor-router,kristianmandrup/falcor-router,trxcllnt/falcor-router,osxi/falcor-router,drager/falcor-router,michaelbpaulson/falcor-router,Netflix/falcor-router | var convertPathToVirtual = require('./convertPathToVirtual');
function createNamedVariables(virtualPath, action) {
// TODO: do this
return function(matchedPath) {
var convertedPath = convertPathToVirtual(matchedPath, virtualPath);
return action.call(this, convertedPath);
};
}
module.exports = createNamedVariables;
| src/parse-tree/actionWrapper.js | var convertPathToVirtual = require('./convertPathToVirtual');
function createNamedVariables(virtualPath, action) {
// TODO: do this
return function(matchedPath) {
var convertedPath = convertPathToVirtual(matchedPath, virtualPath);
return action(convertedPath);
};
}
module.exports = createNamedVariables;
| Ensure route handlers are bound to router instance
Reviewed by J Husain | src/parse-tree/actionWrapper.js | Ensure route handlers are bound to router instance | <ide><path>rc/parse-tree/actionWrapper.js
<ide> // TODO: do this
<ide> return function(matchedPath) {
<ide> var convertedPath = convertPathToVirtual(matchedPath, virtualPath);
<del> return action(convertedPath);
<add> return action.call(this, convertedPath);
<ide> };
<ide> }
<ide> module.exports = createNamedVariables; |
|
Java | mit | 27bc9508aabf40054d69769736c97507d49df988 | 0 | bryanjswift/simplenote-android | package com.bryanjswift.simplenote.widget;
import android.app.Activity;
import android.app.ProgressDialog;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;
import com.bryanjswift.simplenote.Constants;
import com.bryanjswift.simplenote.Preferences;
import com.bryanjswift.simplenote.R;
import com.bryanjswift.simplenote.net.Api;
import com.bryanjswift.simplenote.net.Api.Response;
import com.bryanjswift.simplenote.net.HttpCallback;
import com.bryanjswift.simplenote.net.SimpleNoteApi;
import com.bryanjswift.simplenote.thread.LoginTask;
/**
* OnEditorActionListener and OnClickListener to handle logging in from SimpleNoteSplash screen
* @author bryanjswift
*/
public class LoginActionListener implements OnEditorActionListener, View.OnClickListener {
private static final String LOGGING_TAG = Constants.TAG + "LoginActionListener";
private final Activity context;
private final EditText email;
private final EditText password;
private final String loggingIn;
private final String authenticating;
private final HttpCallback callback;
/**
* Create an Listener to handle login actions
* @param context for the login action
* @param email text view containing email address information
* @param password text view containing password information
*/
public LoginActionListener(Activity context, EditText email, EditText password) {
this(context, email, password, null);
}
/**
* Create an Listener to handle login actions
* @param context for the login action
* @param email text view containing email address information
* @param password text view containing password information
* @param callback to run after those supplied by the Login action
*/
public LoginActionListener(Activity context, EditText email, EditText password, HttpCallback callback) {
this.context = context;
this.email = email;
this.password = password;
this.authenticating = context.getString(R.string.status_authenticating);
this.loggingIn = context.getString(R.string.status_loggingin);
this.callback = callback;
}
/**
* @see android.widget.TextView.OnEditorActionListener#onEditorAction(android.widget.TextView, int, android.view.KeyEvent)
*/
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
validateAndLogin();
return true;
}
/**
* @see android.view.View.OnClickListener#onClick(android.view.View)
*/
public void onClick(View v) {
validateAndLogin();
}
/**
* Attempt login only if information in fields is valid
*/
private void validateAndLogin() {
if (isValid()) {
login();
}
}
/**
* Check if the login fields are filled out and valid
* @return true if email and password both have values
*/
private boolean isValid() {
final String emailValue = email.getText().toString();
final String passwordValue = password.getText().toString();
boolean valid = true;
if (emailValue == null || emailValue.equals("") || passwordValue == null || passwordValue.equals("")) {
Toast.makeText(context, R.string.error_empty, Toast.LENGTH_LONG).show();
valid = false;
}
return valid;
}
/**
* Handle the process of logging a user in when they perform an action that justifies it
*/
private void login() {
Log.i(LOGGING_TAG, "Checking credentials and attempting login");
final String emailValue = email.getText().toString();
final String passwordValue = password.getText().toString();
final ProgressDialog dialog = ProgressDialog.show(context, loggingIn, authenticating);
Log.d(LOGGING_TAG, "Created progressDialog: " + dialog.toString());
final Api.Credentials credentials = Preferences.setLoginPreferences(context, emailValue, passwordValue);
// Login with credentials here
(new LoginTask(context, credentials, new HttpCallback() {
/**
* @see com.bryanjswift.simplenote.net.HttpCallback#on200(com.bryanjswift.simplenote.net.Api.Response)
*/
@Override
public void on200(Response response) {
dialog.dismiss();
}
/**
* @see com.bryanjswift.simplenote.net.HttpCallback#onError(com.bryanjswift.simplenote.net.Api.Response)
*/
@Override
public void onError(Response response) {
if (response.status == Constants.NO_CONNECTION) {
Toast.makeText(context, R.string.error_no_connection, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, R.string.error_authentication, Toast.LENGTH_LONG).show();
}
Preferences.setPassword(context, null);
dialog.dismiss();
}
/**
* If an HttpCallback was provided in the constructor execute them here
* @see com.bryanjswift.simplenote.net.HttpCallback#onComplete(com.bryanjswift.simplenote.net.Api.Response)
*/
@Override
public void onComplete(final Response response) {
if (callback != null) {
SimpleNoteApi.handleResponse(callback, response);
}
}
/**
* @see com.bryanjswift.simplenote.net.HttpCallback#onException(java.lang.String, java.lang.String, java.lang.Throwable)
*/
@Override
public void onException(final String url, final String data, final Throwable t) {
if (callback != null) {
callback.onException(url, data, t);
}
}
})).execute();
}
}
| src/com/bryanjswift/simplenote/widget/LoginActionListener.java | package com.bryanjswift.simplenote.widget;
import android.app.Activity;
import android.app.ProgressDialog;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;
import com.bryanjswift.simplenote.Constants;
import com.bryanjswift.simplenote.Preferences;
import com.bryanjswift.simplenote.R;
import com.bryanjswift.simplenote.net.Api;
import com.bryanjswift.simplenote.net.Api.Response;
import com.bryanjswift.simplenote.net.HttpCallback;
import com.bryanjswift.simplenote.net.SimpleNoteApi;
import com.bryanjswift.simplenote.thread.LoginTask;
public class LoginActionListener implements OnEditorActionListener, View.OnClickListener {
private static final String LOGGING_TAG = Constants.TAG + "LoginActionListener";
private final Activity context;
private final EditText email;
private final EditText password;
private final String loggingIn;
private final String authenticating;
private final HttpCallback callback;
/**
* Create an Listener to handle login actions
* @param context for the login action
* @param email text view containing email address information
* @param password text view containing password information
*/
public LoginActionListener(Activity context, EditText email, EditText password) {
this(context, email, password, null);
}
/**
* Create an Listener to handle login actions
* @param context for the login action
* @param email text view containing email address information
* @param password text view containing password information
* @param callback to run after those supplied by the Login action
*/
public LoginActionListener(Activity context, EditText email, EditText password, HttpCallback callback) {
this.context = context;
this.email = email;
this.password = password;
this.authenticating = context.getString(R.string.status_authenticating);
this.loggingIn = context.getString(R.string.status_loggingin);
this.callback = callback;
}
/**
* @see android.widget.TextView.OnEditorActionListener#onEditorAction(android.widget.TextView, int, android.view.KeyEvent)
*/
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
validateAndLogin();
return true;
}
/**
* @see android.view.View.OnClickListener#onClick(android.view.View)
*/
public void onClick(View v) {
validateAndLogin();
}
/**
* Attempt login only if information in fields is valid
*/
public void validateAndLogin() {
if (isValid()) {
login();
}
}
/**
* Check if the login fields are filled out and valid
* @return true if email and password both have values
*/
public boolean isValid() {
final String emailValue = email.getText().toString();
final String passwordValue = password.getText().toString();
boolean valid = true;
if (emailValue == null || emailValue.equals("") || passwordValue == null || passwordValue.equals("")) {
Toast.makeText(context, R.string.error_empty, Toast.LENGTH_LONG).show();
valid = false;
}
return valid;
}
/**
* Handle the process of logging a user in when they perform an action that justifies it
*/
public void login() {
Log.i(LOGGING_TAG, "Checking credentials and attempting login");
final String emailValue = email.getText().toString();
final String passwordValue = password.getText().toString();
if (emailValue == null || emailValue.equals("") || passwordValue == null || passwordValue.equals("")) {
Toast.makeText(context, R.string.error_empty, Toast.LENGTH_LONG).show();
return; // bail
}
final ProgressDialog dialog = ProgressDialog.show(context, loggingIn, authenticating);
Log.d(LOGGING_TAG, "Created progressDialog: " + dialog.toString());
final Api.Credentials credentials = Preferences.setLoginPreferences(context, emailValue, passwordValue);
// Login with credentials here
(new LoginTask(context, credentials, new HttpCallback() {
/**
* @see com.bryanjswift.simplenote.net.HttpCallback#on200(com.bryanjswift.simplenote.net.Api.Response)
*/
@Override
public void on200(Response response) {
dialog.dismiss();
}
/**
* @see com.bryanjswift.simplenote.net.HttpCallback#onError(com.bryanjswift.simplenote.net.Api.Response)
*/
@Override
public void onError(Response response) {
if (response.status == Constants.NO_CONNECTION) {
Toast.makeText(context, R.string.error_no_connection, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, R.string.error_authentication, Toast.LENGTH_LONG).show();
}
Preferences.setPassword(context, null);
dialog.dismiss();
}
/**
* If an HttpCallback was provided in the constructor execute them here
* @see com.bryanjswift.simplenote.net.HttpCallback#onComplete(com.bryanjswift.simplenote.net.Api.Response)
*/
@Override
public void onComplete(final Response response) {
if (callback != null) {
SimpleNoteApi.handleResponse(callback, response);
}
}
/**
* @see com.bryanjswift.simplenote.net.HttpCallback#onException(java.lang.String, java.lang.String, java.lang.Throwable)
*/
@Override
public void onException(final String url, final String data, final Throwable t) {
if (callback != null) {
callback.onException(url, data, t);
}
}
})).execute();
}
}
| Separate validation logic from login logic
| src/com/bryanjswift/simplenote/widget/LoginActionListener.java | Separate validation logic from login logic | <ide><path>rc/com/bryanjswift/simplenote/widget/LoginActionListener.java
<ide> import com.bryanjswift.simplenote.net.SimpleNoteApi;
<ide> import com.bryanjswift.simplenote.thread.LoginTask;
<ide>
<add>/**
<add> * OnEditorActionListener and OnClickListener to handle logging in from SimpleNoteSplash screen
<add> * @author bryanjswift
<add> */
<ide> public class LoginActionListener implements OnEditorActionListener, View.OnClickListener {
<ide> private static final String LOGGING_TAG = Constants.TAG + "LoginActionListener";
<ide> private final Activity context;
<ide> /**
<ide> * Attempt login only if information in fields is valid
<ide> */
<del> public void validateAndLogin() {
<add> private void validateAndLogin() {
<ide> if (isValid()) {
<ide> login();
<ide> }
<ide> * Check if the login fields are filled out and valid
<ide> * @return true if email and password both have values
<ide> */
<del> public boolean isValid() {
<add> private boolean isValid() {
<ide> final String emailValue = email.getText().toString();
<ide> final String passwordValue = password.getText().toString();
<ide> boolean valid = true;
<ide> /**
<ide> * Handle the process of logging a user in when they perform an action that justifies it
<ide> */
<del> public void login() {
<add> private void login() {
<ide> Log.i(LOGGING_TAG, "Checking credentials and attempting login");
<ide> final String emailValue = email.getText().toString();
<ide> final String passwordValue = password.getText().toString();
<del> if (emailValue == null || emailValue.equals("") || passwordValue == null || passwordValue.equals("")) {
<del> Toast.makeText(context, R.string.error_empty, Toast.LENGTH_LONG).show();
<del> return; // bail
<del> }
<ide> final ProgressDialog dialog = ProgressDialog.show(context, loggingIn, authenticating);
<ide> Log.d(LOGGING_TAG, "Created progressDialog: " + dialog.toString());
<ide> final Api.Credentials credentials = Preferences.setLoginPreferences(context, emailValue, passwordValue); |
|
Java | mit | 73958b06e46463172eb577802d2c16f5f11e2e21 | 0 | rubenlagus/TelegramBots | package org.telegram.telegrambots.bots;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.telegram.telegrambots.ApiConstants;
import org.telegram.telegrambots.ApiContext;
import org.telegram.telegrambots.api.methods.updates.SetWebhook;
import org.telegram.telegrambots.exceptions.TelegramApiRequestException;
import org.telegram.telegrambots.generics.WebhookBot;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief Base abstract class for a bot that will receive updates using a
* <a href="https://core.telegram.org/bots/api#setwebhook">webhook</a>
* @date 14 of January of 2016
*/
public abstract class TelegramWebhookBot extends DefaultAbsSender implements WebhookBot {
private final DefaultBotOptions botOptions;
public TelegramWebhookBot() {
this(ApiContext.getInstance(DefaultBotOptions.class));
}
public TelegramWebhookBot(DefaultBotOptions options) {
super(options);
this.botOptions = options;
}
@Override
public void setWebhook(String url, String publicCertificatePath) throws TelegramApiRequestException {
try (CloseableHttpClient httpclient = HttpClientBuilder.create().setSSLHostnameVerifier(new NoopHostnameVerifier()).build()) {
String requestUrl = getBaseUrl() + SetWebhook.PATH;
HttpPost httppost = new HttpPost(requestUrl);
httppost.setConfig(botOptions.getRequestConfig());
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addTextBody(SetWebhook.URL_FIELD, url);
if (botOptions.getMaxWebhookConnections() != null) {
builder.addTextBody(SetWebhook.MAXCONNECTIONS_FIELD, botOptions.getMaxWebhookConnections().toString());
}
if (botOptions.getAllowedUpdates() != null) {
builder.addTextBody(SetWebhook.ALLOWEDUPDATES_FIELD, new JSONArray(botOptions.getMaxWebhookConnections()).toString());
}
if (publicCertificatePath != null) {
File certificate = new File(publicCertificatePath);
if (certificate.exists()) {
builder.addBinaryBody(SetWebhook.CERTIFICATE_FIELD, certificate, ContentType.TEXT_PLAIN, certificate.getName());
}
}
HttpEntity multipart = builder.build();
httppost.setEntity(multipart);
try (CloseableHttpResponse response = httpclient.execute(httppost)) {
HttpEntity ht = response.getEntity();
BufferedHttpEntity buf = new BufferedHttpEntity(ht);
String responseContent = EntityUtils.toString(buf, StandardCharsets.UTF_8);
JSONObject jsonObject = new JSONObject(responseContent);
if (!jsonObject.getBoolean(ApiConstants.RESPONSE_FIELD_OK)) {
throw new TelegramApiRequestException("Error setting webhook", jsonObject);
}
}
} catch (JSONException e) {
throw new TelegramApiRequestException("Error deserializing setWebhook method response", e);
} catch (IOException e) {
throw new TelegramApiRequestException("Error executing setWebook method", e);
}
}
}
| telegrambots/src/main/java/org/telegram/telegrambots/bots/TelegramWebhookBot.java | package org.telegram.telegrambots.bots;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.telegram.telegrambots.ApiConstants;
import org.telegram.telegrambots.ApiContext;
import org.telegram.telegrambots.api.methods.updates.SetWebhook;
import org.telegram.telegrambots.exceptions.TelegramApiRequestException;
import org.telegram.telegrambots.generics.WebhookBot;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
/**
* @author Ruben Bermudez
* @version 1.0
* @brief Base abstract class for a bot that will receive updates using a
* <a href="https://core.telegram.org/bots/api#setwebhook">webhook</a>
* @date 14 of January of 2016
*/
public abstract class TelegramWebhookBot extends DefaultAbsSender implements WebhookBot {
private final DefaultBotOptions botOptions;
public TelegramWebhookBot() {
this(ApiContext.getInstance(DefaultBotOptions.class));
}
public TelegramWebhookBot(DefaultBotOptions options) {
super(options);
this.botOptions = options;
}
@Override
public void setWebhook(String url, String publicCertificatePath) throws TelegramApiRequestException {
try (CloseableHttpClient httpclient = HttpClientBuilder.create().setSSLHostnameVerifier(new NoopHostnameVerifier()).build()) {
String requestUrl = getBaseUrl() + getBotToken() + "/" + SetWebhook.PATH;
HttpPost httppost = new HttpPost(requestUrl);
httppost.setConfig(botOptions.getRequestConfig());
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addTextBody(SetWebhook.URL_FIELD, url);
if (botOptions.getMaxWebhookConnections() != null) {
builder.addTextBody(SetWebhook.MAXCONNECTIONS_FIELD, botOptions.getMaxWebhookConnections().toString());
}
if (botOptions.getAllowedUpdates() != null) {
builder.addTextBody(SetWebhook.ALLOWEDUPDATES_FIELD, new JSONArray(botOptions.getMaxWebhookConnections()).toString());
}
if (publicCertificatePath != null) {
File certificate = new File(publicCertificatePath);
if (certificate.exists()) {
builder.addBinaryBody(SetWebhook.CERTIFICATE_FIELD, certificate, ContentType.TEXT_PLAIN, certificate.getName());
}
}
HttpEntity multipart = builder.build();
httppost.setEntity(multipart);
try (CloseableHttpResponse response = httpclient.execute(httppost)) {
HttpEntity ht = response.getEntity();
BufferedHttpEntity buf = new BufferedHttpEntity(ht);
String responseContent = EntityUtils.toString(buf, StandardCharsets.UTF_8);
JSONObject jsonObject = new JSONObject(responseContent);
if (!jsonObject.getBoolean(ApiConstants.RESPONSE_FIELD_OK)) {
throw new TelegramApiRequestException("Error setting webhook", jsonObject);
}
}
} catch (JSONException e) {
throw new TelegramApiRequestException("Error deserializing setWebhook method response", e);
} catch (IOException e) {
throw new TelegramApiRequestException("Error executing setWebook method", e);
}
}
}
| Fix bug when setting webhook
| telegrambots/src/main/java/org/telegram/telegrambots/bots/TelegramWebhookBot.java | Fix bug when setting webhook | <ide><path>elegrambots/src/main/java/org/telegram/telegrambots/bots/TelegramWebhookBot.java
<ide> @Override
<ide> public void setWebhook(String url, String publicCertificatePath) throws TelegramApiRequestException {
<ide> try (CloseableHttpClient httpclient = HttpClientBuilder.create().setSSLHostnameVerifier(new NoopHostnameVerifier()).build()) {
<del> String requestUrl = getBaseUrl() + getBotToken() + "/" + SetWebhook.PATH;
<add> String requestUrl = getBaseUrl() + SetWebhook.PATH;
<ide>
<ide> HttpPost httppost = new HttpPost(requestUrl);
<ide> httppost.setConfig(botOptions.getRequestConfig()); |
|
Java | lgpl-2.1 | 2cef685add12b6cfcb52220fa7634b104b2406e2 | 0 | CloverETL/CloverETL-Engine,CloverETL/CloverETL-Engine,CloverETL/CloverETL-Engine,CloverETL/CloverETL-Engine | /*
* jETeL/Clover - Java based ETL application framework.
* Copyright (C) 2002-05 David Pavlis <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
package org.jetel.data.tape;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.BufferOverflowException;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jetel.data.DataRecord;
import org.jetel.data.Defaults;
import org.jetel.util.bytes.ByteBufferUtils;
/**
* Data structure for storing records in chunks on local disk (in temporary file).<br>
* When the data object is closed - the physical representation (the file) is removed - i.e.
* no permanent storage is performed.<br>
* Each chunk registers how many records is stored in it. The number
* of chunks on tape(in file) is not limited. Records can be read only
* sequentially, but particular chunk can be selected.<br><br>
* <i>Usage:</i><br>
* <code>
* tape=new DataRecordTape();<br>
* tape.open();<br>
* tape.addDataChunk();<br>
* ..loop.. tape.put(..data..);<br>
* tape.addDataChunk();<br>
* ..loop.. tape.put(..data..);<br>
* tape.rewind();<br>
* ..loop..tape.get();<br>
* tape.nextChunk();<br>
* ..loop..tape.get();<br>
* tape.close();<br>
* </code>
*
* @author david
* @since 20.1.2005
*
*/
public class DataRecordTape {
private FileChannel tmpFileChannel;
private File tmpFile;
private File tmpDirectory;
private String tmpFileName;
private boolean deleteOnExit;
private boolean deleteOnStart;
private List dataChunks;
private ByteBuffer dataBuffer;
private DataChunk currentDataChunk;
private int currentDataChunkIndex;
// size of BUFFER - used for push & shift operations
private final static int DEFAULT_BUFFER_SIZE = Defaults.DEFAULT_INTERNAL_IO_BUFFER_SIZE;
// prefix of temporary file generated by system
private final static String TMP_FILE_PREFIX = ".fbufclv";
// suffix of temporary file generated by system
private final static String TMP_FILE_SUFFIX = ".tmp";
private final static String TMP_FILE_MODE = "rw";
static Log logger = LogFactory.getLog(DataRecordTape.class);
/**
* Constructor for the DataRecordTape object
*
*@param tmpFileName Name of the temp file or NULL (the system default temp directory and name will be used)
*@param dataBufferSize The size of internal in memory buffer.
* If smaller than DEFAULT_BUFFER_SIZE, then default is used
*/
public DataRecordTape(String tmpFileName, int dataBufferSize, boolean deleteOnStart, boolean deleteOnExit) {
this.tmpFileName = tmpFileName;
this.deleteOnStart = deleteOnStart;
this.deleteOnExit = deleteOnExit;
dataChunks=new ArrayList();
dataBuffer = ByteBuffer.allocateDirect(dataBufferSize > DEFAULT_BUFFER_SIZE ? dataBufferSize : DEFAULT_BUFFER_SIZE);
}
/**
* Constructor.
* @param tmpFileName
* @param deleteOnExit
*/
public DataRecordTape(String tmpFileName, boolean deleteOnStart, boolean deleteOnExit) {
this(tmpFileName,DEFAULT_BUFFER_SIZE, deleteOnStart, deleteOnExit);
}
/**
* Constructor for the DataRecordTape object
*
*@param tmpFileName Name of the temp file or NULL (the system default temp directory and name will be used)
*/
public DataRecordTape(String tmpFileName) {
this(tmpFileName,DEFAULT_BUFFER_SIZE, true, true);
}
/**
* Constructor for DataRecordTape - all parameters defaulted.
*/
public DataRecordTape(){
this(null,DEFAULT_BUFFER_SIZE, true, true);
}
/**
* Opens buffer, creates temporary file.
*
*@exception IOException Description of Exception
*@since September 17, 2002
*/
public void open() throws IOException {
if(tmpFileName == null)
tmpFile = File.createTempFile(TMP_FILE_PREFIX, TMP_FILE_SUFFIX, tmpDirectory);
else {
tmpFile = new File(tmpFileName);
if(deleteOnStart && tmpFile.exists()) {
if (!tmpFile.delete()) {
throw new IOException("Can't delete TMP file: " + tmpFile.getAbsoluteFile());
}
}
if(!deleteOnStart && !tmpFile.exists()) {
throw new IOException("Temp file does not exist.");
}
}
if(deleteOnExit) tmpFile.deleteOnExit();
// we want the temp file be deleted on exit
tmpFileChannel = new RandomAccessFile(tmpFile, TMP_FILE_MODE).getChannel();
currentDataChunkIndex=-1;
currentDataChunk=null;
}
/**
* Closes buffer, removes temporary file (is exists)
*
*@exception IOException Description of Exception
* @throws InterruptedException
*@since September 17, 2002
*/
public void close() throws IOException, InterruptedException {
if(deleteOnExit) {
clear();
tmpFileChannel.close();
if (!tmpFile.delete()) {
throw new IOException("Can't delete TMP file: " + tmpFile.getAbsoluteFile());
}
} else {
tmpFileChannel.close();
}
}
/**
* Flushes tape content to disk.
*
* @throws IOException
* @throws InterruptedException
*/
public void flush(boolean force) throws IOException, InterruptedException {
try {
dataBuffer.flip();
tmpFileChannel.write(dataBuffer);
dataBuffer.clear();
//currentDataChunk.flushBuffer();
if (force){
tmpFileChannel.force(true);
}
} catch (ClosedChannelException e) {
throw new InterruptedException();
}
}
/**
* Rewinds the buffer and makes first chunk active. Next get operation returns first record stored in
* first chunk.
* @throws InterruptedException
* @throws IOException
*
*@since September 19, 2002
*/
public void rewind() throws InterruptedException, IOException {
if (dataChunks.size()==0){
return;
}
try {
flush(true);
tmpFileChannel.position(0);
currentDataChunkIndex=0;
currentDataChunk=(DataChunk)dataChunks.get(0);
currentDataChunk.rewind();
} catch (ClosedChannelException e) {
throw new InterruptedException();
}
}
/**
* Clears the tape. All DataChunks are destroyed. Underlying
* tmp file is truncated.
* @throws InterruptedException
*/
public void clear() throws IOException, InterruptedException {
try {
dataChunks.clear();
tmpFileChannel.truncate(0);
tmpFileChannel.position(0);
currentDataChunkIndex=-1;
currentDataChunk=null;
} catch (ClosedChannelException e) {
throw new InterruptedException();
}
}
/**
* Adds new data chunk to the tape and opens it.
* @return true if successful, otherwise false
* @throws InterruptedException
* @throws IOException
*/
public void addDataChunk() throws InterruptedException, IOException {
if (currentDataChunk==null){
// add new data chunk
DataChunk chunk=new DataChunk(tmpFileChannel,dataBuffer);
dataChunks.add(chunk);
currentDataChunkIndex=0;
currentDataChunk=chunk;
} else {
try {
// set file position to the end of file
flush(true);
tmpFileChannel.position(tmpFileChannel.size());
// add new data chunk
DataChunk chunk=new DataChunk(tmpFileChannel,dataBuffer);
dataChunks.add(chunk);
currentDataChunkIndex++;
currentDataChunk=chunk;
} catch (ClosedChannelException e) {
throw new InterruptedException();
}
}
dataBuffer.clear();
}
/**
* Sets next data chunk active. Next get() operation will return first record
* from the newly activated chunk. This method must be called after rewind()
* method, otherwise the result is not guaranteed.
*
* @return true if next data chunk has been activated, otherwise false
* @throws InterruptedException
* @throws IOException
* @throws IOException
*/
public boolean nextDataChunk() throws InterruptedException, IOException {
if (currentDataChunkIndex!=-1 && currentDataChunkIndex+1 < dataChunks.size()){
currentDataChunkIndex++;
currentDataChunk=(DataChunk)dataChunks.get(currentDataChunkIndex);
currentDataChunk.rewind();
return true;
}else{
currentDataChunkIndex=-1;
currentDataChunk=null;
return false;
}
}
public boolean setDataChunk(int order) throws InterruptedException, IOException {
if (order<dataChunks.size()){
currentDataChunk=(DataChunk)dataChunks.get(order);
currentDataChunkIndex=order;
currentDataChunk.rewind();
return true;
}else{
currentDataChunkIndex=-1;
currentDataChunk=null;
return false;
}
}
/**
* Returns number of chunks this tape contains.
*
* @return
* @since 1.2.2007
*/
public int getNumChunks(){
return dataChunks.size();
}
/**
* For specified chunk number returns its
* length (in bytes).
*
* @param chunk
* @return
* @since 1.2.2007
*/
public long getChunkLength(int chunk) {
return ((DataChunk)dataChunks.get(chunk)).getLength();
}
/**
* For specified chunk number returns how
* many records it contains.
*
* @param chunk
* @return
* @since 1.2.2007
*/
public int getChunkRecNum(int chunk) {
return ((DataChunk)dataChunks.get(chunk)).getNumRecords();
}
/**
* Stores data in current/active chunk. Must not be mixed with calls to
* get() method, otherwise the result is not guaranteed.
*
* @param data buffer containig record's data
* @return
* @throws InterruptedException
*/
public long put(ByteBuffer data) throws IOException, InterruptedException {
if (currentDataChunk != null) {
return currentDataChunk.put(data);
} else {
throw new RuntimeException("No DataChunk has been created !");
}
}
/**
* Bulk-copy of data (1 record) from one tape to the other (directly)
*
* @param source DataRecordTape from which to copy data
* @return new size of chunk or -1 in case of problem
* @throws InterruptedException
*/
public long put(DataRecordTape sourceTape) throws IOException, InterruptedException{
if (currentDataChunk != null) {
if (sourceTape.currentDataChunk!=null){
return currentDataChunk.put(sourceTape.currentDataChunk);
}else{
return -1;
}
} else {
throw new RuntimeException("No DataChunk has been created !");
}
}
public long putDirect(DataRecordTape sourceTape) throws IOException, InterruptedException {
if (currentDataChunk != null) {
if (sourceTape.currentDataChunk!=null){
return currentDataChunk.putDirect(sourceTape.currentDataChunk);
}else{
return -1;
}
} else {
throw new RuntimeException("No DataChunk has been created !");
}
}
/**
* Stores data record in current/active chunk.
*
* @param data
* @return
* @throws IOException
* @throws InterruptedException
*/
public long put(DataRecord data) throws IOException, InterruptedException {
if (currentDataChunk != null) {
return currentDataChunk.put(data);
} else {
throw new RuntimeException("No DataChunk has been created !");
}
}
/**
* Fills buffer passed as an argument with data read from current data chunk.
* Must not be mixed with put() method calls, otherwise the result is not guaranteed.<br>
* The normal way of using this method is:<br>
* while(get(data)){
* ... do something ...
* }
* @param data buffer into which store data
* @return true if success, otherwise false (chunk contains no more data).
* @throws InterruptedException
*/
public boolean get(ByteBuffer data) throws IOException, InterruptedException {
if (currentDataChunk!=null){
return currentDataChunk.get(data);
}else{
return false;
}
}
/**
* Reads again previously read record.
*
* @param data
* @return
* @throws IOException
* @since 27.2.2007
*/
public boolean reget(ByteBuffer data) {
if (currentDataChunk!=null){
return currentDataChunk.reget(data);
}else{
return false;
}
}
/**
* Reads data record from current chunk
*
* @param data
* @return
* @throws IOException
* @throws InterruptedException
*/
public boolean get(DataRecord data) throws IOException, InterruptedException {
if (currentDataChunk!=null){
return currentDataChunk.get(data);
}else{
return false;
}
}
/**
* Reads again previously read record.
*
* @param data
* @return
* @throws IOException
* @since 27.2.2007
*/
public boolean reget(DataRecord data) {
if (currentDataChunk!=null){
return currentDataChunk.reget(data);
}else{
return false;
}
}
/* Returns String containing short summary of chunks stored on tape.
*
* (non-Javadoc)
* @see java.lang.Object#toString()
*/
public String toString(){
StringBuffer buffer=new StringBuffer(160);
int index=0;
for (Iterator i=dataChunks.iterator();i.hasNext();){
buffer.append("Chunk #").append(index++);
buffer.append(((DataChunk)i.next()).toString());
buffer.append("\n");
}
return buffer.toString();
}
public void testConsistency() throws InterruptedException, IOException {
ByteBuffer buffer=ByteBuffer.allocateDirect(2048);
logger.info("Testing consistency...");
rewind();
for(int i=0;i<getNumChunks();i++){
int counter=0;
try{
while(get(buffer)){
counter++;
buffer.clear();
}
if(!nextDataChunk()) break;
}catch(Exception ex){
logger.error("Problem with chunk: "+i+" record "+counter);
ex.printStackTrace();
}
}
logger.info("OK");
}
/**
* Helper class for storing data chunks.
* @author david
* @since 20.1.2005
*
*/
private static class DataChunk{
// size of integer variable used to keep record length
// this is the maximum size, can be between 1 & 4 bytes
private final static int LEN_SIZE_SPECIFIER = 4;
ByteBuffer dataBuffer;
FileChannel tmpFileChannel;
long offsetStart;
long length;
int recordsRead;
int nRecords;
boolean canRead;
int recordSize;
private DataChunk(FileChannel channel,ByteBuffer buffer) throws InterruptedException, IOException{
tmpFileChannel=channel;
canRead=false;
dataBuffer=buffer;
try{
offsetStart=channel.position();
} catch (ClosedChannelException e) {
throw new InterruptedException();
}
length=0;
nRecords=recordsRead=0;
dataBuffer.clear();
}
long getLength(){
return length;
}
int getNumRecords(){
return nRecords;
}
void rewind() throws IOException, InterruptedException {
try {
tmpFileChannel.position(offsetStart);
canRead=true;
recordsRead=0;
dataBuffer.clear();
tmpFileChannel.read(dataBuffer);
dataBuffer.flip();
} catch (ClosedChannelException e) {
throw new InterruptedException();
}
}
/**
* Stores one data record into buffer / file.
*
*@param recordBuffer ByteBuffer containing record's data
*@exception IOException In case of IO failure
*@since September 17, 2002
*@return number of bytes in the chunk after saveing data
* @throws InterruptedException
*/
long put(ByteBuffer recordBuffer) throws IOException, InterruptedException {
recordSize = recordBuffer.remaining();
final int lengthSize=ByteBufferUtils.lengthEncoded(recordSize);
// check that internal buffer has enough space
if ((recordSize + lengthSize) > dataBuffer.remaining()){
flushBuffer();
}
try {
ByteBufferUtils.encodeLength(dataBuffer, recordSize);
dataBuffer.put(recordBuffer);
} catch (BufferOverflowException ex) {
throw new IOException("Input Buffer is not big enough to accomodate data record !");
}
length+=(recordSize+ lengthSize);
nRecords++;
return length;
}
long put(DataChunk sourceChunk) throws IOException, InterruptedException {
final ByteBuffer sourceDataBuffer=sourceChunk.dataBuffer;
if(!sourceChunk.canRead){
throw new IOException("Buffer has not been rewind !");
}
if (sourceChunk.nRecords > 0 && sourceChunk.recordsRead>=sourceChunk.nRecords){
return -1;
}
// check that internal buffer has enough data to read data size
if (LEN_SIZE_SPECIFIER > sourceDataBuffer.remaining()){
sourceChunk.reloadBuffer();
if(sourceDataBuffer.remaining() == 0) return -1;
}
recordSize = ByteBufferUtils.decodeLength(sourceDataBuffer);
// check that internal buffer has enough data to read data record
if (recordSize > sourceDataBuffer.remaining()){
sourceChunk.reloadBuffer();
if(recordSize > sourceDataBuffer.remaining()) return -1;
}
int oldLimit = sourceDataBuffer.limit();
sourceDataBuffer.limit(sourceDataBuffer.position() + recordSize);
//write it here
final int lengthSize=ByteBufferUtils.lengthEncoded(recordSize);
// check that internal buffer has enough space
if ((recordSize + lengthSize) > dataBuffer.remaining()){
flushBuffer();
}
try {
ByteBufferUtils.encodeLength(dataBuffer, recordSize);
dataBuffer.put(sourceDataBuffer);
} catch (BufferOverflowException ex) {
throw new IOException("Input Buffer is not big enough to accomodate data record !");
}
// end write
sourceDataBuffer.limit(oldLimit);
length+=(recordSize+ lengthSize);
nRecords++;
return length;
}
/**
* This operation copies directly data from source chunk's buffer
* into this chunk. <br>It assumes that get() operation on source chunk
* was performed previously and source chunk's buffer contains the whole record<br>
*
* @param sourceChunk
* @return
* @throws IOException
* @throws InterruptedException
* @since 28.2.2007
*/
long putDirect(DataChunk sourceChunk) throws IOException, InterruptedException {
final ByteBuffer sourceDataBuffer=sourceChunk.dataBuffer;
final int sourceRecSize=sourceChunk.recordSize;
sourceDataBuffer.reset(); //we are re-getting data
// check that internal buffer has enough data to read data size
final int lengthSize=ByteBufferUtils.lengthEncoded(sourceRecSize)+sourceRecSize;
if (lengthSize > dataBuffer.remaining()){
flushBuffer();
if(lengthSize > dataBuffer.remaining()) return -1;
}
int oldLimit = sourceDataBuffer.limit();
sourceDataBuffer.limit(sourceDataBuffer.position() + sourceRecSize);
//write it here
try {
ByteBufferUtils.encodeLength(dataBuffer, sourceRecSize);
dataBuffer.put(sourceDataBuffer);
} catch (BufferOverflowException ex) {
throw new IOException("Input Buffer is not big enough to accomodate data record !");
}
// end write
sourceDataBuffer.limit(oldLimit);
length+=lengthSize;
nRecords++;
return length;
}
/**
* Stores one data record into buffer / file.
*
* @param data DataRecord to be stored
*@return number of bytes in the chunk after saving data
* @throws IOException
* @throws InterruptedException
*/
long put(DataRecord data) throws IOException, InterruptedException {
recordSize = data.getSizeSerialized();
final int lengthSize=ByteBufferUtils.lengthEncoded(recordSize);
// check that internal buffer has enough space
if ((recordSize + lengthSize) > dataBuffer.remaining()){
flushBuffer();
}
try {
ByteBufferUtils.encodeLength(dataBuffer, recordSize);
data.serialize(dataBuffer);
} catch (BufferOverflowException ex) {
throw new IOException("Input Buffer is not big enough to accomodate data record !");
}
length+=(recordSize+ lengthSize);
nRecords++;
return length;
}
/**
* Returns next record from the buffer - FIFO order.
*
*@param recordBuffer ByteBuffer into which store data
*@return ByteBuffer populated with record's data or NULL if
* no more record can be retrieved
*@exception IOException Description of Exception
* @throws InterruptedException
*@since September 17, 2002
*/
boolean get(ByteBuffer recordBuffer) throws IOException, InterruptedException {
if(!canRead){
throw new IOException("Buffer has not been rewind !");
}
if (nRecords > 0 && recordsRead>=nRecords){
return false;
}
// check that internal buffer has enough data to read data size
if (LEN_SIZE_SPECIFIER > dataBuffer.remaining()){
reloadBuffer();
if(dataBuffer.remaining() == 0) return false;
}
recordSize = ByteBufferUtils.decodeLength(dataBuffer);
// check that internal buffer has enough data to read data record
if (recordSize > dataBuffer.remaining()){
reloadBuffer();
if(recordSize > dataBuffer.remaining()) return false;
}
int oldLimit = dataBuffer.limit();
dataBuffer.mark(); //could be used later in reget method
dataBuffer.limit(dataBuffer.position() + recordSize);
recordBuffer.clear();
recordBuffer.put(dataBuffer);
recordBuffer.flip();
dataBuffer.limit(oldLimit);
recordsRead++;
return true;
}
/**
* Read again previously read record. Use caution when calling this
* method as it lifts most of the safety checks. Should be used
* only immediately after successful get(ByteBuffer) call
*
* @param recordBuffer
* @return
* @throws IOException
* @since 27.2.2007
*/
boolean reget(ByteBuffer recordBuffer) {
dataBuffer.reset();
int oldLimit = dataBuffer.limit();
dataBuffer.limit(dataBuffer.position() + recordSize);
recordBuffer.clear();
recordBuffer.put(dataBuffer);
recordBuffer.flip();
dataBuffer.limit(oldLimit);
return true;
}
// protected ByteBuffer bulkGetStart() throws IOException {
// final int recordSize;
// if(!canRead){
// throw new IOException("Buffer has not been rewind !");
// }
//
// if (nRecords > 0 && recordsRead>=nRecords){
// return null;
// }
// // check that internal buffer has enough data to read data size
// if (LEN_SIZE_SPECIFIER > dataBuffer.remaining()){
// reloadBuffer();
// if(LEN_SIZE_SPECIFIER > dataBuffer.remaining()) return null;
// }
// recordSize = ByteBufferUtils.decodeLength(dataBuffer);
//
// // check that internal buffer has enough data to read data record
// if (recordSize > dataBuffer.remaining()){
// reloadBuffer();
// if(recordSize > dataBuffer.remaining()) return null;
// }
// int oldLimit = dataBuffer.limit();
// dataBuffer.limit(dataBuffer.position() + recordSize);
// //write it here
//
// dataBuffer.limit(oldLimit);
// recordsRead++;
// return dataBuffer;
// }
/**
* Returns next record from the buffer - FIFO order.
* @param data DataRecord into which load the data
* @return
* @throws IOException
* @throws InterruptedException
*/
boolean get(DataRecord data) throws IOException, InterruptedException {
if(!canRead){
throw new IOException("Buffer has not been rewind !");
}
if (nRecords > 0 && recordsRead>=nRecords){
return false;
}
// check that internal buffer has enough data to read data size
if (LEN_SIZE_SPECIFIER > dataBuffer.remaining()) {
reloadBuffer();
if(dataBuffer.remaining() == 0) return false;
}
recordSize = ByteBufferUtils.decodeLength(dataBuffer);
// check that internal buffer has enough data to read data record
if (recordSize > dataBuffer.remaining()){
reloadBuffer();
if(recordSize > dataBuffer.remaining()) return false;
}
dataBuffer.mark();//could be used later for reget
data.deserialize(dataBuffer);
recordsRead++;
return true;
}
boolean reget(DataRecord data) {
dataBuffer.reset();
data.deserialize(dataBuffer);
return true;
}
/**
* Flushes in memory buffer into TMP file
*
*@exception IOException Description of Exception
* @throws InterruptedException
*@since September 17, 2002
*/
private void flushBuffer() throws IOException, InterruptedException {
try {
dataBuffer.flip();
tmpFileChannel.write(dataBuffer);
dataBuffer.clear();
} catch (ClosedChannelException e) {
throw new InterruptedException();
}
}
private void reloadBuffer() throws IOException, InterruptedException {
try {
dataBuffer.compact();
tmpFileChannel.read(dataBuffer);
dataBuffer.flip();
} catch (ClosedChannelException e) {
throw new InterruptedException();
}
}
public boolean isEmpty(){
return (length==0);
}
public String toString(){
return "start: "+offsetStart+" #records: "+nRecords+" length: "+length;
}
}
/**
* Returns previously set temporary directory where this DataRecordTape
* should create its file (temporary)
*
* @return
*/
public File getTmpDirectory() {
return tmpDirectory;
}
/**
* Allows to set the temporary directory in which this DataRecordTape will
* create temporary file to store data.
*
* @param tmpDirectory
*/
public void setTmpDirectory(File tmpDirectory) {
this.tmpDirectory = tmpDirectory;
}
}
| cloveretl.engine/src/org/jetel/data/tape/DataRecordTape.java | /*
* jETeL/Clover - Java based ETL application framework.
* Copyright (C) 2002-05 David Pavlis <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
package org.jetel.data.tape;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.BufferOverflowException;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jetel.data.DataRecord;
import org.jetel.data.Defaults;
import org.jetel.util.bytes.ByteBufferUtils;
/**
* Data structure for storing records in chunks on local disk (in temporary file).<br>
* When the data object is closed - the physical representation (the file) is removed - i.e.
* no permanent storage is performed.<br>
* Each chunk registers how many records is stored in it. The number
* of chunks on tape(in file) is not limited. Records can be read only
* sequentially, but particular chunk can be selected.<br><br>
* <i>Usage:</i><br>
* <code>
* tape=new DataRecordTape();<br>
* tape.open();<br>
* tape.addDataChunk();<br>
* ..loop.. tape.put(..data..);<br>
* tape.addDataChunk();<br>
* ..loop.. tape.put(..data..);<br>
* tape.rewind();<br>
* ..loop..tape.get();<br>
* tape.nextChunk();<br>
* ..loop..tape.get();<br>
* tape.close();<br>
* </code>
*
* @author david
* @since 20.1.2005
*
*/
public class DataRecordTape {
private FileChannel tmpFileChannel;
private File tmpFile;
private File tmpDirectory;
private String tmpFileName;
private boolean deleteOnExit;
private boolean deleteOnStart;
private List dataChunks;
private ByteBuffer dataBuffer;
private DataChunk currentDataChunk;
private int currentDataChunkIndex;
// size of BUFFER - used for push & shift operations
private final static int DEFAULT_BUFFER_SIZE = Defaults.DEFAULT_INTERNAL_IO_BUFFER_SIZE;
// prefix of temporary file generated by system
private final static String TMP_FILE_PREFIX = ".fbufclv";
// suffix of temporary file generated by system
private final static String TMP_FILE_SUFFIX = ".tmp";
private final static String TMP_FILE_MODE = "rw";
static Log logger = LogFactory.getLog(DataRecordTape.class);
/**
* Constructor for the DataRecordTape object
*
*@param tmpFileName Name of the temp file or NULL (the system default temp directory and name will be used)
*@param dataBufferSize The size of internal in memory buffer.
* If smaller than DEFAULT_BUFFER_SIZE, then default is used
*/
public DataRecordTape(String tmpFileName, int dataBufferSize, boolean deleteOnStart, boolean deleteOnExit) {
this.tmpFileName = tmpFileName;
this.deleteOnStart = deleteOnStart;
this.deleteOnExit = deleteOnExit;
dataChunks=new ArrayList();
dataBuffer = ByteBuffer.allocateDirect(dataBufferSize > DEFAULT_BUFFER_SIZE ? dataBufferSize : DEFAULT_BUFFER_SIZE);
}
/**
* Constructor.
* @param tmpFileName
* @param deleteOnExit
*/
public DataRecordTape(String tmpFileName, boolean deleteOnStart, boolean deleteOnExit) {
this(tmpFileName,DEFAULT_BUFFER_SIZE, deleteOnStart, deleteOnExit);
}
/**
* Constructor for the DataRecordTape object
*
*@param tmpFileName Name of the temp file or NULL (the system default temp directory and name will be used)
*/
public DataRecordTape(String tmpFileName) {
this(tmpFileName,DEFAULT_BUFFER_SIZE, true, true);
}
/**
* Constructor for DataRecordTape - all parameters defaulted.
*/
public DataRecordTape(){
this(null,DEFAULT_BUFFER_SIZE, true, true);
}
/**
* Opens buffer, creates temporary file.
*
*@exception IOException Description of Exception
*@since September 17, 2002
*/
public void open() throws IOException {
if(tmpFileName == null)
tmpFile = File.createTempFile(TMP_FILE_PREFIX, TMP_FILE_SUFFIX, tmpDirectory);
else {
tmpFile = new File(tmpFileName);
if(deleteOnStart && tmpFile.exists()) {
if (!tmpFile.delete()) {
throw new IOException("Can't delete TMP file: " + tmpFile.getAbsoluteFile());
}
}
if(!deleteOnStart && !tmpFile.exists()) {
throw new IOException("Temp file does not exist.");
}
}
if(deleteOnExit) tmpFile.deleteOnExit();
// we want the temp file be deleted on exit
tmpFileChannel = new RandomAccessFile(tmpFile, TMP_FILE_MODE).getChannel();
currentDataChunkIndex=-1;
currentDataChunk=null;
}
/**
* Closes buffer, removes temporary file (is exists)
*
*@exception IOException Description of Exception
* @throws InterruptedException
*@since September 17, 2002
*/
public void close() throws IOException, InterruptedException {
if(deleteOnExit) {
clear();
tmpFileChannel.close();
if (!tmpFile.delete()) {
throw new IOException("Can't delete TMP file: " + tmpFile.getAbsoluteFile());
}
} else {
tmpFileChannel.close();
}
}
/**
* Flushes tape content to disk.
*
* @throws IOException
* @throws InterruptedException
*/
public void flush(boolean force) throws IOException, InterruptedException {
try {
dataBuffer.flip();
tmpFileChannel.write(dataBuffer);
dataBuffer.clear();
//currentDataChunk.flushBuffer();
if (force){
tmpFileChannel.force(true);
}
} catch (ClosedChannelException e) {
throw new InterruptedException();
}
}
/**
* Rewinds the buffer and makes first chunk active. Next get operation returns first record stored in
* first chunk.
* @throws InterruptedException
* @throws IOException
*
*@since September 19, 2002
*/
public void rewind() throws InterruptedException, IOException {
if (dataChunks.size()==0){
return;
}
try {
flush(true);
tmpFileChannel.position(0);
currentDataChunkIndex=0;
currentDataChunk=(DataChunk)dataChunks.get(0);
currentDataChunk.rewind();
} catch (ClosedChannelException e) {
throw new InterruptedException();
}
}
/**
* Clears the tape. All DataChunks are destroyed. Underlying
* tmp file is truncated.
* @throws InterruptedException
*/
public void clear() throws IOException, InterruptedException {
try {
dataChunks.clear();
tmpFileChannel.truncate(0);
tmpFileChannel.position(0);
currentDataChunkIndex=-1;
currentDataChunk=null;
} catch (ClosedChannelException e) {
throw new InterruptedException();
}
}
/**
* Adds new data chunk to the tape and opens it.
* @return true if successful, otherwise false
* @throws InterruptedException
* @throws IOException
*/
public void addDataChunk() throws InterruptedException, IOException {
if (currentDataChunk==null){
// add new data chunk
DataChunk chunk=new DataChunk(tmpFileChannel,dataBuffer);
dataChunks.add(chunk);
currentDataChunkIndex=0;
currentDataChunk=chunk;
} else {
try {
// set file position to the end of file
flush(true);
tmpFileChannel.position(tmpFileChannel.size());
// add new data chunk
DataChunk chunk=new DataChunk(tmpFileChannel,dataBuffer);
dataChunks.add(chunk);
currentDataChunkIndex++;
currentDataChunk=chunk;
} catch (ClosedChannelException e) {
throw new InterruptedException();
}
}
dataBuffer.clear();
}
/**
* Sets next data chunk active. Next get() operation will return first record
* from the newly activated chunk. This method must be called after rewind()
* method, otherwise the result is not guaranteed.
*
* @return true if next data chunk has been activated, otherwise false
* @throws InterruptedException
* @throws IOException
* @throws IOException
*/
public boolean nextDataChunk() throws InterruptedException, IOException {
if (currentDataChunkIndex!=-1 && currentDataChunkIndex+1 < dataChunks.size()){
currentDataChunkIndex++;
currentDataChunk=(DataChunk)dataChunks.get(currentDataChunkIndex);
currentDataChunk.rewind();
return true;
}else{
currentDataChunkIndex=-1;
currentDataChunk=null;
return false;
}
}
public boolean setDataChunk(int order) throws InterruptedException, IOException {
if (order<dataChunks.size()){
currentDataChunk=(DataChunk)dataChunks.get(order);
currentDataChunkIndex=order;
currentDataChunk.rewind();
return true;
}else{
currentDataChunkIndex=-1;
currentDataChunk=null;
return false;
}
}
/**
* Returns number of chunks this tape contains.
*
* @return
* @since 1.2.2007
*/
public int getNumChunks(){
return dataChunks.size();
}
/**
* For specified chunk number returns its
* length (in bytes).
*
* @param chunk
* @return
* @since 1.2.2007
*/
public long getChunkLength(int chunk) {
return ((DataChunk)dataChunks.get(chunk)).getLength();
}
/**
* For specified chunk number returns how
* many records it contains.
*
* @param chunk
* @return
* @since 1.2.2007
*/
public int getChunkRecNum(int chunk) {
return ((DataChunk)dataChunks.get(chunk)).getNumRecords();
}
/**
* Stores data in current/active chunk. Must not be mixed with calls to
* get() method, otherwise the result is not guaranteed.
*
* @param data buffer containig record's data
* @return
* @throws InterruptedException
*/
public long put(ByteBuffer data) throws IOException, InterruptedException {
if (currentDataChunk != null) {
return currentDataChunk.put(data);
} else {
throw new RuntimeException("No DataChunk has been created !");
}
}
/**
* Bulk-copy of data (1 record) from one tape to the other (directly)
*
* @param source DataRecordTape from which to copy data
* @return new size of chunk or -1 in case of problem
* @throws InterruptedException
*/
public long put(DataRecordTape sourceTape) throws IOException, InterruptedException{
if (currentDataChunk != null) {
if (sourceTape.currentDataChunk!=null){
return currentDataChunk.put(sourceTape.currentDataChunk);
}else{
return -1;
}
} else {
throw new RuntimeException("No DataChunk has been created !");
}
}
public long putDirect(DataRecordTape sourceTape) throws IOException, InterruptedException {
if (currentDataChunk != null) {
if (sourceTape.currentDataChunk!=null){
return currentDataChunk.putDirect(sourceTape.currentDataChunk);
}else{
return -1;
}
} else {
throw new RuntimeException("No DataChunk has been created !");
}
}
/**
* Stores data record in current/active chunk.
*
* @param data
* @return
* @throws IOException
* @throws InterruptedException
*/
public long put(DataRecord data) throws IOException, InterruptedException {
if (currentDataChunk != null) {
return currentDataChunk.put(data);
} else {
throw new RuntimeException("No DataChunk has been created !");
}
}
/**
* Fills buffer passed as an argument with data read from current data chunk.
* Must not be mixed with put() method calls, otherwise the result is not guaranteed.<br>
* The normal way of using this method is:<br>
* while(get(data)){
* ... do something ...
* }
* @param data buffer into which store data
* @return true if success, otherwise false (chunk contains no more data).
* @throws InterruptedException
*/
public boolean get(ByteBuffer data) throws IOException, InterruptedException {
if (currentDataChunk!=null){
return currentDataChunk.get(data);
}else{
return false;
}
}
/**
* Reads again previously read record.
*
* @param data
* @return
* @throws IOException
* @since 27.2.2007
*/
public boolean reget(ByteBuffer data) {
if (currentDataChunk!=null){
return currentDataChunk.reget(data);
}else{
return false;
}
}
/**
* Reads data record from current chunk
*
* @param data
* @return
* @throws IOException
* @throws InterruptedException
*/
public boolean get(DataRecord data) throws IOException, InterruptedException {
if (currentDataChunk!=null){
return currentDataChunk.get(data);
}else{
return false;
}
}
/**
* Reads again previously read record.
*
* @param data
* @return
* @throws IOException
* @since 27.2.2007
*/
public boolean reget(DataRecord data) {
if (currentDataChunk!=null){
return currentDataChunk.reget(data);
}else{
return false;
}
}
/* Returns String containing short summary of chunks stored on tape.
*
* (non-Javadoc)
* @see java.lang.Object#toString()
*/
public String toString(){
StringBuffer buffer=new StringBuffer(160);
int index=0;
for (Iterator i=dataChunks.iterator();i.hasNext();){
buffer.append("Chunk #").append(index++);
buffer.append(((DataChunk)i.next()).toString());
buffer.append("\n");
}
return buffer.toString();
}
public void testConsistency() throws InterruptedException, IOException {
ByteBuffer buffer=ByteBuffer.allocateDirect(2048);
logger.info("Testing consistency...");
rewind();
for(int i=0;i<getNumChunks();i++){
int counter=0;
try{
while(get(buffer)){
counter++;
buffer.clear();
}
if(!nextDataChunk()) break;
}catch(Exception ex){
logger.error("Problem with chunk: "+i+" record "+counter);
ex.printStackTrace();
}
}
logger.info("OK");
}
/**
* Helper class for storing data chunks.
* @author david
* @since 20.1.2005
*
*/
private static class DataChunk{
// size of integer variable used to keep record length
// this is the maximum size, can be between 1 & 4 bytes
private final static int LEN_SIZE_SPECIFIER = 4;
ByteBuffer dataBuffer;
FileChannel tmpFileChannel;
long offsetStart;
long length;
int recordsRead;
int nRecords;
boolean canRead;
int recordSize;
private DataChunk(FileChannel channel,ByteBuffer buffer) throws InterruptedException, IOException{
tmpFileChannel=channel;
canRead=false;
dataBuffer=buffer;
try{
offsetStart=channel.position();
} catch (ClosedChannelException e) {
throw new InterruptedException();
}
length=0;
nRecords=recordsRead=0;
dataBuffer.clear();
}
long getLength(){
return length;
}
int getNumRecords(){
return nRecords;
}
void rewind() throws IOException, InterruptedException {
try {
tmpFileChannel.position(offsetStart);
canRead=true;
recordsRead=0;
dataBuffer.clear();
tmpFileChannel.read(dataBuffer);
dataBuffer.flip();
} catch (ClosedChannelException e) {
throw new InterruptedException();
}
}
/**
* Stores one data record into buffer / file.
*
*@param recordBuffer ByteBuffer containing record's data
*@exception IOException In case of IO failure
*@since September 17, 2002
*@return number of bytes in the chunk after saveing data
* @throws InterruptedException
*/
long put(ByteBuffer recordBuffer) throws IOException, InterruptedException {
recordSize = recordBuffer.remaining();
final int lengthSize=ByteBufferUtils.lengthEncoded(recordSize);
// check that internal buffer has enough space
if ((recordSize + lengthSize) > dataBuffer.remaining()){
flushBuffer();
}
try {
ByteBufferUtils.encodeLength(dataBuffer, recordSize);
dataBuffer.put(recordBuffer);
} catch (BufferOverflowException ex) {
throw new IOException("Input Buffer is not big enough to accomodate data record !");
}
length+=(recordSize+ lengthSize);
nRecords++;
return length;
}
long put(DataChunk sourceChunk) throws IOException, InterruptedException {
final ByteBuffer sourceDataBuffer=sourceChunk.dataBuffer;
if(!sourceChunk.canRead){
throw new IOException("Buffer has not been rewind !");
}
if (sourceChunk.nRecords > 0 && sourceChunk.recordsRead>=sourceChunk.nRecords){
return -1;
}
// check that internal buffer has enough data to read data size
if (LEN_SIZE_SPECIFIER > sourceDataBuffer.remaining()){
sourceChunk.reloadBuffer();
if(LEN_SIZE_SPECIFIER > sourceDataBuffer.remaining()) return -1;
}
recordSize = ByteBufferUtils.decodeLength(sourceDataBuffer);
// check that internal buffer has enough data to read data record
if (recordSize > sourceDataBuffer.remaining()){
sourceChunk.reloadBuffer();
if(recordSize > sourceDataBuffer.remaining()) return -1;
}
int oldLimit = sourceDataBuffer.limit();
sourceDataBuffer.limit(sourceDataBuffer.position() + recordSize);
//write it here
final int lengthSize=ByteBufferUtils.lengthEncoded(recordSize);
// check that internal buffer has enough space
if ((recordSize + lengthSize) > dataBuffer.remaining()){
flushBuffer();
}
try {
ByteBufferUtils.encodeLength(dataBuffer, recordSize);
dataBuffer.put(sourceDataBuffer);
} catch (BufferOverflowException ex) {
throw new IOException("Input Buffer is not big enough to accomodate data record !");
}
// end write
sourceDataBuffer.limit(oldLimit);
length+=(recordSize+ lengthSize);
nRecords++;
return length;
}
/**
* This operation copies directly data from source chunk's buffer
* into this chunk. <br>It assumes that get() operation on source chunk
* was performed previously and source chunk's buffer contains the whole record<br>
*
* @param sourceChunk
* @return
* @throws IOException
* @throws InterruptedException
* @since 28.2.2007
*/
long putDirect(DataChunk sourceChunk) throws IOException, InterruptedException {
final ByteBuffer sourceDataBuffer=sourceChunk.dataBuffer;
final int sourceRecSize=sourceChunk.recordSize;
sourceDataBuffer.reset(); //we are re-getting data
// check that internal buffer has enough data to read data size
final int lengthSize=ByteBufferUtils.lengthEncoded(sourceRecSize)+sourceRecSize;
if (lengthSize > dataBuffer.remaining()){
flushBuffer();
if(lengthSize > dataBuffer.remaining()) return -1;
}
int oldLimit = sourceDataBuffer.limit();
sourceDataBuffer.limit(sourceDataBuffer.position() + sourceRecSize);
//write it here
try {
ByteBufferUtils.encodeLength(dataBuffer, sourceRecSize);
dataBuffer.put(sourceDataBuffer);
} catch (BufferOverflowException ex) {
throw new IOException("Input Buffer is not big enough to accomodate data record !");
}
// end write
sourceDataBuffer.limit(oldLimit);
length+=lengthSize;
nRecords++;
return length;
}
/**
* Stores one data record into buffer / file.
*
* @param data DataRecord to be stored
*@return number of bytes in the chunk after saving data
* @throws IOException
* @throws InterruptedException
*/
long put(DataRecord data) throws IOException, InterruptedException {
recordSize = data.getSizeSerialized();
final int lengthSize=ByteBufferUtils.lengthEncoded(recordSize);
// check that internal buffer has enough space
if ((recordSize + lengthSize) > dataBuffer.remaining()){
flushBuffer();
}
try {
ByteBufferUtils.encodeLength(dataBuffer, recordSize);
data.serialize(dataBuffer);
} catch (BufferOverflowException ex) {
throw new IOException("Input Buffer is not big enough to accomodate data record !");
}
length+=(recordSize+ lengthSize);
nRecords++;
return length;
}
/**
* Returns next record from the buffer - FIFO order.
*
*@param recordBuffer ByteBuffer into which store data
*@return ByteBuffer populated with record's data or NULL if
* no more record can be retrieved
*@exception IOException Description of Exception
* @throws InterruptedException
*@since September 17, 2002
*/
boolean get(ByteBuffer recordBuffer) throws IOException, InterruptedException {
if(!canRead){
throw new IOException("Buffer has not been rewind !");
}
if (nRecords > 0 && recordsRead>=nRecords){
return false;
}
// check that internal buffer has enough data to read data size
if (LEN_SIZE_SPECIFIER > dataBuffer.remaining()){
reloadBuffer();
if(LEN_SIZE_SPECIFIER > dataBuffer.remaining()) return false;
}
recordSize = ByteBufferUtils.decodeLength(dataBuffer);
// check that internal buffer has enough data to read data record
if (recordSize > dataBuffer.remaining()){
reloadBuffer();
if(recordSize > dataBuffer.remaining()) return false;
}
int oldLimit = dataBuffer.limit();
dataBuffer.mark(); //could be used later in reget method
dataBuffer.limit(dataBuffer.position() + recordSize);
recordBuffer.clear();
recordBuffer.put(dataBuffer);
recordBuffer.flip();
dataBuffer.limit(oldLimit);
recordsRead++;
return true;
}
/**
* Read again previously read record. Use caution when calling this
* method as it lifts most of the safety checks. Should be used
* only immediately after successful get(ByteBuffer) call
*
* @param recordBuffer
* @return
* @throws IOException
* @since 27.2.2007
*/
boolean reget(ByteBuffer recordBuffer) {
dataBuffer.reset();
int oldLimit = dataBuffer.limit();
dataBuffer.limit(dataBuffer.position() + recordSize);
recordBuffer.clear();
recordBuffer.put(dataBuffer);
recordBuffer.flip();
dataBuffer.limit(oldLimit);
return true;
}
// protected ByteBuffer bulkGetStart() throws IOException {
// final int recordSize;
// if(!canRead){
// throw new IOException("Buffer has not been rewind !");
// }
//
// if (nRecords > 0 && recordsRead>=nRecords){
// return null;
// }
// // check that internal buffer has enough data to read data size
// if (LEN_SIZE_SPECIFIER > dataBuffer.remaining()){
// reloadBuffer();
// if(LEN_SIZE_SPECIFIER > dataBuffer.remaining()) return null;
// }
// recordSize = ByteBufferUtils.decodeLength(dataBuffer);
//
// // check that internal buffer has enough data to read data record
// if (recordSize > dataBuffer.remaining()){
// reloadBuffer();
// if(recordSize > dataBuffer.remaining()) return null;
// }
// int oldLimit = dataBuffer.limit();
// dataBuffer.limit(dataBuffer.position() + recordSize);
// //write it here
//
// dataBuffer.limit(oldLimit);
// recordsRead++;
// return dataBuffer;
// }
/**
* Returns next record from the buffer - FIFO order.
* @param data DataRecord into which load the data
* @return
* @throws IOException
* @throws InterruptedException
*/
boolean get(DataRecord data) throws IOException, InterruptedException {
if(!canRead){
throw new IOException("Buffer has not been rewind !");
}
if (nRecords > 0 && recordsRead>=nRecords){
return false;
}
// check that internal buffer has enough data to read data size
if (LEN_SIZE_SPECIFIER > dataBuffer.remaining()) {
reloadBuffer();
if(LEN_SIZE_SPECIFIER > dataBuffer.remaining()) return false;
}
recordSize = ByteBufferUtils.decodeLength(dataBuffer);
// check that internal buffer has enough data to read data record
if (recordSize > dataBuffer.remaining()){
reloadBuffer();
if(recordSize > dataBuffer.remaining()) return false;
}
dataBuffer.mark();//could be used later for reget
data.deserialize(dataBuffer);
recordsRead++;
return true;
}
boolean reget(DataRecord data) {
dataBuffer.reset();
data.deserialize(dataBuffer);
return true;
}
/**
* Flushes in memory buffer into TMP file
*
*@exception IOException Description of Exception
* @throws InterruptedException
*@since September 17, 2002
*/
private void flushBuffer() throws IOException, InterruptedException {
try {
dataBuffer.flip();
tmpFileChannel.write(dataBuffer);
dataBuffer.clear();
} catch (ClosedChannelException e) {
throw new InterruptedException();
}
}
private void reloadBuffer() throws IOException, InterruptedException {
try {
dataBuffer.compact();
tmpFileChannel.read(dataBuffer);
dataBuffer.flip();
} catch (ClosedChannelException e) {
throw new InterruptedException();
}
}
public boolean isEmpty(){
return (length==0);
}
public String toString(){
return "start: "+offsetStart+" #records: "+nRecords+" length: "+length;
}
}
/**
* Returns previously set temporary directory where this DataRecordTape
* should create its file (temporary)
*
* @return
*/
public File getTmpDirectory() {
return tmpDirectory;
}
/**
* Allows to set the temporary directory in which this DataRecordTape will
* create temporary file to store data.
*
* @param tmpDirectory
*/
public void setTmpDirectory(File tmpDirectory) {
this.tmpDirectory = tmpDirectory;
}
}
| FIX: fix in DataRecordTape.
git-svn-id: 7003860f782148507aa0d02fa3b12992383fb6a5@4771 a09ad3ba-1a0f-0410-b1b9-c67202f10d70
| cloveretl.engine/src/org/jetel/data/tape/DataRecordTape.java | FIX: fix in DataRecordTape. | <ide><path>loveretl.engine/src/org/jetel/data/tape/DataRecordTape.java
<ide> // check that internal buffer has enough data to read data size
<ide> if (LEN_SIZE_SPECIFIER > sourceDataBuffer.remaining()){
<ide> sourceChunk.reloadBuffer();
<del> if(LEN_SIZE_SPECIFIER > sourceDataBuffer.remaining()) return -1;
<add> if(sourceDataBuffer.remaining() == 0) return -1;
<ide> }
<ide> recordSize = ByteBufferUtils.decodeLength(sourceDataBuffer);
<ide>
<ide> // check that internal buffer has enough data to read data size
<ide> if (LEN_SIZE_SPECIFIER > dataBuffer.remaining()){
<ide> reloadBuffer();
<del> if(LEN_SIZE_SPECIFIER > dataBuffer.remaining()) return false;
<add> if(dataBuffer.remaining() == 0) return false;
<ide> }
<ide> recordSize = ByteBufferUtils.decodeLength(dataBuffer);
<ide>
<ide> // check that internal buffer has enough data to read data size
<ide> if (LEN_SIZE_SPECIFIER > dataBuffer.remaining()) {
<ide> reloadBuffer();
<del> if(LEN_SIZE_SPECIFIER > dataBuffer.remaining()) return false;
<add> if(dataBuffer.remaining() == 0) return false;
<ide> }
<ide> recordSize = ByteBufferUtils.decodeLength(dataBuffer);
<ide> |
|
JavaScript | apache-2.0 | 24474cfa8f78681b6bfff38164caedf846239c29 | 0 | SpiderOak/so_client_html5,SpiderOak/so_client_html5 | /* SpiderOak html5 client Main app.
* Works with:
* - jquery.mobile-1.0.1.css
* - jquery-1.6.4.js
* - jquery.mobile-1.0.1.js
* - js_aux/misc.js - blather(), fragment_quote(), error_alert(), ...
* - Nibbler 2010-04-07 - base32 encode, decode, and enhance with encode_trim.
* - custom-scripting.js - jqm settings and contextual configuration
*/
/*
NOTES
- Content visits:
We intercept navigation to content (eg, $.mobile.changePage) repository
URLs and intervene via binding of handle_content_visit to jQuery mobile
"pagebeforechange" event. URLs included as href links must start with
'#' to trigger jQuery Mobile's navigation detection, which by default
tracks changes to location.hash. handle_content_visit() dispatches those
URLs it receives that reside within the ones satisfy .is_content_root_url(),
to which the root URLs are registered by the root visiting routines.
- My routines which return jQuery objects end in '$', and - following common
practice - my variables intended to contain jQuery objects start with '$'.
*/
// For misc.js:blather() and allowing dangerous stuff only during debugging.
SO_DEBUGGING = true;
var spideroak = function () {
/* SpiderOak application object, as a modular singleton. */
"use strict"; // ECMAScript 5
/* Private elements: */
/* ==== Object-wide settings ===== */
var generic = {
/* Settings not specific to a particular login session: */
// API v1.
// XXX base_host_url may vary according to brand package.
base_host_url: "https://spideroak.com",
combo_root_url: "https://home",
combo_root_page_id: "home",
original_shares_root_page_id: "original-home",
other_shares_root_page_id: "share-home",
storage_login_path: "/browse/login",
storage_logout_suffix: "logout",
storage_path_prefix: "/storage/",
original_shares_path_suffix: "shares",
shares_path_suffix: "/share/",
content_page_template_id: "content-page-template",
devices_query_expression: 'device_info=yes',
versions_query_expression: 'format=version_info',
home_page_id: 'home',
root_storage_node_label: "Devices",
preview_sizes: [25, 48, 228, 800],
dividers_threshold: 10,
filter_threshold: 20,
other_share_room_urls: {},
};
var my = {
/* Login session settings: */
username: null,
storage_web_url: null, // Location of storage web UI for user.
storage_root_url: null,
original_shares_root_url: null,
// All the service's actual shares reside within:
shares_root_url: generic.base_host_url + "/share/",
share_room_urls: {},
original_share_room_urls: {},
};
var base32 = new Nibbler({dataBits: 8,
codeBits: 5,
keyString: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',
pad: '='});
Nibbler.prototype.encode_trim = function (str) {
/* Base32 encoding with trailing "=" removed. */
return this.encode(str).replace(/=+$/, ''); }
/* Navigation handlers: */
function handle_content_visit(e, data) {
/* Intercept URL visits and intervene for repository content. */
var page = internalize_url(data.toPage);
if ((typeof page === "string")
&& (is_content_url(page)
|| document_addrs.hasOwnProperty(page))) {
e.preventDefault();
var mode_opts = query_params(page);
if (document_addrs.hasOwnProperty(page)) {
var current_internal = internalize_url(document.location.href);
return document_addrs[page].call(this, current_internal); }
else {
content_node_manager.get(page).visit(data.options,
mode_opts); }}}
function establish_traversal_handler() {
/* Establish page change event handler. */
$(document).bind("pagebeforechange.SpiderOak", handle_content_visit); }
/* ===== Content Root Registration ===== */
function set_storage_account(username, storage_host, storage_web_url) {
/* Register confirmed user-specific storage details. Return the
storage root URL.
'username' - the account name
'storage_host' - the server for the account
'storage_web_url' - the account's web UI entry address
*/
var storage_url = register_storage_root(storage_host, username,
storage_web_url);
if (! is_content_root_url(storage_url)) {
register_content_root_url(storage_url); }
if (remember_manager.active()) {
remember_manager.store({username: username,
storage_host: storage_host,
storage_web_url: storage_web_url}); }
// Now let's direct the caller to the combo root:
return my.combo_root_url; }
function clear_storage_account() {
/* Obliterate internal settings and all content nodes for a clean slate.
All share artifacts, original and other, are removed, as well
as registered storage. We do not remove persistent settings. */
Object.keys(my.original_share_room_urls).map(function (room_url) {
if (! is_other_share_room_url(room_url)) {
delete my.share_room_urls[room_url]; }})
my.original_share_room_urls = {};
if (my.original_shares_root_url) {
content_node_manager.clear_hierarchy(my.original_shares_root_url); }
my.original_shares_root_url = "";
if (my.storage_root_url) {
content_node_manager.clear_hierarchy(my.storage_root_url); }
my.storage_root_url = "";
content_node_manager.free(content_node_manager.get_combo_root());
my.username = "";
my.storage_host = "";
my.storage_web_url = ""; }
/* ===== Node-independent content URL categorization ===== */
// Managed content is organized within two content roots:
//
// - the storage root, my.storage_root_url, determined by the user's account
// - the public share root, which is the same across all accounts
//
// There is also a collection of the shares originated by the account,
// in the OriginalRootShareNode. Like all SpiderOak share rooms, the
// items are actually public shares, but the collection listing is only
// visible from within the account.
//
// Content urls are recognized by virtue of beginning with one of the
// registered content roots. The storage root is registered when the user
// logs in. The share rooms root is registered upon the registration of
// any share room.
function register_storage_root(host, username, storage_web_url) {
/* Identify user's storage root according to 'host' and 'username'.
The account's 'storage_web_url' is also conveyed.
Return the url. */
my.username = username;
my.storage_host = host;
my.storage_web_url = storage_web_url;
my.storage_root_url = (host
+ generic.storage_path_prefix
+ base32.encode_trim(username)
+ "/");
// Original root is determined by storage root:
register_original_shares_root();
return my.storage_root_url;
}
function register_original_shares_root() {
/* Identify original share rooms root url. Depends on established
storage root. Return the url. */
my.original_shares_root_url =
(my.storage_root_url + generic.original_shares_path_suffix); }
function register_share_room_url(url) {
/* Include url among the registered share rooms. Returns the url. */
my.share_room_urls[url] = true;
return url; }
function unregister_share_room_url(url) {
/* Remove 'url' from the registered share rooms. Persists the change
if remembering mode is active. Returns the url. */
if (my.share_room_urls.hasOwnProperty(url)) {
delete my.share_room_urls[url];
return url; }}
function register_original_share_room_url(url) {
/* Include url among the registered original rooms.
Also registers among the set of all familiar share room urls.
Returns the url. */
my.original_share_room_urls[url] = true;
register_share_room_url(url);
return url; }
function is_combo_root_url(url) {
return (url === my.combo_root_url); }
function is_content_root_url(url) {
/* True if the 'url' is for one of the root content items.
Doesn't depend on the url having an established node. */
return ((url === my.combo_root_url)
|| (url === my.storage_root_url)
|| (url === my.original_shares_root_url)
|| (url === my.shares_root_url)); }
function is_content_root_page_id(url) {
return ((url === generic.combo_root_page_id)
|| (url === generic.other_shares_root_page_id)
|| (url === generic.original_shares_root_page_id)); }
function is_share_room_url(url) {
/* True if the 'url' is for one of the familiar share rooms.
Doesn't depend on the url having an established node. */
return my.share_room_urls.hasOwnProperty(url); }
function is_original_share_room_url(url) {
/* True if the 'url' is for one of the original share rooms.
Doesn't depend on the url having an established node. */
return (my.original_share_room_urls.hasOwnProperty(url)); }
function is_other_share_room_url(url) {
/* True if the 'url' is for one of the original share rooms.
Doesn't depend on the url having an established node. */
return is_share_room_url(url) && (! is_original_share_room_url(url)); }
function is_storage_url(url) {
/* True if the URL is for a content item in the user's storage area.
Doesn't depend on the url having an established node. */
return (my.storage_root_url
&& (url.slice(0, my.storage_root_url.length)
=== my.storage_root_url)); }
function is_share_url(url) {
/* True if the URL is for a content item in the user's storage area.
Doesn't depend on the url having an established node. */
return (my.shares_root_url
&& (url.slice(0, my.shares_root_url.length)
=== my.shares_root_url)); }
function is_content_url(url) {
/* True if url within registered content roots. */
return (is_storage_url(url)
|| is_share_url(url)
|| is_combo_root_url(url)
|| is_content_root_url(url)
|| is_content_root_page_id(url)); }
function other_share_room_urls() {
/* Return an array of known share room urls that are not among the
ones originated by the current account, *including* ones from
peristence storage. Doesn't depend on the urls being
established as nodes. */
var others = Object.keys(pmgr.get('other_share_urls') || {});
others.map(function (candidate) {
if (! my.share_room_urls.hasOwnProperty(candidate)) {
register_share_room_url(candidate); }})
var all = Object.keys(my.share_room_urls);
return all.filter(is_other_share_room_url); }
/* ===== Data model ===== */
/* SpiderOak content includes storage (backups) and share rooms. The
data model distinguishes different kinds of those things - the
roots, devices, folders, and files - and wraps them in abstract
general types - the ContentNode and variants of it, where useful. */
function ContentNode(url, parent) {
/* Constructor for items representing stored content.
- 'url' is absolute URL for the collection's root (top) node.
- 'parent' is containing node. The root's parent is null.
See JSON data examples towards the bottom of this script.
*/
if ( !(this instanceof ContentNode) ) { // Coding failsafe.
throw new Error("Constructor called as a function");
}
if (url) { // Skip if we're in prototype assignment.
this.url = url;
this.root_url = parent ? parent.root_url : url;
this.query_qualifier = "";
this.parent_url = parent ? parent.url : null;
this.is_container = true; // Typically.
this.subdirs = []; // Urls of contained devices, folders.
this.files = []; // Urls of contained files.
this.$page = null; // This node's jQuery-ified DOM data-role="page"
this.lastfetched = false;
this.emblem = ""; // At least for debugging/.toString()
this.icon_path = ""; }}
ContentNode.prototype.free = function () {
/* Free composite content to make available for garbage collection. */
if (this.$page) {
this.$page.remove();
this.$page = null; }}
function StorageNode(url, parent) {
ContentNode.call(this, url, parent);
// All but the root storage nodes are contained within a device.
// The DeviceStorageNode sets the device url, which will trickle
// down to all its contents.
this.device_url = parent ? parent.device_url : null; }
StorageNode.prototype = new ContentNode();
function ShareNode(url, parent) {
/* Share room abstract prototype for collections, rooms, and contents */
ContentNode.call(this, url, parent);
this.root_url = parent ? parent.root_url : null;
this.room_url = parent ? parent.room_url : null; }
ShareNode.prototype = new ContentNode();
function RootContentNode(url, parent) {
/* Consolidated root of the storage and share content hierarchies. */
ContentNode.call(this, url, parent);
this.root_url = url;
this.emblem = "Root";
this.name = "Dashboard";
delete this.subdirs;
delete this.files; }
RootContentNode.prototype = new ContentNode();
RootContentNode.prototype.free = function () {
/* Free composite content to make available for garbage collection. */
if (this.$page) {
// Do not .remove() the page - it's the original, not a clone.
this.$page = null; }}
RootContentNode.prototype.loggedin_ish = function () {
/* True if we have enough info to be able to use session credentials. */
return (my.username && true); }
function RootStorageNode(url, parent) {
StorageNode.call(this, url, parent);
this.query_qualifier = "?" + generic.devices_query_expression;
this.emblem = "Root Storage";
this.stats = null;
delete this.files; }
RootStorageNode.prototype = new StorageNode();
function RootShareNode(url, parent) {
ShareNode.call(this, url, this);
this.emblem = "Root Share";
this.root_url = url; }
RootShareNode.prototype = new ShareNode();
function OtherRootShareNode(url, parent) {
RootShareNode.call(this, url, parent);
this.name = "Other Share Rooms";
this.emblem = "Other Share Rooms";
this.job_id = 0;
// Whitelist of methods eligible for invocation via mode_opts.action:
this.action_methods = {'collection_menu': true,
'remove_item': true,
'persist_item': true,
'unpersist_item': true}
}
OriginalRootShareNode.prototype = new RootShareNode();
function OriginalRootShareNode(url, parent) {
RootShareNode.call(this, url, parent);
this.name = "My Share Rooms";
this.emblem = "Originally Published Share Rooms"; }
OtherRootShareNode.prototype = new RootShareNode();
function DeviceStorageNode(url, parent) {
StorageNode.call(this, url, parent);
this.emblem = "Storage Device";
this.device_url = url; }
DeviceStorageNode.prototype = new StorageNode();
function RoomShareNode(url, parent) {
ShareNode.call(this, url, parent);
this.emblem = "Share Room";
this.room_url = url; }
RoomShareNode.prototype = new ShareNode();
function FolderContentNode(url, parent) {
/* Stub, for situating intermediary methods. */ }
function FileContentNode(url, parent) {
/* Stub, for situating intermediary methods. */ }
function FolderStorageNode(url, parent) {
this.emblem = "Storage Folder";
StorageNode.call(this, url, parent); }
FolderStorageNode.prototype = new StorageNode();
function FolderShareNode(url, parent) {
this.emblem = "Share Room Folder";
ShareNode.call(this, url, parent); }
FolderShareNode.prototype = new ShareNode();
function FileStorageNode(url, parent) {
this.emblem = "Storage File";
StorageNode.call(this, url, parent);
this.is_container = false;
delete this.subdirs;
delete this.files; }
FileStorageNode.prototype = new StorageNode();
function FileShareNode(url, parent) {
this.emblem = "Share Room File";
ShareNode.call(this, url, parent);
this.is_container = false;
delete this.subdirs;
delete this.files; }
FileShareNode.prototype = new ShareNode();
/* ===== Content type and role predicates ===== */
ContentNode.prototype.is_root = function () {
/* True if the node is a collections top-level item. */
return (this.url === this.root_url); }
ContentNode.prototype.is_device = function() {
return false; }
DeviceStorageNode.prototype.is_device = function() {
return true; }
/* ===== Remote data access ===== */
ContentNode.prototype.visit = function (chngpg_opts, mode_opts) {
/* Fetch current data from server, provision, layout, and present.
'chngpg_opts': framework changePage() options,
'mode_opts': node provisioning and layout modal settings. */
if (! this.up_to_date()) {
this.fetch_and_dispatch(chngpg_opts, mode_opts); }
else {
this.show(chngpg_opts, mode_opts); }}
RootContentNode.prototype.visit = function (chngpg_opts, mode_opts) {
/* Do the special visit of the consolidated storage/share root. */
// Trigger visits to the respective root content nodes in 'passive'
// mode so they do not focus the browser on themselves. 'notify' mode
// is also provoked, so they report their success or failure to our
// notify_subvisit_status() method.
//
// See docs/AppOverview.txt "Content Node navigation modes" for
// details about mode controls.
this.remove_status_message();
this.show(chngpg_opts, {});
if (! this.loggedin_ish()) {
// Not enough registered info to try authenticating:
this.authenticated(false);
this.layout(mode_opts);
this.show(chngpg_opts, {}); }
else {
var storage_root = content_node_manager.get(my.storage_root_url);
var our_mode_opts = {passive: true,
notify_callback:
this.notify_subvisit_status.bind(this),
notify_token: 'storage'};
$.extend(our_mode_opts, mode_opts);
try {
// Will chain via notify_callback:
storage_root.visit(chngpg_opts, our_mode_opts); }
catch (err) {
// XXX These failsafes should be in error handlers:
this.authenticated(false,
{status: 0, statusText: "System error"},
err);
this.layout(); }
// XXX Populate the familiar other share rooms.
// XXX Provide other share edit and "+" add controls - somewhere.
}}
OtherRootShareNode.prototype.visit = function (chngpg_opts, mode_opts) {
/* Obtain the known, non-original share rooms and present them. */
// Our content is the set of remembered urls, from:
// - those visited in this session
// - those remembered across sessions
this.remove_status_message();
if (mode_opts.hasOwnProperty('action')) {
var action = mode_opts.action;
if (this.action_methods.hasOwnProperty(action)) {
return this[action](mode_opts); }}
this.subdirs = other_share_room_urls();
// .add_item() will also remove invalid ones from this.subdirs:
this.subdirs.map(this.add_item.bind(this));
this.do_presentation(chngpg_opts, mode_opts); }
ContentNode.prototype.fetch_and_dispatch = function (chngpg_opts,
mode_opts) {
/* Retrieve this node's data and deploy it.
'chngpg_opts' - Options for the framework's changePage function
'mode_opts': node provisioning and layout modal settings.
- On success, call this.handle_visit_success() with the retrieved
JSON data, new Date() just prior to the retrieval, chngpg_opts,
mode_opts, a text status categorization, and the XMLHttpRequest
object.
- Otherwise, this.handle_visit_failure() is called with the
XMLHttpResponse object, chngpg_opts, mode_opts, the text status
categorization, and an exception object, present if an exception
was caught.
See the jQuery.ajax() documentation for XMLHttpResponse details.
*/
var when = new Date();
var url = this.url + this.query_qualifier;
$.ajax({url: url,
type: 'GET',
dataType: 'json',
cache: false,
success: function (data, status, xhr) {
this.handle_visit_success(data, when,
chngpg_opts, mode_opts,
status, xhr); }.bind(this),
error: function (xhr, statusText, thrown) {
this.handle_visit_failure(xhr, chngpg_opts, mode_opts,
statusText,
thrown)}.bind(this), })}
RootContentNode.prototype.notify_subvisit_status = function(succeeded,
token,
response) {
/* Callback passed to subordinate root content nodes to signal their
update disposition:
'succeeded': true for success, false for failure.
'token': token they were passed to identify the transaction,
'response': on failure: the resulting XHR object. */
if (token !== 'other-shares') {
this.authenticated(true); }
var $page = this.my_page$();
var selector = ((token === 'storage')
? "#my-storage-leader"
: "#my-rooms-leader")
var $leader = $(selector);
if (! succeeded) {
$.mobile.hidePageLoadingMsg();
if (token === "storage") {
this.authenticated(false, response);
this.layout(); }}
else {
this.layout();
if (token === 'storage') {
// Ensure we're current page and chain to original shares root.
this.layout();
this.show();
var our_mode_opts = {passive: true,
notify_callback:
this.notify_subvisit_status.bind(this),
notify_token: 'original-share'};
if (this.veiled) {
this.veil(false, $.mobile.hidePageLoadingMsg); }
this.authenticated(true, response);
var ps_root = cnmgr.get(my.original_shares_root_url, this);
ps_root.visit({}, our_mode_opts); }}}
OtherRootShareNode.prototype.notify_subvisit_status = function(succeeded,
token,
content) {
/* Callback for subordinate share nodes to signal their visit result:
'succeeded': true for success, false for failure.
'token': token we passed in to identify transaction and convey info:
[job_id, subnode_URL],
'content': on success: the jquery $(dom) for the populated content,
for failure: the resulting XHR object. */
// We ignore the content.
var $page = this.my_page$();
var sub_job_id = token[0];
var url = token[1];
var splat = url.split('/');
var share_id = base32.decode(splat[splat.length-3]);
var room_key = splat[splat.length-2];
if (succeeded !== true) {
this.remove_status_message('result');
var message = ("Sorry - <tt>"
+ share_id + "</tt> / <tt>" + room_key + "</tt> "
+ content.statusText + " (" + content.status + ")");
var remove = true;
if (content.status === 404) {
this.show_status_message(message); }
else {
message = [].concat(message, " - omit it?");
remove = confirm(message); }
if (remove) {
this.remove_item(url);
this.unpersist_item(url); }}
else {
this.remove_status_message('error'); }
if (sub_job_id === this.job_id) {
// Do update, whether or not it was successful:
this.subdirs = other_share_room_urls()
this.subdirs.sort(content_nodes_by_url_sorter)
this.do_presentation({}, {passive: true}); }}
ContentNode.prototype.handle_visit_success = function (data, when,
chngpg_opts,
mode_opts,
status, xhr) {
/* Deploy successfully obtained node data.
See ContentNode.fetch_and_dispatch() for parameter details. */
this.provision(data, when, mode_opts);
this.layout(mode_opts);
this.show(chngpg_opts, mode_opts);
if (mode_opts.notify_callback) {
mode_opts.notify_callback(true,
mode_opts.notify_token); }}
ContentNode.prototype.handle_visit_failure = function (xhr,
chngpg_opts,
mode_opts,
exception) {
/* Do failed visit error handling with 'xhr' XMLHttpResponse report. */
if (mode_opts.notify_callback) {
mode_opts.notify_callback(false, mode_opts.notify_token, xhr); }
else {
$.mobile.hidePageLoadingMsg();
alert("Visit '" + this.name + "' failed: "
+ xhr.statusText + " (" + xhr.status + ")");
var combo_root = content_node_manager.get_combo_root();
if (! is_combo_root_url(this.url)) {
// Recover upwards, eventually to the top:
$.mobile.changePage(this.parent_url
? this.parent_url
: combo_root.url); }}}
RootContentNode.prototype.handle_visit_failure = function (xhr,
chngpg_opts,
mode_opts,
exception) {
/* Do failed visit error handling with 'xhr' XMLHttpResponse report. */
this.layout();
this.authenticated(false, xhr, exception); }
RootContentNode.prototype.authenticated = function (succeeded, response,
exception) {
/* Present login challenge versus content, depending on access success.
'succeeded': true for success, false for failure.
'response': on failure: the resulting XHR object, if any.
'exception': on failure, exception caught by ajax machinery, if any.
*/
var $page = this.my_page$();
var $content_section = $page.find('.my-content');
var $login_section = $page.find('.login-section');
if (succeeded) {
// Show the content instead of the form
$login_section.hide();
this.remove_status_message();
$content_section.show();
if (remember_manager.active()) {
// remember_manager will store just the relevant fields.
remember_manager.store(my);
this.layout_header(); }}
else {
// Include the xhr.statusText in the form.
this.veil(false);
$content_section.hide();
$login_section.show();
var username;
if (remember_manager.active()
&& (username = persistence_manager.get('username'))) {
$('#my_login_username').val(username); }
if (response) {
var error_message = response.statusText;
if (exception) {
error_message += " - " + exception.message; }
this.show_status_message(error_message);
if (response.status === 401) {
// Unauthorized - expunge all privileged info:
clear_storage_account(); }}
// Hide the storage and original shares sections
$content_section.hide();
if (this.veiled) { this.veil(false); }}}
OtherRootShareNode.prototype.collection_menu = function (target_url) {
/* Present a menu of collection membership actions for 'target_url'. */
alert("OtherRootShareNode.collection_menu");
}
OtherRootShareNode.prototype.add_item_external = function (credentials) {
/* Visit a specified share room, according to 'credentials' object:
{username, password}.
Use this routine only for adding from outside the object - use
this.add_item(), instead, for internal operation.
*/
this.job_id += 1; // Entry
var share_id = credentials.shareid;
var room_key = credentials.password;
var message = (share_id + "</tt> / <tt>" + room_key + "</tt> ");
var new_share_url = (my.shares_root_url
+ base32.encode_trim(share_id)
+ "/" + room_key
+ "/");
if (is_other_share_room_url(new_share_url)) {
this.show_status_message(message + " already added"); }
else if (is_share_room_url(new_share_url)) {
this.show_status_message(message + ' already among "my" shares'); }
else {
var $sm = this.show_status_message("Added: " + message, 'result');
$sm.hide();
$sm.delay(1000).fadeIn(1000); // Give time for error to appear.
return this.add_item(new_share_url); }}
OtherRootShareNode.prototype.add_item = function (url) {
/* Visit a specified share room, according its' URL address.
Return the room object. */
register_share_room_url(url);
var room = content_node_manager.get(url, cnmgr.get_combo_root());
room.visit({},
{passive: true,
notify_callback: this.notify_subvisit_status.bind(this),
notify_token: [this.job_id, url]});
return room; }
OtherRootShareNode.prototype.remove_item_external = function (room_url) {
/* Omit a non-original share room from persistent and resident memory.
This is for use from outside of the object. Use .remove_item() for
internal object operation. */
this.job_id += 1;
this.remove_item(url); }
OtherRootShareNode.prototype.remove_item = function (room_url) {
/* Omit a non-original share room from the persistent and resident
collections. Returns true if the item was present, else false. */
if (is_other_share_room_url(room_url)) {
unregister_share_room_url(room_url);
this.unpersist_item(room_url);
return true; }
else { return false; }}
OtherRootShareNode.prototype.persist_item = function (room_url) {
/* Add a share rooms to the collection persistent non-originals. */
var persistents = pmgr.get("other_share_urls") || {};
if (! persistents.hasOwnProperty(room_url)) {
persistents[room_url] = true;
pmgr.set("other_share_urls", persistents); }}
OtherRootShareNode.prototype.unpersist_item = function (room_url) {
/* Omit a non-original share room from the persistent
collection. Returns true if the item was present, else false. */
var persistents = pmgr.get("other_share_urls") || {};
if (persistents.hasOwnProperty(room_url)) {
delete persistents[room_url];
pmgr.set("other_share_urls", persistents);
return true; }
else { return false; }}
/* ===== Containment ===== */
/* For content_node_manager.clear_hierarchy() */
ContentNode.prototype.contained_urls = function () {
return [].concat(this.subdirs, this.files); }
RootContentNode.prototype.contained_urls = function () {
return [].concat(this.storage_devices,
this.original_shares, this.shares); }
RootStorageNode.prototype.contained_urls = function () {
return [].concat(this.subdirs); }
FileStorageNode.prototype.contained_urls = function () {
return []; }
FileShareNode.prototype.contained_urls = function () {
return []; }
/* "Provisioning": Data model assimilation of fetched data */
ContentNode.prototype.provision = function (data, when, mode_opts) {
/* Populate node with JSON 'data'. 'when' is the data's current-ness.
'when' should be no more recent than the XMLHttpRequest.
*/
this.provision_preliminaries(data, when, mode_opts);
this.provision_populate(data, when, mode_opts); }
ContentNode.prototype.provision_preliminaries = function (data, when,
mode_opts) {
/* Do provisioning stuff generally useful for derived types. */
if (! when) {
throw new Error("Node provisioning without reliable time stamp.");
}
this.up_to_date(when); }
ContentNode.prototype.provision_populate = function (data, when,
mode_opts) {
/* Stub, must be overridden by type-specific provisionings. */
error_alert("Not yet implemented",
this.emblem
+ " type-specific provisioning implementation"); }
ContentNode.prototype.provision_items = function (data_items,
this_container,
url_base, url_element,
trailing_slash,
fields,
contents_parent) {
/* Register data item fields into subnodes of this node:
'data_items' - the object to iterate over for the data,
'this_container' - the container into which to place the subnodes,
'url_base' - the base url onto which the url_element is appended,
'url_element' - the field name for the url of item within this node,
'trailing_slash' - true: url is given a trailing slash if absent,
'fields' - an array of field names for properties to be copied (1),
'contents_parent' - the node to attribute as the subnodes parent (2).
(1) Fields are either strings, denoting the same attribute name in
the data item and subnode, or two element subarrays, with the
first element being the data attribute name and the second being
the attribute name for the subnode.
(2) The contained item's parent is not always this object, eg for
the content roots. */
var parent = content_node_manager.get(contents_parent);
data_items.map(function (item) {
var url = url_base + item[url_element];
if (trailing_slash && (url.slice(url.length-1) !== '/')) {
url += "/"; }
var subnode = content_node_manager.get(url, parent);
fields.map(function (field) {
if (field instanceof Array) {
subnode[field[1]] = item[field[0]]; }
else {
subnode[field] = item[field]; }})
// TODO Scaling - make subdirs an object for hashed lookup.
if (this_container.indexOf(url) === -1) {
this_container.push(url); }})}
RootStorageNode.prototype.provision_populate = function (data, when,
mode_opts) {
/* Embody the root storage node with 'data'.
'when' is time soon before data was fetched. */
var combo_root = content_node_manager.get_combo_root();
var url, dev, devdata;
// XXX ?:
this.name = my.username;
// TODO: We'll cook stats when UI is ready.
this.stats = data["stats"];
this.subdirs = [];
this.provision_items(data.devices, this.subdirs,
this.url, 'encoded', true,
['name', 'lastlogin', 'lastcommit'],
my.combo_root_url);
this.lastfetched = when; }
FolderContentNode.prototype.provision_populate = function (data, when) {
/* Embody folder content items with 'data'.
'when' is time soon before data was fetched. */
this.subdirs = [];
this.provision_items(data.dirs, this.subdirs, this.url, 1, true,
[[0, 'name']], this.url);
if (data.hasOwnProperty('files')) {
this.files = [];
var fields = ['name', 'size', 'ctime', 'mtime', 'versions'];
generic.preview_sizes.map(function (size) {
/* Add previews, if any, to the fields. */
if (("preview_" + size) in data.files) {
fields.push("preview_" + size); }})
this.provision_items(data.files, this.files, this.url, 'url', false,
fields, this.url); }
this.lastfetched = when; }
OriginalRootShareNode.prototype.provision_populate = function (data, when) {
/* Embody the root share room with 'data'.
'when' is time soon before data was fetched. */
this.subdirs = [];
var room_base = my.shares_root_url + data.share_id_b32 + "/";
this.provision_items(data.share_rooms, this.subdirs,
room_base, 'room_key', true,
[['room_name', 'name'],
['room_description', 'description'],
'room_key', 'share_id'],
my.combo_root_url);
this.subdirs.map(function (url) {
/* Ensure the contained rooms urls are registered as originals. */
register_original_share_room_url(url); });
this.lastfetched = when; }
DeviceStorageNode.prototype.provision_populate = function (data, when) {
/* Embody storage folder items with 'data'.
'when' is time soon before data was fetched. */
FolderStorageNode.prototype.provision_populate.call(this, data, when); }
RoomShareNode.prototype.provision_populate = function (data, when) {
/* Embody storage folder items with 'data'.
'when' is time soon before data was fetched. */
FolderShareNode.prototype.provision_populate.call(this, data,
when);
this.name = data.stats.room_name;
this.description = data.stats.description;
this.number_of_files = data.stats.number_of_files;
this.number_of_folders = data.stats.number_of_folders;
this.firstname = data.stats.firstname;
this.lastname = data.stats.lastname;
this.lastfetched = when; }
FolderStorageNode.prototype.provision_populate = function (data, when) {
/* Embody storage folder items with 'data'.
'when' is time soon before data was fetched. */
FolderContentNode.prototype.provision_populate.call(this, data, when); }
FolderShareNode.prototype.provision_populate = function (data, when){
/* Embody share room folder items with 'data'.
'when' is time soon before data was fetched. */
FolderContentNode.prototype.provision_populate.call(this, data, when); }
FileStorageNode.prototype.provision_populate = function (data, when) {
error_alert("Not yet implemented", "File preview"); }
ContentNode.prototype.up_to_date = function (when) {
/* True if provisioned data is considered current.
Optional 'when' specifies (new) time we were fetched. */
// The generic case offers no shortcut for determining up-to-date-ness.
if (when) { this.lastfetched = when; }
if (! this.lastfetched) { return false; }
// No intelligence yet.
return false; }
/* ===== Content node page presentation ===== */
ContentNode.prototype.my_page_id = function () {
/* Set the UI page id, escaping special characters as necessary. */
return this.url; }
RootContentNode.prototype.my_page_id = function () {
/* Set the UI page id, escaping special characters as necessary. */
return generic.combo_root_page_id; }
OtherRootShareNode.prototype.my_page_id = function () {
/* Set the UI page id, escaping special characters as necessary. */
return generic.other_shares_root_page_id; }
OriginalRootShareNode.prototype.my_page_id = function () {
/* Set the UI page id, escaping special characters as necessary. */
return generic.original_shares_root_page_id; }
ContentNode.prototype.show = function (chngpg_opts, mode_opts) {
/* Trigger UI focus on our content layout.
If mode_opts "passive" === true, don't do a changePage.
*/
var $page = this.my_page$();
if ($.mobile.activePage
&& ($.mobile.activePage[0].id !== this.my_page_id())
&& (!mode_opts.passive)) {
$.mobile.changePage($page, chngpg_opts); }
// Just in case, eg of refresh:
$.mobile.hidePageLoadingMsg(); }
OtherRootShareNode.prototype.do_presentation = function (chngpg_opts,
mode_opts) {
/* An exceptional, consolidated presentation routine. */
// For use by this.visit() and this.notify_subvisit_status().
this.subdirs.sort(content_nodes_by_url_sorter);
this.layout(mode_opts);
this.show(chngpg_opts, mode_opts);
if (mode_opts.notify_callback) {
mode_opts.notify_callback(true,
mode_opts.notify_token); }}
ContentNode.prototype.layout = function (mode_opts) {
/* Deploy content as markup on our page. */
this.layout_header(mode_opts);
this.layout_content(mode_opts);
this.layout_footer(mode_opts); }
OtherRootShareNode.prototype.layout = function (mode_opts) {
/* Deploy content as markup on our page. */
// Get a split button on each item to provoke an action menu:
var split_params = {url: this.url + '?action=collection_menu&target=',
icon: 'gear',
title: "Collection membership"};
mode_opts.split_button_url_append = split_params;
ContentNode.prototype.layout.call(this, mode_opts);
var $content_items = this.my_page$().find('.page-content')
if (this.subdirs.length === 0) {
$content_items.hide(); }
else {
$content_items.show(); }}
OtherRootShareNode.prototype.show = function (chngpg_opts, mode_opts) {
/* Deploy content as markup on our page. */
ContentNode.prototype.show.call(this, chngpg_opts, mode_opts);
deploy_focus_oneshot('#my_share_id', "pageshow"); }
RootContentNode.prototype.layout = function (chngpg_opts, mode_opts) {
/* Do layout arrangements - different than other node types. */
var $page = this.my_page$();
this.layout_header();
// Storage content section:
// We avoid doing layout of these when not authenticated so the
// re-presentation of the hidden sections doesn't show through.
var storage_subdirs = (my.storage_root_url
&& cnmgr.get(my.storage_root_url,
this).subdirs
|| [])
this.layout_content(mode_opts, storage_subdirs, false,
'.storage-list');
// My share rooms section:
var myshares_subdirs = (my.original_shares_root_url
&& cnmgr.get(my.original_shares_root_url,
this).subdirs
|| [])
this.layout_content(mode_opts, myshares_subdirs, false,
'.my-shares-list');
// Other share rooms section:
var other_share_urls = other_share_room_urls();
var $other_shares_nonempty = $page.find('.other-content');
var $other_shares_empty = $page.find('.other-no-content');
// Show the section or the button depending on whether there's content:
if (other_share_urls.length === 0) {
$other_shares_nonempty.hide();
$other_shares_empty.show(); }
else {
$other_shares_empty.hide();
$other_shares_nonempty.show();
this.layout_content(mode_opts, other_share_urls, false,
'.other-shares-list'); }
this.layout_footer(mode_opts); }
ContentNode.prototype.layout_header_fields = function(fields) {
/* Populate this content node's page header with these fields settings:
field.title: html (or just text) with the page label;
left_url: left-hand button URL; if absent left button not changed;
left_label: text for left-hand button, or empty to hide the button;
left_label = "-" => use the login URL;
right_url: right-hand button URL; if absent right button not changed;
right_label: text for right-hand button, or empty to hide the button;
*/
var $header = this.my_page$().find('[data-role="header"]');
var $label;
if (fields.hasOwnProperty('title')) {
$header.find('.header-title').html(elide(fields.title, 25)); }
if (fields.hasOwnProperty('right_url')) {
var $right_slot = $header.find('.header-right-slot');
$right_slot.attr('href', fields.right_url);
if (fields.hasOwnProperty('right_label')) {
if (! fields.right_label) {
$right_slot.hide(); }
else {
replace_button_text($right_slot, elide(fields.right_label,
15));
$right_slot.show(); }}}
if (fields.hasOwnProperty('left_url')) {
var $left_slot = $header.find('.header-left-slot');
if (fields.left_url === "-") {
var parsed = $.mobile.path.parseUrl(window.location.href);
fields.left_url = parsed.hrefNoHash; }
$left_slot.attr('href', fields.left_url);
if (fields.hasOwnProperty('left_label')) {
if (! fields.left_label) {
$left_slot.hide(); }
else {
replace_button_text($left_slot, elide(fields.left_label,
15));
$left_slot.show(); }}}}
RootContentNode.prototype.layout_header = function (mode_opts) {
/* Do special RootContentNode header layout. */
var $header = this.my_page$().find('[data-role="header"]');
var $logout_button = $header.find('.logout-button');
if (! this.loggedin_ish()) {
$logout_button.hide(); }
else {
$logout_button.show(); }}
StorageNode.prototype.layout_header = function(mode_opts) {
/* Fill in typical values for header fields of .my_page$().
Many storage node types will use these values as is, some will
replace them.
*/
var fields = {};
fields.right_url = ('#' + add_query_param(this.url,
"refresh", "true", true));
fields.right_label = "Refresh";
fields.title = this.name;
if (this.parent_url) {
var container = content_node_manager.get(this.parent_url);
fields.left_url = '#' + this.parent_url;
fields.left_label = container.name; }
this.layout_header_fields(fields); }
RootStorageNode.prototype.layout_header = function(mode_opts) {
/* Fill in typical values for header fields of .my_page$(). */
StorageNode.prototype.layout_header.call(this, mode_opts);
this.layout_header_fields({'title': "Storage Devices",
'left_label': "Home",
'left_url': "#" + this.parent_url}); }
ShareNode.prototype.layout_header = function(mode_opts) {
/* Fill in header fields of .my_page$(). */
var fields = {};
if (this.parent_url) {
var container = content_node_manager.get(this.parent_url);
fields.right_url = '#' + add_query_param(this.url,"refresh","true");
fields.right_label = "Refresh"
fields.left_url = '#' + this.parent_url;
fields.left_label = container.name;
fields.title = this.name; }
else {
fields.right_url = '#' + add_query_param(this.url, "mode", "edit");
fields.right_label = "Edit";
fields.left_url = '#' + add_query_param(this.url, 'mode', "add");
fields.left_label = "+";
fields.title = "ShareRooms"; }
this.layout_header_fields(fields); }
RootShareNode.prototype.layout_header = function(mode_opts) {
/* Fill in header fields of .my_page$(). */
ShareNode.prototype.layout_header.call(this, mode_opts);
var fields = {'right_url': '#' + add_query_param(this.url,
"mode", "edit"),
'right_label': "Edit"};
this.layout_header_fields(fields); }
ContentNode.prototype.layout_content = function (mode_opts,
subdirs,
files,
content_items_selector) {
/* Present this content node by adjusting its DOM data-role="page".
'mode_opts' adjust various aspects of provisioning and layout.
'subdirs' is an optional array of urls for contained directories,
otherwise this.subdirs is used;
'files' is an optional array of urls for contained files, otherwise
this.files is used;
'content_items_selector' optionally specifies the selector for
the listview to hold the items, via this.my_content_items$().
*/
var $page = this.my_page$();
var $content = $page.find('[data-role="content"]');
var $list = this.my_content_items$(content_items_selector);
if ($list.children().length) {
$list.empty(); }
subdirs = subdirs || this.subdirs;
var lensubdirs = subdirs ? subdirs.length : 0;
files = files || this.files;
var lenfiles = files ? files.length : 0;
var do_dividers = (lensubdirs + lenfiles) > generic.dividers_threshold;
var do_filter = (lensubdirs + lenfiles) > generic.filter_threshold;
function insert_item($item) {
if ($cursor === $list) { $cursor.append($item); }
else { $cursor.after($item); }
$cursor = $item; }
function conditionally_insert_divider(t) {
if (do_dividers && t && (t[0].toUpperCase() !== curinitial)) {
curinitial = t[0].toUpperCase();
indicator = divider_prefix + curinitial;
$item = $('<li data-role="list-divider" id="divider-'
+ indicator + '">' + indicator + '</li>')
insert_item($item); }}
function insert_subnode(suburl) {
var subnode = content_node_manager.get(suburl, this);
conditionally_insert_divider(subnode.name);
insert_item(subnode.layout_item$(mode_opts)); }
if (lensubdirs + lenfiles === 0) {
$list.append($('<li title="Empty" class="empty-placeholder"/>')
.html('<span class="empty-sign ui-btn-text">'
+ '∅</span>')); }
else {
var $item;
var curinitial, divider_prefix, indicator = "";
var $cursor = $list;
if (do_filter) { $list.attr('data-filter', 'true'); }
if (lensubdirs) {
divider_prefix = "/";
for (var i=0; i < subdirs.length; i++) {
insert_subnode(subdirs[i]); }}
if (lenfiles) {
divider_prefix = "";
for (var i=0; i < files.length; i++) {
insert_subnode(files[i]); }}}
$page.page();
$list.listview("refresh");
return $page; }
FolderContentNode.prototype.layout_item$ = function(mode_opts) {
/* Return a folder-like content item's description as jQuery item.
Optional:
mode_opts['split_button_url_append']: {icon:, title:, url:}
- construct a split button, appending node's url onto passed url.
*/
var $a = $('<a/>').attr('class', "compact-vertical");
$a.attr('href', "#" + this.url);
$a.html($('<h4/>').html(this.name));
var $it = $('<li/>').append($a);
if (mode_opts && mode_opts.hasOwnProperty('split_button_url_append')) {
var split_params = mode_opts.split_button_url_append;
$a = $('<a/>');
$a.attr('href', '#' + split_params.url + this.url);
$a.attr('data-icon', split_params.icon);
$a.attr('title', split_params.title);
$it.find('a').after($a); }
$it.attr('data-filtertext', this.name);
return $it; }
DeviceStorageNode.prototype.layout_item$ = function(mode_opts) {
/* Return a storage device's description as a jQuery item. */
return FolderStorageNode.prototype.layout_item$.call(this); }
FolderStorageNode.prototype.layout_item$ = function(mode_opts) {
/* Return a storage folder's description as a jQuery item. */
return FolderContentNode.prototype.layout_item$.call(this, mode_opts); }
FolderShareNode.prototype.layout_item$ = function(mode_opts) {
/* Return a share room folder's description as a jQuery item. */
return FolderContentNode.prototype.layout_item$.call(this, mode_opts); }
RoomShareNode.prototype.layout_item$ = function(mode_opts) {
/* Return a share room's description as a jQuery item. */
return FolderShareNode.prototype.layout_item$.call(this,
mode_opts); }
FileContentNode.prototype.layout_item$ = function(mode_opts) {
/* Return a file-like content node's description as a jQuery item. */
var $it = $('<li data-mini="true"/>');
$it.attr('data-filtertext', this.name);
var type = classify_file_by_name(this.name);
var pretty_type = type ? (type + ", ") : "";
var $details = $('<p>' + pretty_type + bytesToSize(this.size) +'</p>');
var date = new Date(this.mtime*1000);
var day_splat = date.toLocaleDateString().split(",");
var $date = $('<p class="ul-li-aside">'
+ day_splat[1] + "," + day_splat[2]
+ " " + date.toLocaleTimeString()
+'</p>');
var $table = $('<table width="100%"/>');
var $td = $('<td colspan="2"/>').append($('<h4/>').html(this.name));
$table.append($('<tr/>').append($td));
var $tr = $('<tr/>');
$tr.append($('<td/>').append($details).attr('wrap', "none"));
$tr.append($('<td/>').append($date).attr('align', "right"));
$table.append($tr);
var $href = $('<a/>');
$href.attr('href', this.url);
$href.attr('class', "compact-vertical");
$href.append($table);
$it.append($href);
// XXX use classification to select an icon:
$it.attr('data-icon', "false");
return $it; }
FileStorageNode.prototype.layout_item$ = function(mode_opts) {
/* Return a storage file's description as a jQuery item. */
return FileContentNode.prototype.layout_item$.call(this, mode_opts); }
FileShareNode.prototype.layout_item$ = function(mode_opts) {
/* Return a storage file's description as a jQuery item. */
return FileContentNode.prototype.layout_item$.call(this, mode_opts); }
ContentNode.prototype.layout_footer = function(mode_opts) {
/* Return markup with general and specific legend fields and urls. */
// XXX Not yet implemented.
}
ContentNode.prototype.my_page_from_dom$ = function () {
/* Return a jquery DOM search for my page, by id. */
return $('#' + fragment_quote(this.my_page_id())); }
ContentNode.prototype.my_page$ = function (reinit) {
/* Return this node's jQuery page object, producing if not present.
Optional 'reinit' means to discard existing page, if any,
forcing clone of a new copy.
If not present, we get a clone of the storage page template, and
situate the clone after the storage page template.
*/
if (reinit && this.$page) {
this.$page.remove();
delete this.$page; }
if (! this.$page) {
var $template = this.get_storage_page_template$();
if (! $template) {
error_alert("Missing markup",
"Expected page #"
+ generic.content_page_template_id
+ " not present."); }
this.$page = $template.clone();
this.$page.attr('id', this.my_page_id());
this.$page.attr('data-url', this.my_page_id());
// Include our page in the DOM, after the storage page template:
$template.after(this.my_page$()); }
return this.$page; }
OtherRootShareNode.prototype.my_page$ = function () {
return RootContentNode.prototype.my_page$.call(this); }
RootContentNode.prototype.my_page$ = function () {
/* Return the special case of the root content nodes actual page. */
return (this.$page
? this.$page
: (this.$page = $("#" + this.my_page_id()))); }
ContentNode.prototype.my_content_items$ = function (selector) {
/* Return this node's jQuery contents litview object.
Optional 'selector' is used, otherwise '.content-items'. */
return this.my_page$().find(selector || '.content-items'); }
ContentNode.prototype.get_storage_page_template$ = function() {
return $("#" + generic.content_page_template_id); }
/* ===== Resource managers ===== */
var persistence_manager = {
/* Maintain domain-specific persistent settings, using localStorage.
- Value structure is maintained using JSON.
- Use .get(name), .set(name, value), and .remove(name).
- .keys() returns an array of all stored keys.
- .length returns the number of keys.
*/
// NOTE Compat: versions of android < 2.1 do not support localStorage.
// They do support gears sqlite. lawnchair would make it
// easy to switch between them.
get: function (name) {
/* Retrieve the value for 'name' from persistent storage. */
return JSON.parse(localStorage.getItem(name)); },
set: function (name, value) {
/* Preserve name and value in persistent storage.
Return the settings manager, for chaining. */
localStorage.setItem(name, JSON.stringify(value));
return persistence_manager; },
remove: function (name) {
/* Delete persistent storage of name. */
localStorage.removeItem(name); },
keys: function () { return Object.keys(localStorage); },
};
// Gratuitous 'persistence_manager.length' getter, for a technical example:
persistence_manager.__defineGetter__('length',
function() {
return localStorage.length; });
var pmgr = persistence_manager; // Compact name.
var remember_manager = {
/* Maintain user account info in persistent storage. */
// "remember_me" field not in fields, so only it is retained when
// remembering is disabled:
fields: ['username', 'storage_host', 'storage_web_url'],
unset: function (disposition) {
/* True if no persistent remember manager settings are found. */
return persistence_manager.get("remember_me") === null; },
active: function (disposition) {
/* Report or set "Remember Me" persistent account info retention.
'disposition':
- activate if truthy,
- return status if not passed in, ie undefined,
- deactivate otherwise.
Deactivating entails wiping the retained account info settings.
*/
if (disposition) {
return persistence_manager.set("remember_me", true); }
else if (typeof disposition === "undefined") {
return persistence_manager.get("remember_me") || false; }
else {
remember_manager.fields.map(function (key) {
persistence_manager.remove(key); });
return persistence_manager.set("remember_me", false); }},
fetch: function () {
/* Return remembered account info . */
var got = {};
remember_manager.fields.map(function (key) {
got[key] = persistence_manager.get(key); });
return got; },
store: function (obj) {
/* Preserve account info, obtaining specific fields from 'obj'.
Error is thrown if obj lacks any fields. */
remember_manager.fields.map(function (key) {
if (! obj.hasOwnProperty(key)) {
throw new Error("Missing field: " + key); }
persistence_manager.set(key, obj[key]); })},
remove_storage_host: function () {
/* How to inhibit auto-login, without losing the convenience of
a remembered username, in the absence of a way to remove the
authentication cookies. */
persistence_manager.remove('storage_host'); },
};
var remgr = remember_manager;
var content_node_manager = function () {
/* A singleton utility for getting and removing content node objects.
"Getting" means finding existing ones or else allocating new ones.
*/
// Type of newly minted nodes are according to get parameters.
// ???: Cleanup? Remove nodes when ascending above them?
// ???:
// - prefetch offspring layer and defer release til 2 layers above.
// - make fetch of multiple items contingent to device lastcommit time.
/* Private */
var by_url = {};
/* Public */
return {
get_combo_root: function () {
return this.get(my.combo_root_url, null); },
get: function (url, parent) {
/* Retrieve a node according to 'url'.
'parent' is required for production of new nodes,
which are produced on first reference.
Provisioning nodes with remote data is done elsewhere,
not here.
*/
url = url.split('?')[0]; // Strip query string.
var got = by_url[url];
if (! got) {
// Roots:
if (is_content_root_url(url)) {
if (is_combo_root_url(url)) {
got = new RootContentNode(url, parent); }
else if (url === my.storage_root_url) {
got = new RootStorageNode(url, parent); }
else if (url === my.original_shares_root_url) {
got = new OriginalRootShareNode(url, parent); }
else if (url === my.shares_root_url) {
got = new OtherRootShareNode(url, parent); }
else {
throw new Error("Content model management error");}}
// Contents:
else if (parent && (is_combo_root_url(parent.url))) {
// Content node just below a root:
if (is_storage_url(url)) {
got = new DeviceStorageNode(url, parent); }
else {
got = new RoomShareNode(url, parent); }}
else if (url.charAt(url.length-1) !== "/") {
// No trailing slash.
if (is_storage_url(url)) {
got = new FileStorageNode(url, parent); }
else {
got = new FileShareNode(url, parent); }}
else {
if (is_storage_url(url)) {
got = new FolderStorageNode(url, parent); }
else {
got = new FolderShareNode(url, parent); }
}
by_url[url] = got;
}
return got; },
free: function (node) {
/* Remove a content node from index and free it for gc. */
if (by_url.hasOwnProperty(node.url)) {
delete by_url[node.url]; }
node.free(); },
clear_hierarchy: function (url) {
/* Free node at 'url' and its recursively contained nodes. */
var it = this.get(url);
var suburls = it.contained_urls();
for (var i=0; i < suburls.length; i++) {
this.clear_hierarchy(suburls[i]); }
this.free(it); },
// Expose the by_url registry when debugging:
bu: (SO_DEBUGGING ? by_url : null),
}
}()
var cnmgr = content_node_manager; // Compact name, for convenience.
/* ===== Login ===== */
function go_to_entrance() {
/* Visit the entrance page. Depending on session state, it might
present a login challenge or it might present the top-level
contents associated with the logged-in account. */
$.mobile.changePage(content_node_manager.get_combo_root().url); }
function storage_login(login_info, url) {
/* Login to storage account and commence browsing at devices.
'login_info': An object with "username" and "password" attrs.
'url': An optional url, else generic.storage_login_path is used.
We provide for redirection to specific alternative servers
by recursive calls. See:
https://spideroak.com/apis/partners/web_storage_api#Loggingin
*/
var login_url;
var server_host_url;
var parsed;
if (url
&& (parsed = $.mobile.path.parseUrl(url))
&& ["http:", "https:"].indexOf(parsed.protocol) !== -1) {
server_host_url = parsed.domain;
login_url = url; }
else {
server_host_url = generic.base_host_url;
login_url = (server_host_url + generic.storage_login_path); }
$.ajax({
url: login_url,
type: 'POST',
dataType: 'text',
data: login_info,
success: function (data) {
var match = data.match(/^(login|location):(.+)$/m);
if (!match) {
error_alert('Temporary server failure',
'Please try again later.');
} else if (match[1] === 'login') {
if (match[2].charAt(0) === "/") {
login_url = server_host_url + match[2];
} else {
login_url = match[2];
}
storage_login(login_info, login_url);
} else {
// Browser haz auth cookies, we haz relative location.
// Go there, and machinery will intervene to handle it.
$.mobile.changePage(
set_storage_account(login_info['username'],
server_host_url,
match[2]));
}},
error: function (xhr) {
$.mobile.hidePageLoadingMsg();
var username;
if (remember_manager.active()
&& (username = persistence_manager.get('username'))) {
$('#my_login_username').val(username); }
error_alert("Storage login", xhr.status); },
}); }
function storage_logout() {
/* Conclude storage login, clearing credentials and stored data.
Wind up back on the main entry page.
*/
function finish() {
clear_storage_account();
if (remember_manager.active()) {
// The storage server doesn't remove cookies, so we inhibit
// relogin by removing the persistent info about the
// storage host. This leaves the username intact as a
// "remember" convenience for the user.
remember_manager.remove_storage_host(); }
go_to_entrance(); }
var combo_root = content_node_manager.get_combo_root();
combo_root.veil(true);
if (! combo_root.loggedin_ish()) {
// Can't reach logout location without server - just clear and bail.
finish(); }
else {
// SpiderOak's logout url doesn't (as of 2012-06-15) remove cookies!
$.ajax({url: my.storage_root_url + generic.storage_logout_suffix,
type: 'GET',
success: function (data) {
finish(); },
error: function (xhr) {
console.log("Logout ajax fault: "
+ xhr.status
+ " (" + xhr.statusText + ")");
finish(); }}); }}
RootContentNode.prototype.veil = function (conceal, callback) {
/* If 'conceal' is true, conceal our baudy body. Otherwise, gradually
reveal and position the cursor in the username field.
Optional callback is a function to invoke as part of the un/veiling.
*/
function do_focus() {
var $username = $('#my_login_username');
if ($username.val() === "") { $username.focus(); }
else { $('#my_login_password').focus(); }}
function do_focus_and_callback() {
do_focus();
if (callback) { callback(); }}
var selector = '#home [data-role="content"]';
if (conceal) {
$(selector).hide(0, callback);
this.veiled = true; }
else {
this.veiled = false;
// Surprisingly, doing focus before dispatching fadeIn doesn't work.
// Also, username field focus doesn't *always* work before the
// delay is done, hence the redundancy. Sigh.
$(selector).fadeIn(3000, do_focus_and_callback);
do_focus(); }}
function prep_login_form(content_selector, submit_handler, name_field,
do_fade) {
/* Instrument form within 'content_selector' to submit with
'submit_handler'. 'name_field' is the id of the form field with
the login name, "password" is assumed to be the password field
id. If 'do_fade' is true, the content portion of the page will
be rigged to fade on form submit, and on pagechange reappear
gradually. In any case, the password value will be cleared, so
it can't be reused.
*/
var $content = $(content_selector);
var $form = $(content_selector + " form");
var $password = $form.find('input[name=password]');
var $name = $form.find('input[name=' + name_field + ']');
var $submit = $form.find('[type="submit"]');
var sentinel = new submit_button_sentinel([$name, $password], $submit)
$name.bind('keyup', sentinel);
$password.bind('keyup', sentinel);
$submit.button()
sentinel();
var $remember_widget = $form.find('#remember-me');
var remembering = remember_manager.active();
if (remembering && ($remember_widget.val() !== "on")) {
$remember_widget.find('option[value="on"]').attr('selected',
'selected');
$remember_widget.val("on");
// I believe the reason we need to also .change() is because
// the presented slider is just tracking the actual select widget.
$remember_widget.trigger('change'); }
else if (!remember_manager.unset() && !remembering) {
$remember_widget.val("off");
$remember_widget.trigger('change'); }
var name_field_val = pmgr.get(name_field);
if (name_field_val
&& ($remember_widget.length > 0)
&& ($remember_widget.val() === "on")) {
$name.attr('value',name_field_val); }
$form.submit(function () {
var $remember_widget = $form.find('#remember-me');
var $name = $('input[name=' + name_field + ']', this);
var $password = $('input[name=password]', this);
var data = {};
if (($name.val() === "") || ($password.val() === "")) {
// Minimal - the submit button sentinel should prevent this.
return false; }
data[name_field] = $name.val();
$name.val("");
if ($remember_widget.length > 0) {
// Preserve whether or not we're remembering, so on a
// successful visits we'll know whether to preserve data:
if ($remember_widget.val() === "on") {
remember_manager.active(true); }
else {
remember_manager.active(false); }}
data['password'] = $password.val();
if (do_fade) {
var combo_root = content_node_manager.get_combo_root();
combo_root.veil(true, function() { $password.val(""); });
var unhide_form_oneshot = function(event, data) {
$content.show('fast');
$.mobile.hidePageLoadingMsg();
$(document).unbind("pagechange", unhide_form_oneshot);
$(document).unbind("error", unhide_form_oneshot); }
$(document).bind("pagechange", unhide_form_oneshot)
$(document).bind("error", unhide_form_oneshot); }
else {
$name.val("");
$password.val(""); }
$name.focus();
submit_handler(data);
return false; }); }
/* ===== Public interface ===== */
// ("public_interface" because "public" is reserved in strict mode.)
var public_interface = {
init: function () {
/* Do preliminary setup and launch into the combo root. */
// Setup traversal hook:
establish_traversal_handler();
my.combo_root_url = generic.combo_root_url;
var combo_root = content_node_manager.get_combo_root();
var other_shares = content_node_manager.get(my.shares_root_url);
// Properly furnish login form:
prep_login_form('.nav_login_storage', storage_login,
'username', true);
prep_login_form('.nav_login_share',
other_shares.add_item_external.bind(other_shares),
'shareid', false);
// Hide everything below the banner, for subsequent unveiling:
combo_root.veil(true);
// Try a storage account if available from persistent settings
if (remember_manager.active()) {
var settings = remember_manager.fetch();
if (settings.username && settings.storage_host) {
set_storage_account(settings.username,
settings.storage_host,
settings.storage_web_url); }}
// ... and go:
$.mobile.changePage(combo_root.url); },
}
/* ===== Boilerplate ===== */
ContentNode.prototype.show_status_message = function (html, kind) {
/* Inject 'html' into the page DOM as a status message. Optional
'kind' is the status message kind - currently, 'result' and
'error' have distinct color styles, the default is 'error'.
Returns a produced $status_message object. */
kind = kind || 'error';
var selector = '.' + kind + '-status-message';
var $page = this.my_page$();
var $sm = $page.find(selector)
if ($sm.length > 0) {
$sm.html(html);
$sm.listview(); }
else {
var $li = $('<li class="status-message '
+ kind + '-status-message">');
$li.html(html);
$sm = $('<ul data-role="listview"/>');
$sm.append($li);
$page.find('[data-role="header"]').after($sm);
$sm.listview();
$sm.show(); }
return $sm; }
ContentNode.prototype.remove_status_message = function (kind) {
/* Remove existing status message of specified 'kind' (default,
all), if present. */
var selector = (kind
? '.' + kind + '-status-message'
: '.status-message');
var $page = this.my_page$();
var $sm = $page.find(selector);
if ($sm.length !== 0) {
$sm.remove(); }}
ContentNode.prototype.toString = function () {
return "<" + this.emblem + ": " + this.url + ">"; }
var document_addrs = {
/* Map specific document fragment addresses from the application
document to internal functions/methods. */
logout: storage_logout,
}
function internalize_url(obj) {
/* Return the "internal" version of the 'url'.
- For non-string objects, returns the object
- For fragments of the application code's url, returns the fragment
(sans the '#'),
- Translates page-ids for root content nodes to their urls,
- Those last two Combined transforms fragment references to root
content pages to the urls of those pages.
main body is that of the application. Otherwise, the original
object is returned. */
if (typeof obj !== "string") { return obj; }
if (obj.split('#')[0] === window.location.href.split('#')[0]) {
obj = obj.split('#')[1]; }
if (document_addrs.hasOwnProperty(obj)) {
return obj; }
switch (obj) {
case (generic.combo_root_page_id):
return generic.combo_root_url;
case (generic.original_shares_root_page_id):
return my.original_shares_root_url;
case (generic.other_shares_root_page_id):
return my.shares_root_url;
default: return obj; }}
function content_nodes_by_url_sorter(prev, next) {
var prev_str = prev, next_str = next;
var prev_name = content_node_manager.get(prev).name;
var next_name = content_node_manager.get(next).name;
if (prev_name && next_name) {
prev_str = prev_name, next_str = next_name; }
if (prev_str < next_str) { return -1; }
else if (prev_str > next_str) { return 1; }
else { return 0; }}
if (SO_DEBUGGING) {
// Expose the managers for access while debugging:
public_interface.cnmgr = cnmgr;
public_interface.pmgr = pmgr; }
/* ===== Here we go: ===== */
return public_interface;
}();
$(document).ready(function () {
"use strict"; // ECMAScript 5
// Development convenience: Go back to start page on full document reload.
// All the internal application state is gone, anyway.
if (window.location.hash) {
$.mobile.changePage(window.location.href.split('#')[0]); }
spideroak.init();
});
| SpiderOak.js | /* SpiderOak html5 client Main app.
* Works with:
* - jquery.mobile-1.0.1.css
* - jquery-1.6.4.js
* - jquery.mobile-1.0.1.js
* - js_aux/misc.js - blather(), fragment_quote(), error_alert(), ...
* - Nibbler 2010-04-07 - base32 encode, decode, and enhance with encode_trim.
* - custom-scripting.js - jqm settings and contextual configuration
*/
/*
NOTES
- Content visits:
We intercept navigation to content (eg, $.mobile.changePage) repository
URLs and intervene via binding of handle_content_visit to jQuery mobile
"pagebeforechange" event. URLs included as href links must start with
'#' to trigger jQuery Mobile's navigation detection, which by default
tracks changes to location.hash. handle_content_visit() dispatches those
URLs it receives that reside within the ones satisfy .is_content_root_url(),
to which the root URLs are registered by the root visiting routines.
- My routines which return jQuery objects end in '$', and - following common
practice - my variables intended to contain jQuery objects start with '$'.
*/
// For misc.js:blather() and allowing dangerous stuff only during debugging.
SO_DEBUGGING = true;
var spideroak = function () {
/* SpiderOak application object, as a modular singleton. */
"use strict"; // ECMAScript 5
/* Private elements: */
/* ==== Object-wide settings ===== */
var defaults = {
/* Settings not specific to a particular login session: */
// API v1.
// XXX base_host_url may vary according to brand package.
base_host_url: "https://spideroak.com",
combo_root_url: "https://home",
combo_root_page_id: "home",
original_shares_root_page_id: "original-home",
other_shares_root_page_id: "share-home",
storage_login_path: "/browse/login",
storage_logout_suffix: "logout",
storage_path_prefix: "/storage/",
original_shares_path_suffix: "shares",
shares_path_suffix: "/share/",
content_page_template_id: "content-page-template",
devices_query_expression: 'device_info=yes',
versions_query_expression: 'format=version_info',
home_page_id: 'home',
root_storage_node_label: "Devices",
preview_sizes: [25, 48, 228, 800],
dividers_threshold: 10,
filter_threshold: 20,
other_share_room_urls: {},
};
var my = {
/* Login session settings: */
username: null,
storage_web_url: null, // Location of storage web UI for user.
storage_root_url: null,
original_shares_root_url: null,
// All the service's actual shares reside within:
shares_root_url: defaults.base_host_url + "/share/",
share_room_urls: {},
original_share_room_urls: {},
};
var base32 = new Nibbler({dataBits: 8,
codeBits: 5,
keyString: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',
pad: '='});
Nibbler.prototype.encode_trim = function (str) {
/* Base32 encoding with trailing "=" removed. */
return this.encode(str).replace(/=+$/, ''); }
/* Navigation handlers: */
function handle_content_visit(e, data) {
/* Intercept URL visits and intervene for repository content. */
var page = internalize_url(data.toPage);
if ((typeof page === "string")
&& (is_content_url(page)
|| document_addrs.hasOwnProperty(page))) {
e.preventDefault();
var mode_opts = query_params(page);
if (document_addrs.hasOwnProperty(page)) {
var current_internal = internalize_url(document.location.href);
return document_addrs[page].call(this, current_internal); }
else {
content_node_manager.get(page).visit(data.options,
mode_opts); }}}
function establish_traversal_handler() {
/* Establish page change event handler. */
$(document).bind("pagebeforechange.SpiderOak", handle_content_visit); }
/* ===== Content Root Registration ===== */
function set_storage_account(username, storage_host, storage_web_url) {
/* Register confirmed user-specific storage details. Return the
storage root URL.
'username' - the account name
'storage_host' - the server for the account
'storage_web_url' - the account's web UI entry address
*/
var storage_url = register_storage_root(storage_host, username,
storage_web_url);
if (! is_content_root_url(storage_url)) {
register_content_root_url(storage_url); }
if (remember_manager.active()) {
remember_manager.store({username: username,
storage_host: storage_host,
storage_web_url: storage_web_url}); }
// Now let's direct the caller to the combo root:
return my.combo_root_url; }
function clear_storage_account() {
/* Obliterate internal settings and all content nodes for a clean slate.
All share artifacts, original and other, are removed, as well
as registered storage. We do not remove persistent settings. */
Object.keys(my.original_share_room_urls).map(function (room_url) {
if (! is_other_share_room_url(room_url)) {
delete my.share_room_urls[room_url]; }})
my.original_share_room_urls = {};
if (my.original_shares_root_url) {
content_node_manager.clear_hierarchy(my.original_shares_root_url); }
my.original_shares_root_url = "";
if (my.storage_root_url) {
content_node_manager.clear_hierarchy(my.storage_root_url); }
my.storage_root_url = "";
content_node_manager.free(content_node_manager.get_combo_root());
my.username = "";
my.storage_host = "";
my.storage_web_url = ""; }
/* ===== Node-independent content URL categorization ===== */
// Managed content is organized within two content roots:
//
// - the storage root, my.storage_root_url, determined by the user's account
// - the public share root, which is the same across all accounts
//
// There is also a collection of the shares originated by the account,
// in the OriginalRootShareNode. Like all SpiderOak share rooms, the
// items are actually public shares, but the collection listing is only
// visible from within the account.
//
// Content urls are recognized by virtue of beginning with one of the
// registered content roots. The storage root is registered when the user
// logs in. The share rooms root is registered upon the registration of
// any share room.
function register_storage_root(host, username, storage_web_url) {
/* Identify user's storage root according to 'host' and 'username'.
The account's 'storage_web_url' is also conveyed.
Return the url. */
my.username = username;
my.storage_host = host;
my.storage_web_url = storage_web_url;
my.storage_root_url = (host
+ defaults.storage_path_prefix
+ base32.encode_trim(username)
+ "/");
// Original root is determined by storage root:
register_original_shares_root();
return my.storage_root_url;
}
function register_original_shares_root() {
/* Identify original share rooms root url. Depends on established
storage root. Return the url. */
my.original_shares_root_url =
(my.storage_root_url + defaults.original_shares_path_suffix); }
function register_share_room_url(url) {
/* Include url among the registered share rooms. Returns the url. */
my.share_room_urls[url] = true;
return url; }
function unregister_share_room_url(url) {
/* Remove 'url' from the registered share rooms. Persists the change
if remembering mode is active. Returns the url. */
if (my.share_room_urls.hasOwnProperty(url)) {
delete my.share_room_urls[url];
return url; }}
function register_original_share_room_url(url) {
/* Include url among the registered original rooms.
Also registers among the set of all familiar share room urls.
Returns the url. */
my.original_share_room_urls[url] = true;
register_share_room_url(url);
return url; }
function is_combo_root_url(url) {
return (url === my.combo_root_url); }
function is_content_root_url(url) {
/* True if the 'url' is for one of the root content items.
Doesn't depend on the url having an established node. */
return ((url === my.combo_root_url)
|| (url === my.storage_root_url)
|| (url === my.original_shares_root_url)
|| (url === my.shares_root_url)); }
function is_content_root_page_id(url) {
return ((url === defaults.combo_root_page_id)
|| (url === defaults.other_shares_root_page_id)
|| (url === defaults.original_shares_root_page_id)); }
function is_share_room_url(url) {
/* True if the 'url' is for one of the familiar share rooms.
Doesn't depend on the url having an established node. */
return my.share_room_urls.hasOwnProperty(url); }
function is_original_share_room_url(url) {
/* True if the 'url' is for one of the original share rooms.
Doesn't depend on the url having an established node. */
return (my.original_share_room_urls.hasOwnProperty(url)); }
function is_other_share_room_url(url) {
/* True if the 'url' is for one of the original share rooms.
Doesn't depend on the url having an established node. */
return is_share_room_url(url) && (! is_original_share_room_url(url)); }
function is_storage_url(url) {
/* True if the URL is for a content item in the user's storage area.
Doesn't depend on the url having an established node. */
return (my.storage_root_url
&& (url.slice(0, my.storage_root_url.length)
=== my.storage_root_url)); }
function is_share_url(url) {
/* True if the URL is for a content item in the user's storage area.
Doesn't depend on the url having an established node. */
return (my.shares_root_url
&& (url.slice(0, my.shares_root_url.length)
=== my.shares_root_url)); }
function is_content_url(url) {
/* True if url within registered content roots. */
return (is_storage_url(url)
|| is_share_url(url)
|| is_combo_root_url(url)
|| is_content_root_url(url)
|| is_content_root_page_id(url)); }
function other_share_room_urls() {
/* Return an array of known share room urls that are not among the
ones originated by the current account, *including* ones from
peristence storage. Doesn't depend on the urls being
established as nodes. */
var others = Object.keys(pmgr.get('other_share_urls') || {});
others.map(function (candidate) {
if (! my.share_room_urls.hasOwnProperty(candidate)) {
register_share_room_url(candidate); }})
var all = Object.keys(my.share_room_urls);
return all.filter(is_other_share_room_url); }
/* ===== Data model ===== */
/* SpiderOak content includes storage (backups) and share rooms. The
data model distinguishes different kinds of those things - the
roots, devices, folders, and files - and wraps them in abstract
general types - the ContentNode and variants of it, where useful. */
function ContentNode(url, parent) {
/* Constructor for items representing stored content.
- 'url' is absolute URL for the collection's root (top) node.
- 'parent' is containing node. The root's parent is null.
See JSON data examples towards the bottom of this script.
*/
if ( !(this instanceof ContentNode) ) { // Coding failsafe.
throw new Error("Constructor called as a function");
}
if (url) { // Skip if we're in prototype assignment.
this.url = url;
this.root_url = parent ? parent.root_url : url;
this.query_qualifier = "";
this.parent_url = parent ? parent.url : null;
this.is_container = true; // Typically.
this.subdirs = []; // Urls of contained devices, folders.
this.files = []; // Urls of contained files.
this.$page = null; // This node's jQuery-ified DOM data-role="page"
this.lastfetched = false;
this.emblem = ""; // At least for debugging/.toString()
this.icon_path = ""; }}
ContentNode.prototype.free = function () {
/* Free composite content to make available for garbage collection. */
if (this.$page) {
this.$page.remove();
this.$page = null; }}
function StorageNode(url, parent) {
ContentNode.call(this, url, parent);
// All but the root storage nodes are contained within a device.
// The DeviceStorageNode sets the device url, which will trickle
// down to all its contents.
this.device_url = parent ? parent.device_url : null; }
StorageNode.prototype = new ContentNode();
function ShareNode(url, parent) {
/* Share room abstract prototype for collections, rooms, and contents */
ContentNode.call(this, url, parent);
this.root_url = parent ? parent.root_url : null;
this.room_url = parent ? parent.room_url : null; }
ShareNode.prototype = new ContentNode();
function RootContentNode(url, parent) {
/* Consolidated root of the storage and share content hierarchies. */
ContentNode.call(this, url, parent);
this.root_url = url;
this.emblem = "Root";
this.name = "Dashboard";
delete this.subdirs;
delete this.files; }
RootContentNode.prototype = new ContentNode();
RootContentNode.prototype.free = function () {
/* Free composite content to make available for garbage collection. */
if (this.$page) {
// Do not .remove() the page - it's the original, not a clone.
this.$page = null; }}
RootContentNode.prototype.loggedin_ish = function () {
/* True if we have enough info to be able to use session credentials. */
return (my.username && true); }
function RootStorageNode(url, parent) {
StorageNode.call(this, url, parent);
this.query_qualifier = "?" + defaults.devices_query_expression;
this.emblem = "Root Storage";
this.stats = null;
delete this.files; }
RootStorageNode.prototype = new StorageNode();
function RootShareNode(url, parent) {
ShareNode.call(this, url, this);
this.emblem = "Root Share";
this.root_url = url; }
RootShareNode.prototype = new ShareNode();
function OtherRootShareNode(url, parent) {
RootShareNode.call(this, url, parent);
this.name = "Other Share Rooms";
this.emblem = "Other Share Rooms";
this.job_id = 0;
// Whitelist of methods eligible for invocation via mode_opts.action:
this.action_methods = {'collection_menu': true,
'remove_item': true,
'persist_item': true,
'unpersist_item': true}
}
OriginalRootShareNode.prototype = new RootShareNode();
function OriginalRootShareNode(url, parent) {
RootShareNode.call(this, url, parent);
this.name = "My Share Rooms";
this.emblem = "Originally Published Share Rooms"; }
OtherRootShareNode.prototype = new RootShareNode();
function DeviceStorageNode(url, parent) {
StorageNode.call(this, url, parent);
this.emblem = "Storage Device";
this.device_url = url; }
DeviceStorageNode.prototype = new StorageNode();
function RoomShareNode(url, parent) {
ShareNode.call(this, url, parent);
this.emblem = "Share Room";
this.room_url = url; }
RoomShareNode.prototype = new ShareNode();
function FolderContentNode(url, parent) {
/* Stub, for situating intermediary methods. */ }
function FileContentNode(url, parent) {
/* Stub, for situating intermediary methods. */ }
function FolderStorageNode(url, parent) {
this.emblem = "Storage Folder";
StorageNode.call(this, url, parent); }
FolderStorageNode.prototype = new StorageNode();
function FolderShareNode(url, parent) {
this.emblem = "Share Room Folder";
ShareNode.call(this, url, parent); }
FolderShareNode.prototype = new ShareNode();
function FileStorageNode(url, parent) {
this.emblem = "Storage File";
StorageNode.call(this, url, parent);
this.is_container = false;
delete this.subdirs;
delete this.files; }
FileStorageNode.prototype = new StorageNode();
function FileShareNode(url, parent) {
this.emblem = "Share Room File";
ShareNode.call(this, url, parent);
this.is_container = false;
delete this.subdirs;
delete this.files; }
FileShareNode.prototype = new ShareNode();
/* ===== Content type and role predicates ===== */
ContentNode.prototype.is_root = function () {
/* True if the node is a collections top-level item. */
return (this.url === this.root_url); }
ContentNode.prototype.is_device = function() {
return false; }
DeviceStorageNode.prototype.is_device = function() {
return true; }
/* ===== Remote data access ===== */
ContentNode.prototype.visit = function (chngpg_opts, mode_opts) {
/* Fetch current data from server, provision, layout, and present.
'chngpg_opts': framework changePage() options,
'mode_opts': node provisioning and layout modal settings. */
if (! this.up_to_date()) {
this.fetch_and_dispatch(chngpg_opts, mode_opts); }
else {
this.show(chngpg_opts, mode_opts); }}
RootContentNode.prototype.visit = function (chngpg_opts, mode_opts) {
/* Do the special visit of the consolidated storage/share root. */
// Trigger visits to the respective root content nodes in 'passive'
// mode so they do not focus the browser on themselves. 'notify' mode
// is also provoked, so they report their success or failure to our
// notify_subvisit_status() method.
//
// See docs/AppOverview.txt "Content Node navigation modes" for
// details about mode controls.
this.remove_status_message();
this.show(chngpg_opts, {});
if (! this.loggedin_ish()) {
// Not enough registered info to try authenticating:
this.authenticated(false);
this.layout(mode_opts);
this.show(chngpg_opts, {}); }
else {
var storage_root = content_node_manager.get(my.storage_root_url);
var our_mode_opts = {passive: true,
notify_callback:
this.notify_subvisit_status.bind(this),
notify_token: 'storage'};
$.extend(our_mode_opts, mode_opts);
try {
// Will chain via notify_callback:
storage_root.visit(chngpg_opts, our_mode_opts); }
catch (err) {
// XXX These failsafes should be in error handlers:
this.authenticated(false,
{status: 0, statusText: "System error"},
err);
this.layout(); }
// XXX Populate the familiar other share rooms.
// XXX Provide other share edit and "+" add controls - somewhere.
}}
OtherRootShareNode.prototype.visit = function (chngpg_opts, mode_opts) {
/* Obtain the known, non-original share rooms and present them. */
// Our content is the set of remembered urls, from:
// - those visited in this session
// - those remembered across sessions
this.remove_status_message();
if (mode_opts.hasOwnProperty('action')) {
var action = mode_opts.action;
if (this.action_methods.hasOwnProperty(action)) {
return this[action](mode_opts); }}
this.subdirs = other_share_room_urls();
// .add_item() will also remove invalid ones from this.subdirs:
this.subdirs.map(this.add_item.bind(this));
this.do_presentation(chngpg_opts, mode_opts); }
ContentNode.prototype.fetch_and_dispatch = function (chngpg_opts,
mode_opts) {
/* Retrieve this node's data and deploy it.
'chngpg_opts' - Options for the framework's changePage function
'mode_opts': node provisioning and layout modal settings.
- On success, call this.handle_visit_success() with the retrieved
JSON data, new Date() just prior to the retrieval, chngpg_opts,
mode_opts, a text status categorization, and the XMLHttpRequest
object.
- Otherwise, this.handle_visit_failure() is called with the
XMLHttpResponse object, chngpg_opts, mode_opts, the text status
categorization, and an exception object, present if an exception
was caught.
See the jQuery.ajax() documentation for XMLHttpResponse details.
*/
var when = new Date();
var url = this.url + this.query_qualifier;
$.ajax({url: url,
type: 'GET',
dataType: 'json',
cache: false,
success: function (data, status, xhr) {
this.handle_visit_success(data, when,
chngpg_opts, mode_opts,
status, xhr); }.bind(this),
error: function (xhr, statusText, thrown) {
this.handle_visit_failure(xhr, chngpg_opts, mode_opts,
statusText,
thrown)}.bind(this), })}
RootContentNode.prototype.notify_subvisit_status = function(succeeded,
token,
response) {
/* Callback passed to subordinate root content nodes to signal their
update disposition:
'succeeded': true for success, false for failure.
'token': token they were passed to identify the transaction,
'response': on failure: the resulting XHR object. */
if (token !== 'other-shares') {
this.authenticated(true); }
var $page = this.my_page$();
var selector = ((token === 'storage')
? "#my-storage-leader"
: "#my-rooms-leader")
var $leader = $(selector);
if (! succeeded) {
$.mobile.hidePageLoadingMsg();
if (token === "storage") {
this.authenticated(false, response);
this.layout(); }}
else {
this.layout();
if (token === 'storage') {
// Ensure we're current page and chain to original shares root.
this.layout();
this.show();
var our_mode_opts = {passive: true,
notify_callback:
this.notify_subvisit_status.bind(this),
notify_token: 'original-share'};
if (this.veiled) {
this.veil(false, $.mobile.hidePageLoadingMsg); }
this.authenticated(true, response);
var ps_root = cnmgr.get(my.original_shares_root_url, this);
ps_root.visit({}, our_mode_opts); }}}
OtherRootShareNode.prototype.notify_subvisit_status = function(succeeded,
token,
content) {
/* Callback for subordinate share nodes to signal their visit result:
'succeeded': true for success, false for failure.
'token': token we passed in to identify transaction and convey info:
[job_id, subnode_URL],
'content': on success: the jquery $(dom) for the populated content,
for failure: the resulting XHR object. */
// We ignore the content.
var $page = this.my_page$();
var sub_job_id = token[0];
var url = token[1];
var splat = url.split('/');
var share_id = base32.decode(splat[splat.length-3]);
var room_key = splat[splat.length-2];
if (succeeded !== true) {
this.remove_status_message('result');
var message = ("Sorry - <tt>"
+ share_id + "</tt> / <tt>" + room_key + "</tt> "
+ content.statusText + " (" + content.status + ")");
var remove = true;
if (content.status === 404) {
this.show_status_message(message); }
else {
message = [].concat(message, " - omit it?");
remove = confirm(message); }
if (remove) {
this.remove_item(url);
this.unpersist_item(url); }}
else {
this.remove_status_message('error'); }
if (sub_job_id === this.job_id) {
// Do update, whether or not it was successful:
this.subdirs = other_share_room_urls()
this.subdirs.sort(content_nodes_by_url_sorter)
this.do_presentation({}, {passive: true}); }}
ContentNode.prototype.handle_visit_success = function (data, when,
chngpg_opts,
mode_opts,
status, xhr) {
/* Deploy successfully obtained node data.
See ContentNode.fetch_and_dispatch() for parameter details. */
this.provision(data, when, mode_opts);
this.layout(mode_opts);
this.show(chngpg_opts, mode_opts);
if (mode_opts.notify_callback) {
mode_opts.notify_callback(true,
mode_opts.notify_token); }}
ContentNode.prototype.handle_visit_failure = function (xhr,
chngpg_opts,
mode_opts,
exception) {
/* Do failed visit error handling with 'xhr' XMLHttpResponse report. */
if (mode_opts.notify_callback) {
mode_opts.notify_callback(false, mode_opts.notify_token, xhr); }
else {
$.mobile.hidePageLoadingMsg();
alert("Visit '" + this.name + "' failed: "
+ xhr.statusText + " (" + xhr.status + ")");
var combo_root = content_node_manager.get_combo_root();
if (! is_combo_root_url(this.url)) {
// Recover upwards, eventually to the top:
$.mobile.changePage(this.parent_url
? this.parent_url
: combo_root.url); }}}
RootContentNode.prototype.handle_visit_failure = function (xhr,
chngpg_opts,
mode_opts,
exception) {
/* Do failed visit error handling with 'xhr' XMLHttpResponse report. */
this.layout();
this.authenticated(false, xhr, exception); }
RootContentNode.prototype.authenticated = function (succeeded, response,
exception) {
/* Present login challenge versus content, depending on access success.
'succeeded': true for success, false for failure.
'response': on failure: the resulting XHR object, if any.
'exception': on failure, exception caught by ajax machinery, if any.
*/
var $page = this.my_page$();
var $content_section = $page.find('.my-content');
var $login_section = $page.find('.login-section');
if (succeeded) {
// Show the content instead of the form
$login_section.hide();
this.remove_status_message();
$content_section.show();
if (remember_manager.active()) {
// remember_manager will store just the relevant fields.
remember_manager.store(my);
this.layout_header(); }}
else {
// Include the xhr.statusText in the form.
this.veil(false);
$content_section.hide();
$login_section.show();
var username;
if (remember_manager.active()
&& (username = persistence_manager.get('username'))) {
$('#my_login_username').val(username); }
if (response) {
var error_message = response.statusText;
if (exception) {
error_message += " - " + exception.message; }
this.show_status_message(error_message);
if (response.status === 401) {
// Unauthorized - expunge all privileged info:
clear_storage_account(); }}
// Hide the storage and original shares sections
$content_section.hide();
if (this.veiled) { this.veil(false); }}}
OtherRootShareNode.prototype.collection_menu = function (target_url) {
/* Present a menu of collection membership actions for 'target_url'. */
// >>>
}
OtherRootShareNode.prototype.add_item_external = function (credentials) {
/* Visit a specified share room, according to 'credentials' object:
{username, password}.
Use this routine only for adding from outside the object - use
this.add_item(), instead, for internal operation.
*/
this.job_id += 1; // Entry
var share_id = credentials.shareid;
var room_key = credentials.password;
var message = (share_id + "</tt> / <tt>" + room_key + "</tt> ");
var new_share_url = (my.shares_root_url
+ base32.encode_trim(share_id)
+ "/" + room_key
+ "/");
if (is_other_share_room_url(new_share_url)) {
this.show_status_message(message + " already added"); }
else if (is_share_room_url(new_share_url)) {
this.show_status_message(message + ' already among "my" shares'); }
else {
var $sm = this.show_status_message("Added: " + message, 'result');
$sm.hide();
$sm.delay(1000).fadeIn(1000); // Give time for error to appear.
return this.add_item(new_share_url); }}
OtherRootShareNode.prototype.add_item = function (url) {
/* Visit a specified share room, according its' URL address.
Return the room object. */
register_share_room_url(url);
var room = content_node_manager.get(url, cnmgr.get_combo_root());
room.visit({},
{passive: true,
notify_callback: this.notify_subvisit_status.bind(this),
notify_token: [this.job_id, url]});
return room; }
OtherRootShareNode.prototype.remove_item_external = function (room_url) {
/* Omit a non-original share room from persistent and resident memory.
This is for use from outside of the object. Use .remove_item() for
internal object operation. */
this.job_id += 1;
this.remove_item(url); }
OtherRootShareNode.prototype.remove_item = function (room_url) {
/* Omit a non-original share room from the persistent and resident
collections. Returns true if the item was present, else false. */
if (is_other_share_room_url(room_url)) {
unregister_share_room_url(room_url);
this.unpersist_item(room_url);
return true; }
else { return false; }}
OtherRootShareNode.prototype.persist_item = function (room_url) {
/* Add a share rooms to the collection persistent non-originals. */
var persistents = pmgr.get("other_share_urls") || {};
if (! persistents.hasOwnProperty(room_url)) {
persistents[room_url] = true;
pmgr.set("other_share_urls", persistents); }}
OtherRootShareNode.prototype.unpersist_item = function (room_url) {
/* Omit a non-original share room from the persistent
collection. Returns true if the item was present, else false. */
var persistents = pmgr.get("other_share_urls") || {};
if (persistents.hasOwnProperty(room_url)) {
delete persistents[room_url];
pmgr.set("other_share_urls", persistents);
return true; }
else { return false; }}
/* ===== Containment ===== */
/* For content_node_manager.clear_hierarchy() */
ContentNode.prototype.contained_urls = function () {
return [].concat(this.subdirs, this.files); }
RootContentNode.prototype.contained_urls = function () {
return [].concat(this.storage_devices,
this.original_shares, this.shares); }
RootStorageNode.prototype.contained_urls = function () {
return [].concat(this.subdirs); }
FileStorageNode.prototype.contained_urls = function () {
return []; }
FileShareNode.prototype.contained_urls = function () {
return []; }
/* "Provisioning": Data model assimilation of fetched data */
ContentNode.prototype.provision = function (data, when, mode_opts) {
/* Populate node with JSON 'data'. 'when' is the data's current-ness.
'when' should be no more recent than the XMLHttpRequest.
*/
this.provision_preliminaries(data, when, mode_opts);
this.provision_populate(data, when, mode_opts); }
ContentNode.prototype.provision_preliminaries = function (data, when,
mode_opts) {
/* Do provisioning stuff generally useful for derived types. */
if (! when) {
throw new Error("Node provisioning without reliable time stamp.");
}
this.up_to_date(when); }
ContentNode.prototype.provision_populate = function (data, when,
mode_opts) {
/* Stub, must be overridden by type-specific provisionings. */
error_alert("Not yet implemented",
this.emblem
+ " type-specific provisioning implementation"); }
ContentNode.prototype.provision_items = function (data_items,
this_container,
url_base, url_element,
trailing_slash,
fields,
contents_parent) {
/* Register data item fields into subnodes of this node:
'data_items' - the object to iterate over for the data,
'this_container' - the container into which to place the subnodes,
'url_base' - the base url onto which the url_element is appended,
'url_element' - the field name for the url of item within this node,
'trailing_slash' - true: url is given a trailing slash if absent,
'fields' - an array of field names for properties to be copied (1),
'contents_parent' - the node to attribute as the subnodes parent (2).
(1) Fields are either strings, denoting the same attribute name in
the data item and subnode, or two element subarrays, with the
first element being the data attribute name and the second being
the attribute name for the subnode.
(2) The contained item's parent is not always this object, eg for
the content roots. */
var parent = content_node_manager.get(contents_parent);
data_items.map(function (item) {
var url = url_base + item[url_element];
if (trailing_slash && (url.slice(url.length-1) !== '/')) {
url += "/"; }
var subnode = content_node_manager.get(url, parent);
fields.map(function (field) {
if (field instanceof Array) {
subnode[field[1]] = item[field[0]]; }
else {
subnode[field] = item[field]; }})
// TODO Scaling - make subdirs an object for hashed lookup.
if (this_container.indexOf(url) === -1) {
this_container.push(url); }})}
RootStorageNode.prototype.provision_populate = function (data, when,
mode_opts) {
/* Embody the root storage node with 'data'.
'when' is time soon before data was fetched. */
var combo_root = content_node_manager.get_combo_root();
var url, dev, devdata;
// XXX ?:
this.name = my.username;
// TODO: We'll cook stats when UI is ready.
this.stats = data["stats"];
this.subdirs = [];
this.provision_items(data.devices, this.subdirs,
this.url, 'encoded', true,
['name', 'lastlogin', 'lastcommit'],
my.combo_root_url);
this.lastfetched = when; }
FolderContentNode.prototype.provision_populate = function (data, when) {
/* Embody folder content items with 'data'.
'when' is time soon before data was fetched. */
this.subdirs = [];
this.provision_items(data.dirs, this.subdirs, this.url, 1, true,
[[0, 'name']], this.url);
if (data.hasOwnProperty('files')) {
this.files = [];
var fields = ['name', 'size', 'ctime', 'mtime', 'versions'];
defaults.preview_sizes.map(function (size) {
/* Add previews, if any, to the fields. */
if (("preview_" + size) in data.files) {
fields.push("preview_" + size); }})
this.provision_items(data.files, this.files, this.url, 'url', false,
fields, this.url); }
this.lastfetched = when; }
OriginalRootShareNode.prototype.provision_populate = function (data, when) {
/* Embody the root share room with 'data'.
'when' is time soon before data was fetched. */
this.subdirs = [];
var room_base = my.shares_root_url + data.share_id_b32 + "/";
this.provision_items(data.share_rooms, this.subdirs,
room_base, 'room_key', true,
[['room_name', 'name'],
['room_description', 'description'],
'room_key', 'share_id'],
my.combo_root_url);
this.subdirs.map(function (url) {
/* Ensure the contained rooms urls are registered as originals. */
register_original_share_room_url(url); });
this.lastfetched = when; }
DeviceStorageNode.prototype.provision_populate = function (data, when) {
/* Embody storage folder items with 'data'.
'when' is time soon before data was fetched. */
FolderStorageNode.prototype.provision_populate.call(this, data, when); }
RoomShareNode.prototype.provision_populate = function (data, when) {
/* Embody storage folder items with 'data'.
'when' is time soon before data was fetched. */
FolderShareNode.prototype.provision_populate.call(this, data,
when);
this.name = data.stats.room_name;
this.description = data.stats.description;
this.number_of_files = data.stats.number_of_files;
this.number_of_folders = data.stats.number_of_folders;
this.firstname = data.stats.firstname;
this.lastname = data.stats.lastname;
this.lastfetched = when; }
FolderStorageNode.prototype.provision_populate = function (data, when) {
/* Embody storage folder items with 'data'.
'when' is time soon before data was fetched. */
FolderContentNode.prototype.provision_populate.call(this, data, when); }
FolderShareNode.prototype.provision_populate = function (data, when){
/* Embody share room folder items with 'data'.
'when' is time soon before data was fetched. */
FolderContentNode.prototype.provision_populate.call(this, data, when); }
FileStorageNode.prototype.provision_populate = function (data, when) {
error_alert("Not yet implemented", "File preview"); }
ContentNode.prototype.up_to_date = function (when) {
/* True if provisioned data is considered current.
Optional 'when' specifies (new) time we were fetched. */
// The generic case offers no shortcut for determining up-to-date-ness.
if (when) { this.lastfetched = when; }
if (! this.lastfetched) { return false; }
// No intelligence yet.
return false; }
/* ===== Content node page presentation ===== */
ContentNode.prototype.my_page_id = function () {
/* Set the UI page id, escaping special characters as necessary. */
return this.url; }
RootContentNode.prototype.my_page_id = function () {
/* Set the UI page id, escaping special characters as necessary. */
return defaults.combo_root_page_id; }
OtherRootShareNode.prototype.my_page_id = function () {
/* Set the UI page id, escaping special characters as necessary. */
return defaults.other_shares_root_page_id; }
OriginalRootShareNode.prototype.my_page_id = function () {
/* Set the UI page id, escaping special characters as necessary. */
return defaults.original_shares_root_page_id; }
ContentNode.prototype.show = function (chngpg_opts, mode_opts) {
/* Trigger UI focus on our content layout.
If mode_opts "passive" === true, don't do a changePage.
*/
var $page = this.my_page$();
if ($.mobile.activePage
&& ($.mobile.activePage[0].id !== this.my_page_id())
&& (!mode_opts.passive)) {
$.mobile.changePage($page, chngpg_opts); }
// Just in case, eg of refresh:
$.mobile.hidePageLoadingMsg(); }
OtherRootShareNode.prototype.do_presentation = function (chngpg_opts,
mode_opts) {
/* An exceptional, consolidated presentation routine. */
// For use by this.visit() and this.notify_subvisit_status().
this.subdirs.sort(content_nodes_by_url_sorter);
this.layout(mode_opts);
this.show(chngpg_opts, mode_opts);
if (mode_opts.notify_callback) {
mode_opts.notify_callback(true,
mode_opts.notify_token); }}
ContentNode.prototype.layout = function (mode_opts) {
/* Deploy content as markup on our page. */
this.layout_header(mode_opts);
this.layout_content(mode_opts);
this.layout_footer(mode_opts); }
OtherRootShareNode.prototype.layout = function (mode_opts) {
/* Deploy content as markup on our page. */
// Get a split button on each item to provoke an action menu:
var split_params = {url: this.url + '?action=collection_menu&target=',
icon: 'gear',
title: "Collection membership"};
mode_opts.split_button_url_append = split_params;
ContentNode.prototype.layout.call(this, mode_opts);
var $content_items = this.my_page$().find('.page-content')
if (this.subdirs.length === 0) {
$content_items.hide(); }
else {
$content_items.show(); }}
OtherRootShareNode.prototype.show = function (chngpg_opts, mode_opts) {
/* Deploy content as markup on our page. */
ContentNode.prototype.show.call(this, chngpg_opts, mode_opts);
deploy_focus_oneshot('#my_share_id', "pageshow"); }
RootContentNode.prototype.layout = function (chngpg_opts, mode_opts) {
/* Do layout arrangements - different than other node types. */
var $page = this.my_page$();
this.layout_header();
// Storage content section:
// We avoid doing layout of these when not authenticated so the
// re-presentation of the hidden sections doesn't show through.
var storage_subdirs = (my.storage_root_url
&& cnmgr.get(my.storage_root_url,
this).subdirs
|| [])
this.layout_content(mode_opts, storage_subdirs, false,
'.storage-list');
// My share rooms section:
var myshares_subdirs = (my.original_shares_root_url
&& cnmgr.get(my.original_shares_root_url,
this).subdirs
|| [])
this.layout_content(mode_opts, myshares_subdirs, false,
'.my-shares-list');
// Other share rooms section:
var other_share_urls = other_share_room_urls();
var $other_shares_nonempty = $page.find('.other-content');
var $other_shares_empty = $page.find('.other-no-content');
// Show the section or the button depending on whether there's content:
if (other_share_urls.length === 0) {
$other_shares_nonempty.hide();
$other_shares_empty.show(); }
else {
$other_shares_empty.hide();
$other_shares_nonempty.show();
this.layout_content(mode_opts, other_share_urls, false,
'.other-shares-list'); }
this.layout_footer(mode_opts); }
ContentNode.prototype.layout_header_fields = function(fields) {
/* Populate this content node's page header with these fields settings:
field.title: html (or just text) with the page label;
left_url: left-hand button URL; if absent left button not changed;
left_label: text for left-hand button, or empty to hide the button;
left_label = "-" => use the login URL;
right_url: right-hand button URL; if absent right button not changed;
right_label: text for right-hand button, or empty to hide the button;
*/
var $header = this.my_page$().find('[data-role="header"]');
var $label;
if (fields.hasOwnProperty('title')) {
$header.find('.header-title').html(elide(fields.title, 25)); }
if (fields.hasOwnProperty('right_url')) {
var $right_slot = $header.find('.header-right-slot');
$right_slot.attr('href', fields.right_url);
if (fields.hasOwnProperty('right_label')) {
if (! fields.right_label) {
$right_slot.hide(); }
else {
replace_button_text($right_slot, elide(fields.right_label,
15));
$right_slot.show(); }}}
if (fields.hasOwnProperty('left_url')) {
var $left_slot = $header.find('.header-left-slot');
if (fields.left_url === "-") {
var parsed = $.mobile.path.parseUrl(window.location.href);
fields.left_url = parsed.hrefNoHash; }
$left_slot.attr('href', fields.left_url);
if (fields.hasOwnProperty('left_label')) {
if (! fields.left_label) {
$left_slot.hide(); }
else {
replace_button_text($left_slot, elide(fields.left_label,
15));
$left_slot.show(); }}}}
RootContentNode.prototype.layout_header = function (mode_opts) {
/* Do special RootContentNode header layout. */
var $header = this.my_page$().find('[data-role="header"]');
var $logout_button = $header.find('.logout-button');
if (! this.loggedin_ish()) {
$logout_button.hide(); }
else {
$logout_button.show(); }}
StorageNode.prototype.layout_header = function(mode_opts) {
/* Fill in typical values for header fields of .my_page$().
Many storage node types will use these values as is, some will
replace them.
*/
var fields = {};
fields.right_url = ('#' + add_query_param(this.url,
"refresh", "true", true));
fields.right_label = "Refresh";
fields.title = this.name;
if (this.parent_url) {
var container = content_node_manager.get(this.parent_url);
fields.left_url = '#' + this.parent_url;
fields.left_label = container.name; }
this.layout_header_fields(fields); }
RootStorageNode.prototype.layout_header = function(mode_opts) {
/* Fill in typical values for header fields of .my_page$(). */
StorageNode.prototype.layout_header.call(this, mode_opts);
this.layout_header_fields({'title': "Storage Devices",
'left_label': "Home",
'left_url': "#" + this.parent_url}); }
ShareNode.prototype.layout_header = function(mode_opts) {
/* Fill in header fields of .my_page$(). */
var fields = {};
if (this.parent_url) {
var container = content_node_manager.get(this.parent_url);
fields.right_url = '#' + add_query_param(this.url,"refresh","true");
fields.right_label = "Refresh"
fields.left_url = '#' + this.parent_url;
fields.left_label = container.name;
fields.title = this.name; }
else {
fields.right_url = '#' + add_query_param(this.url, "mode", "edit");
fields.right_label = "Edit";
fields.left_url = '#' + add_query_param(this.url, 'mode', "add");
fields.left_label = "+";
fields.title = "ShareRooms"; }
this.layout_header_fields(fields); }
RootShareNode.prototype.layout_header = function(mode_opts) {
/* Fill in header fields of .my_page$(). */
ShareNode.prototype.layout_header.call(this, mode_opts);
var fields = {'right_url': '#' + add_query_param(this.url,
"mode", "edit"),
'right_label': "Edit"};
this.layout_header_fields(fields); }
ContentNode.prototype.layout_content = function (mode_opts,
subdirs,
files,
content_items_selector) {
/* Present this content node by adjusting its DOM data-role="page".
'mode_opts' adjust various aspects of provisioning and layout.
'subdirs' is an optional array of urls for contained directories,
otherwise this.subdirs is used;
'files' is an optional array of urls for contained files, otherwise
this.files is used;
'content_items_selector' optionally specifies the selector for
the listview to hold the items, via this.my_content_items$().
*/
var $page = this.my_page$();
var $content = $page.find('[data-role="content"]');
var $list = this.my_content_items$(content_items_selector);
if ($list.children().length) {
$list.empty(); }
subdirs = subdirs || this.subdirs;
var lensubdirs = subdirs ? subdirs.length : 0;
files = files || this.files;
var lenfiles = files ? files.length : 0;
var do_dividers = (lensubdirs + lenfiles) > defaults.dividers_threshold;
var do_filter = (lensubdirs + lenfiles) > defaults.filter_threshold;
function insert_item($item) {
if ($cursor === $list) { $cursor.append($item); }
else { $cursor.after($item); }
$cursor = $item; }
function conditionally_insert_divider(t) {
if (do_dividers && t && (t[0].toUpperCase() !== curinitial)) {
curinitial = t[0].toUpperCase();
indicator = divider_prefix + curinitial;
$item = $('<li data-role="list-divider" id="divider-'
+ indicator + '">' + indicator + '</li>')
insert_item($item); }}
function insert_subnode(suburl) {
var subnode = content_node_manager.get(suburl, this);
conditionally_insert_divider(subnode.name);
insert_item(subnode.layout_item$(mode_opts)); }
if (lensubdirs + lenfiles === 0) {
$list.append($('<li title="Empty" class="empty-placeholder"/>')
.html('<span class="empty-sign ui-btn-text">'
+ '∅</span>')); }
else {
var $item;
var curinitial, divider_prefix, indicator = "";
var $cursor = $list;
if (do_filter) { $list.attr('data-filter', 'true'); }
if (lensubdirs) {
divider_prefix = "/";
for (var i=0; i < subdirs.length; i++) {
insert_subnode(subdirs[i]); }}
if (lenfiles) {
divider_prefix = "";
for (var i=0; i < files.length; i++) {
insert_subnode(files[i]); }}}
$page.page();
$list.listview("refresh");
return $page; }
FolderContentNode.prototype.layout_item$ = function(mode_opts) {
/* Return a folder-like content item's description as jQuery item.
Optional:
mode_opts['split_button_url_append']: {icon:, title:, url:}
- construct a split button, appending node's url onto passed url.
*/
var $a = $('<a/>').attr('class', "compact-vertical");
$a.attr('href', "#" + this.url);
$a.html($('<h4/>').html(this.name));
var $it = $('<li/>').append($a);
if (mode_opts && mode_opts.hasOwnProperty('split_button_url_append')) {
var split_params = mode_opts.split_button_url_append;
$a = $('<a/>');
$a.attr('href', '#' + split_params.url + this.url);
$a.attr('data-icon', split_params.icon);
$a.attr('title', split_params.title);
$it.find('a').after($a); }
$it.attr('data-filtertext', this.name);
return $it; }
DeviceStorageNode.prototype.layout_item$ = function(mode_opts) {
/* Return a storage device's description as a jQuery item. */
return FolderStorageNode.prototype.layout_item$.call(this); }
FolderStorageNode.prototype.layout_item$ = function(mode_opts) {
/* Return a storage folder's description as a jQuery item. */
return FolderContentNode.prototype.layout_item$.call(this, mode_opts); }
FolderShareNode.prototype.layout_item$ = function(mode_opts) {
/* Return a share room folder's description as a jQuery item. */
return FolderContentNode.prototype.layout_item$.call(this, mode_opts); }
RoomShareNode.prototype.layout_item$ = function(mode_opts) {
/* Return a share room's description as a jQuery item. */
return FolderShareNode.prototype.layout_item$.call(this,
mode_opts); }
FileContentNode.prototype.layout_item$ = function(mode_opts) {
/* Return a file-like content node's description as a jQuery item. */
var $it = $('<li data-mini="true"/>');
$it.attr('data-filtertext', this.name);
var type = classify_file_by_name(this.name);
var pretty_type = type ? (type + ", ") : "";
var $details = $('<p>' + pretty_type + bytesToSize(this.size) +'</p>');
var date = new Date(this.mtime*1000);
var day_splat = date.toLocaleDateString().split(",");
var $date = $('<p class="ul-li-aside">'
+ day_splat[1] + "," + day_splat[2]
+ " " + date.toLocaleTimeString()
+'</p>');
var $table = $('<table width="100%"/>');
var $td = $('<td colspan="2"/>').append($('<h4/>').html(this.name));
$table.append($('<tr/>').append($td));
var $tr = $('<tr/>');
$tr.append($('<td/>').append($details).attr('wrap', "none"));
$tr.append($('<td/>').append($date).attr('align', "right"));
$table.append($tr);
var $href = $('<a/>');
$href.attr('href', this.url);
$href.attr('class', "compact-vertical");
$href.append($table);
$it.append($href);
// XXX use classification to select an icon:
$it.attr('data-icon', "false");
return $it; }
FileStorageNode.prototype.layout_item$ = function(mode_opts) {
/* Return a storage file's description as a jQuery item. */
return FileContentNode.prototype.layout_item$.call(this, mode_opts); }
FileShareNode.prototype.layout_item$ = function(mode_opts) {
/* Return a storage file's description as a jQuery item. */
return FileContentNode.prototype.layout_item$.call(this, mode_opts); }
ContentNode.prototype.layout_footer = function(mode_opts) {
/* Return markup with general and specific legend fields and urls. */
// XXX Not yet implemented.
}
ContentNode.prototype.my_page_from_dom$ = function () {
/* Return a jquery DOM search for my page, by id. */
return $('#' + fragment_quote(this.my_page_id())); }
ContentNode.prototype.my_page$ = function (reinit) {
/* Return this node's jQuery page object, producing if not present.
Optional 'reinit' means to discard existing page, if any,
forcing clone of a new copy.
If not present, we get a clone of the storage page template, and
situate the clone after the storage page template.
*/
if (reinit && this.$page) {
this.$page.remove();
delete this.$page; }
if (! this.$page) {
var $template = this.get_storage_page_template$();
if (! $template) {
error_alert("Missing markup",
"Expected page #"
+ defaults.content_page_template_id
+ " not present."); }
this.$page = $template.clone();
this.$page.attr('id', this.my_page_id());
this.$page.attr('data-url', this.my_page_id());
// Include our page in the DOM, after the storage page template:
$template.after(this.my_page$()); }
return this.$page; }
OtherRootShareNode.prototype.my_page$ = function () {
return RootContentNode.prototype.my_page$.call(this); }
RootContentNode.prototype.my_page$ = function () {
/* Return the special case of the root content nodes actual page. */
return (this.$page
? this.$page
: (this.$page = $("#" + this.my_page_id()))); }
ContentNode.prototype.my_content_items$ = function (selector) {
/* Return this node's jQuery contents litview object.
Optional 'selector' is used, otherwise '.content-items'. */
return this.my_page$().find(selector || '.content-items'); }
ContentNode.prototype.get_storage_page_template$ = function() {
return $("#" + defaults.content_page_template_id); }
/* ===== Resource managers ===== */
var persistence_manager = {
/* Maintain domain-specific persistent settings, using localStorage.
- Value structure is maintained using JSON.
- Use .get(name), .set(name, value), and .remove(name).
- .keys() returns an array of all stored keys.
- .length returns the number of keys.
*/
// NOTE Compat: versions of android < 2.1 do not support localStorage.
// They do support gears sqlite. lawnchair would make it
// easy to switch between them.
get: function (name) {
/* Retrieve the value for 'name' from persistent storage. */
return JSON.parse(localStorage.getItem(name)); },
set: function (name, value) {
/* Preserve name and value in persistent storage.
Return the settings manager, for chaining. */
localStorage.setItem(name, JSON.stringify(value));
return persistence_manager; },
remove: function (name) {
/* Delete persistent storage of name. */
localStorage.removeItem(name); },
keys: function () { return Object.keys(localStorage); },
};
// Gratuitous 'persistence_manager.length' getter, for a technical example:
persistence_manager.__defineGetter__('length',
function() {
return localStorage.length; });
var pmgr = persistence_manager; // Compact name.
var remember_manager = {
/* Maintain user account info in persistent storage. */
// "remember_me" field not in fields, so only it is retained when
// remembering is disabled:
fields: ['username', 'storage_host', 'storage_web_url'],
unset: function (disposition) {
/* True if no persistent remember manager settings are found. */
return persistence_manager.get("remember_me") === null; },
active: function (disposition) {
/* Report or set "Remember Me" persistent account info retention.
'disposition':
- activate if truthy,
- return status if not passed in, ie undefined,
- deactivate otherwise.
Deactivating entails wiping the retained account info settings.
*/
if (disposition) {
return persistence_manager.set("remember_me", true); }
else if (typeof disposition === "undefined") {
return persistence_manager.get("remember_me") || false; }
else {
remember_manager.fields.map(function (key) {
persistence_manager.remove(key); });
return persistence_manager.set("remember_me", false); }},
fetch: function () {
/* Return remembered account info . */
var got = {};
remember_manager.fields.map(function (key) {
got[key] = persistence_manager.get(key); });
return got; },
store: function (obj) {
/* Preserve account info, obtaining specific fields from 'obj'.
Error is thrown if obj lacks any fields. */
remember_manager.fields.map(function (key) {
if (! obj.hasOwnProperty(key)) {
throw new Error("Missing field: " + key); }
persistence_manager.set(key, obj[key]); })},
remove_storage_host: function () {
/* How to inhibit auto-login, without losing the convenience of
a remembered username, in the absence of a way to remove the
authentication cookies. */
persistence_manager.remove('storage_host'); },
};
var remgr = remember_manager;
var content_node_manager = function () {
/* A singleton utility for getting and removing content node objects.
"Getting" means finding existing ones or else allocating new ones.
*/
// Type of newly minted nodes are according to get parameters.
// ???: Cleanup? Remove nodes when ascending above them?
// ???:
// - prefetch offspring layer and defer release til 2 layers above.
// - make fetch of multiple items contingent to device lastcommit time.
/* Private */
var by_url = {};
/* Public */
return {
get_combo_root: function () {
return this.get(my.combo_root_url, null); },
get: function (url, parent) {
/* Retrieve a node according to 'url'.
'parent' is required for production of new nodes,
which are produced on first reference.
Provisioning nodes with remote data is done elsewhere,
not here.
*/
url = url.split('?')[0]; // Strip query string.
var got = by_url[url];
if (! got) {
// Roots:
if (is_content_root_url(url)) {
if (is_combo_root_url(url)) {
got = new RootContentNode(url, parent); }
else if (url === my.storage_root_url) {
got = new RootStorageNode(url, parent); }
else if (url === my.original_shares_root_url) {
got = new OriginalRootShareNode(url, parent); }
else if (url === my.shares_root_url) {
got = new OtherRootShareNode(url, parent); }
else {
throw new Error("Content model management error");}}
// Contents:
else if (parent && (is_combo_root_url(parent.url))) {
// Content node just below a root:
if (is_storage_url(url)) {
got = new DeviceStorageNode(url, parent); }
else {
got = new RoomShareNode(url, parent); }}
else if (url.charAt(url.length-1) !== "/") {
// No trailing slash.
if (is_storage_url(url)) {
got = new FileStorageNode(url, parent); }
else {
got = new FileShareNode(url, parent); }}
else {
if (is_storage_url(url)) {
got = new FolderStorageNode(url, parent); }
else {
got = new FolderShareNode(url, parent); }
}
by_url[url] = got;
}
return got; },
free: function (node) {
/* Remove a content node from index and free it for gc. */
if (by_url.hasOwnProperty(node.url)) {
delete by_url[node.url]; }
node.free(); },
clear_hierarchy: function (url) {
/* Free node at 'url' and its recursively contained nodes. */
var it = this.get(url);
var suburls = it.contained_urls();
for (var i=0; i < suburls.length; i++) {
this.clear_hierarchy(suburls[i]); }
this.free(it); },
// Expose the by_url registry when debugging:
bu: (SO_DEBUGGING ? by_url : null),
}
}()
var cnmgr = content_node_manager; // Compact name, for convenience.
/* ===== Login ===== */
function go_to_entrance() {
/* Visit the entrance page. Depending on session state, it might
present a login challenge or it might present the top-level
contents associated with the logged-in account. */
$.mobile.changePage(content_node_manager.get_combo_root().url); }
function storage_login(login_info, url) {
/* Login to storage account and commence browsing at devices.
'login_info': An object with "username" and "password" attrs.
'url': An optional url, else defaults.storage_login_path is used.
We provide for redirection to specific alternative servers
by recursive calls. See:
https://spideroak.com/apis/partners/web_storage_api#Loggingin
*/
var login_url;
var server_host_url;
var parsed;
if (url
&& (parsed = $.mobile.path.parseUrl(url))
&& ["http:", "https:"].indexOf(parsed.protocol) !== -1) {
server_host_url = parsed.domain;
login_url = url; }
else {
server_host_url = defaults.base_host_url;
login_url = (server_host_url + defaults.storage_login_path); }
$.ajax({
url: login_url,
type: 'POST',
dataType: 'text',
data: login_info,
success: function (data) {
var match = data.match(/^(login|location):(.+)$/m);
if (!match) {
error_alert('Temporary server failure',
'Please try again later.');
} else if (match[1] === 'login') {
if (match[2].charAt(0) === "/") {
login_url = server_host_url + match[2];
} else {
login_url = match[2];
}
storage_login(login_info, login_url);
} else {
// Browser haz auth cookies, we haz relative location.
// Go there, and machinery will intervene to handle it.
$.mobile.changePage(
set_storage_account(login_info['username'],
server_host_url,
match[2]));
}},
error: function (xhr) {
$.mobile.hidePageLoadingMsg();
var username;
if (remember_manager.active()
&& (username = persistence_manager.get('username'))) {
$('#my_login_username').val(username); }
error_alert("Storage login", xhr.status); },
}); }
function storage_logout() {
/* Conclude storage login, clearing credentials and stored data.
Wind up back on the main entry page.
*/
function finish() {
clear_storage_account();
if (remember_manager.active()) {
// The storage server doesn't remove cookies, so we inhibit
// relogin by removing the persistent info about the
// storage host. This leaves the username intact as a
// "remember" convenience for the user.
remember_manager.remove_storage_host(); }
go_to_entrance(); }
var combo_root = content_node_manager.get_combo_root();
combo_root.veil(true);
if (! combo_root.loggedin_ish()) {
// Can't reach logout location without server - just clear and bail.
finish(); }
else {
// SpiderOak's logout url doesn't (as of 2012-06-15) remove cookies!
$.ajax({url: my.storage_root_url + defaults.storage_logout_suffix,
type: 'GET',
success: function (data) {
finish(); },
error: function (xhr) {
console.log("Logout ajax fault: "
+ xhr.status
+ " (" + xhr.statusText + ")");
finish(); }}); }}
RootContentNode.prototype.veil = function (conceal, callback) {
/* If 'conceal' is true, conceal our baudy body. Otherwise, gradually
reveal and position the cursor in the username field.
Optional callback is a function to invoke as part of the un/veiling.
*/
function do_focus() {
var $username = $('#my_login_username');
if ($username.val() === "") { $username.focus(); }
else { $('#my_login_password').focus(); }}
function do_focus_and_callback() {
do_focus();
if (callback) { callback(); }}
var selector = '#home [data-role="content"]';
if (conceal) {
$(selector).hide(0, callback);
this.veiled = true; }
else {
this.veiled = false;
// Surprisingly, doing focus before dispatching fadeIn doesn't work.
// Also, username field focus doesn't *always* work before the
// delay is done, hence the redundancy. Sigh.
$(selector).fadeIn(3000, do_focus_and_callback);
do_focus(); }}
function prep_login_form(content_selector, submit_handler, name_field,
do_fade) {
/* Instrument form within 'content_selector' to submit with
'submit_handler'. 'name_field' is the id of the form field with
the login name, "password" is assumed to be the password field
id. If 'do_fade' is true, the content portion of the page will
be rigged to fade on form submit, and on pagechange reappear
gradually. In any case, the password value will be cleared, so
it can't be reused.
*/
var $content = $(content_selector);
var $form = $(content_selector + " form");
var $password = $form.find('input[name=password]');
var $name = $form.find('input[name=' + name_field + ']');
var $submit = $form.find('[type="submit"]');
var sentinel = new submit_button_sentinel([$name, $password], $submit)
$name.bind('keyup', sentinel);
$password.bind('keyup', sentinel);
$submit.button()
sentinel();
var $remember_widget = $form.find('#remember-me');
var remembering = remember_manager.active();
if (remembering && ($remember_widget.val() !== "on")) {
$remember_widget.find('option[value="on"]').attr('selected',
'selected');
$remember_widget.val("on");
// I believe the reason we need to also .change() is because
// the presented slider is just tracking the actual select widget.
$remember_widget.trigger('change'); }
else if (!remember_manager.unset() && !remembering) {
$remember_widget.val("off");
$remember_widget.trigger('change'); }
var name_field_val = pmgr.get(name_field);
if (name_field_val
&& ($remember_widget.length > 0)
&& ($remember_widget.val() === "on")) {
$name.attr('value',name_field_val); }
$form.submit(function () {
var $remember_widget = $form.find('#remember-me');
var $name = $('input[name=' + name_field + ']', this);
var $password = $('input[name=password]', this);
var data = {};
if (($name.val() === "") || ($password.val() === "")) {
// Minimal - the submit button sentinel should prevent this.
return false; }
data[name_field] = $name.val();
$name.val("");
if ($remember_widget.length > 0) {
// Preserve whether or not we're remembering, so on a
// successful visits we'll know whether to preserve data:
if ($remember_widget.val() === "on") {
remember_manager.active(true); }
else {
remember_manager.active(false); }}
data['password'] = $password.val();
if (do_fade) {
var combo_root = content_node_manager.get_combo_root();
combo_root.veil(true, function() { $password.val(""); });
var unhide_form_oneshot = function(event, data) {
$content.show('fast');
$.mobile.hidePageLoadingMsg();
$(document).unbind("pagechange", unhide_form_oneshot);
$(document).unbind("error", unhide_form_oneshot); }
$(document).bind("pagechange", unhide_form_oneshot)
$(document).bind("error", unhide_form_oneshot); }
else {
$name.val("");
$password.val(""); }
$name.focus();
submit_handler(data);
return false; }); }
/* ===== Public interface ===== */
// ("public_interface" because "public" is reserved in strict mode.)
var public_interface = {
init: function () {
/* Do preliminary setup and launch into the combo root. */
// Setup traversal hook:
establish_traversal_handler();
my.combo_root_url = defaults.combo_root_url;
var combo_root = content_node_manager.get_combo_root();
var other_shares = content_node_manager.get(my.shares_root_url);
// Properly furnish login form:
prep_login_form('.nav_login_storage', storage_login,
'username', true);
prep_login_form('.nav_login_share',
other_shares.add_item_external.bind(other_shares),
'shareid', false);
// Hide everything below the banner, for subsequent unveiling:
combo_root.veil(true);
// Try a storage account if available from persistent settings
if (remember_manager.active()) {
var settings = remember_manager.fetch();
if (settings.username && settings.storage_host) {
set_storage_account(settings.username,
settings.storage_host,
settings.storage_web_url); }}
// ... and go:
$.mobile.changePage(combo_root.url); },
}
/* ===== Boilerplate ===== */
ContentNode.prototype.show_status_message = function (html, kind) {
/* Inject 'html' into the page DOM as a status message. Optional
'kind' is the status message kind - currently, 'result' and
'error' have distinct color styles, the default is 'error'.
Returns a produced $status_message object. */
kind = kind || 'error';
var selector = '.' + kind + '-status-message';
var $page = this.my_page$();
var $sm = $page.find(selector)
if ($sm.length > 0) {
$sm.html(html);
$sm.listview(); }
else {
var $li = $('<li class="status-message '
+ kind + '-status-message">');
$li.html(html);
$sm = $('<ul data-role="listview"/>');
$sm.append($li);
$page.find('[data-role="header"]').after($sm);
$sm.listview();
$sm.show(); }
return $sm; }
ContentNode.prototype.remove_status_message = function (kind) {
/* Remove existing status message of specified 'kind' (default,
all), if present. */
var selector = (kind
? '.' + kind + '-status-message'
: '.status-message');
var $page = this.my_page$();
var $sm = $page.find(selector);
if ($sm.length !== 0) {
$sm.remove(); }}
ContentNode.prototype.toString = function () {
return "<" + this.emblem + ": " + this.url + ">"; }
var document_addrs = {
/* Map specific document fragment addresses from the application
document to internal functions/methods. */
logout: storage_logout,
}
function internalize_url(obj) {
/* Return the "internal" version of the 'url'.
- For non-string objects, returns the object
- For fragments of the application code's url, returns the fragment
(sans the '#'),
- Translates page-ids for root content nodes to their urls,
- Those last two Combined transforms fragment references to root
content pages to the urls of those pages.
main body is that of the application. Otherwise, the original
object is returned. */
if (typeof obj !== "string") { return obj; }
if (obj.split('#')[0] === window.location.href.split('#')[0]) {
obj = obj.split('#')[1]; }
if (document_addrs.hasOwnProperty(obj)) {
return obj; }
switch (obj) {
case (defaults.combo_root_page_id):
return defaults.combo_root_url;
case (defaults.original_shares_root_page_id):
return my.original_shares_root_url;
case (defaults.other_shares_root_page_id):
return my.shares_root_url;
default: return obj; }}
function content_nodes_by_url_sorter(prev, next) {
var prev_str = prev, next_str = next;
var prev_name = content_node_manager.get(prev).name;
var next_name = content_node_manager.get(next).name;
if (prev_name && next_name) {
prev_str = prev_name, next_str = next_name; }
if (prev_str < next_str) { return -1; }
else if (prev_str > next_str) { return 1; }
else { return 0; }}
if (SO_DEBUGGING) {
// Expose the managers for access while debugging:
public_interface.cnmgr = cnmgr;
public_interface.pmgr = pmgr; }
/* ===== Here we go: ===== */
return public_interface;
}();
$(document).ready(function () {
"use strict"; // ECMAScript 5
// Development convenience: Go back to start page on full document reload.
// All the internal application state is gone, anyway.
if (window.location.hash) {
$.mobile.changePage(window.location.href.split('#')[0]); }
spideroak.init();
});
| "defaults.*" => "generic.*"
Generic better describes the settings that obtain regardless of login
accounts, versus "my.*" login-specific settings.
| SpiderOak.js | "defaults.*" => "generic.*" | <ide><path>piderOak.js
<ide>
<ide> /* ==== Object-wide settings ===== */
<ide>
<del> var defaults = {
<add> var generic = {
<ide> /* Settings not specific to a particular login session: */
<ide> // API v1.
<ide> // XXX base_host_url may vary according to brand package.
<ide> storage_root_url: null,
<ide> original_shares_root_url: null,
<ide> // All the service's actual shares reside within:
<del> shares_root_url: defaults.base_host_url + "/share/",
<add> shares_root_url: generic.base_host_url + "/share/",
<ide> share_room_urls: {},
<ide> original_share_room_urls: {},
<ide> };
<ide> my.storage_web_url = storage_web_url;
<ide>
<ide> my.storage_root_url = (host
<del> + defaults.storage_path_prefix
<add> + generic.storage_path_prefix
<ide> + base32.encode_trim(username)
<ide> + "/");
<ide> // Original root is determined by storage root:
<ide> /* Identify original share rooms root url. Depends on established
<ide> storage root. Return the url. */
<ide> my.original_shares_root_url =
<del> (my.storage_root_url + defaults.original_shares_path_suffix); }
<add> (my.storage_root_url + generic.original_shares_path_suffix); }
<ide> function register_share_room_url(url) {
<ide> /* Include url among the registered share rooms. Returns the url. */
<ide> my.share_room_urls[url] = true;
<ide> || (url === my.original_shares_root_url)
<ide> || (url === my.shares_root_url)); }
<ide> function is_content_root_page_id(url) {
<del> return ((url === defaults.combo_root_page_id)
<del> || (url === defaults.other_shares_root_page_id)
<del> || (url === defaults.original_shares_root_page_id)); }
<add> return ((url === generic.combo_root_page_id)
<add> || (url === generic.other_shares_root_page_id)
<add> || (url === generic.original_shares_root_page_id)); }
<ide> function is_share_room_url(url) {
<ide> /* True if the 'url' is for one of the familiar share rooms.
<ide> Doesn't depend on the url having an established node. */
<ide>
<ide> function RootStorageNode(url, parent) {
<ide> StorageNode.call(this, url, parent);
<del> this.query_qualifier = "?" + defaults.devices_query_expression;
<add> this.query_qualifier = "?" + generic.devices_query_expression;
<ide> this.emblem = "Root Storage";
<ide> this.stats = null;
<ide> delete this.files; }
<ide>
<ide> OtherRootShareNode.prototype.collection_menu = function (target_url) {
<ide> /* Present a menu of collection membership actions for 'target_url'. */
<del> // >>>
<add> alert("OtherRootShareNode.collection_menu");
<ide> }
<ide>
<ide> OtherRootShareNode.prototype.add_item_external = function (credentials) {
<ide> if (data.hasOwnProperty('files')) {
<ide> this.files = [];
<ide> var fields = ['name', 'size', 'ctime', 'mtime', 'versions'];
<del> defaults.preview_sizes.map(function (size) {
<add> generic.preview_sizes.map(function (size) {
<ide> /* Add previews, if any, to the fields. */
<ide> if (("preview_" + size) in data.files) {
<ide> fields.push("preview_" + size); }})
<ide> return this.url; }
<ide> RootContentNode.prototype.my_page_id = function () {
<ide> /* Set the UI page id, escaping special characters as necessary. */
<del> return defaults.combo_root_page_id; }
<add> return generic.combo_root_page_id; }
<ide> OtherRootShareNode.prototype.my_page_id = function () {
<ide> /* Set the UI page id, escaping special characters as necessary. */
<del> return defaults.other_shares_root_page_id; }
<add> return generic.other_shares_root_page_id; }
<ide> OriginalRootShareNode.prototype.my_page_id = function () {
<ide> /* Set the UI page id, escaping special characters as necessary. */
<del> return defaults.original_shares_root_page_id; }
<add> return generic.original_shares_root_page_id; }
<ide> ContentNode.prototype.show = function (chngpg_opts, mode_opts) {
<ide> /* Trigger UI focus on our content layout.
<ide> If mode_opts "passive" === true, don't do a changePage.
<ide> var lensubdirs = subdirs ? subdirs.length : 0;
<ide> files = files || this.files;
<ide> var lenfiles = files ? files.length : 0;
<del> var do_dividers = (lensubdirs + lenfiles) > defaults.dividers_threshold;
<del> var do_filter = (lensubdirs + lenfiles) > defaults.filter_threshold;
<add> var do_dividers = (lensubdirs + lenfiles) > generic.dividers_threshold;
<add> var do_filter = (lensubdirs + lenfiles) > generic.filter_threshold;
<ide>
<ide> function insert_item($item) {
<ide> if ($cursor === $list) { $cursor.append($item); }
<ide> if (! $template) {
<ide> error_alert("Missing markup",
<ide> "Expected page #"
<del> + defaults.content_page_template_id
<add> + generic.content_page_template_id
<ide> + " not present."); }
<ide> this.$page = $template.clone();
<ide> this.$page.attr('id', this.my_page_id());
<ide> Optional 'selector' is used, otherwise '.content-items'. */
<ide> return this.my_page$().find(selector || '.content-items'); }
<ide> ContentNode.prototype.get_storage_page_template$ = function() {
<del> return $("#" + defaults.content_page_template_id); }
<add> return $("#" + generic.content_page_template_id); }
<ide>
<ide>
<ide> /* ===== Resource managers ===== */
<ide> function storage_login(login_info, url) {
<ide> /* Login to storage account and commence browsing at devices.
<ide> 'login_info': An object with "username" and "password" attrs.
<del> 'url': An optional url, else defaults.storage_login_path is used.
<add> 'url': An optional url, else generic.storage_login_path is used.
<ide> We provide for redirection to specific alternative servers
<ide> by recursive calls. See:
<ide> https://spideroak.com/apis/partners/web_storage_api#Loggingin
<ide> login_url = url; }
<ide>
<ide> else {
<del> server_host_url = defaults.base_host_url;
<del> login_url = (server_host_url + defaults.storage_login_path); }
<add> server_host_url = generic.base_host_url;
<add> login_url = (server_host_url + generic.storage_login_path); }
<ide>
<ide> $.ajax({
<ide> url: login_url,
<ide> finish(); }
<ide> else {
<ide> // SpiderOak's logout url doesn't (as of 2012-06-15) remove cookies!
<del> $.ajax({url: my.storage_root_url + defaults.storage_logout_suffix,
<add> $.ajax({url: my.storage_root_url + generic.storage_logout_suffix,
<ide> type: 'GET',
<ide> success: function (data) {
<ide> finish(); },
<ide> // Setup traversal hook:
<ide> establish_traversal_handler();
<ide>
<del> my.combo_root_url = defaults.combo_root_url;
<add> my.combo_root_url = generic.combo_root_url;
<ide> var combo_root = content_node_manager.get_combo_root();
<ide> var other_shares = content_node_manager.get(my.shares_root_url);
<ide>
<ide> if (document_addrs.hasOwnProperty(obj)) {
<ide> return obj; }
<ide> switch (obj) {
<del> case (defaults.combo_root_page_id):
<del> return defaults.combo_root_url;
<del> case (defaults.original_shares_root_page_id):
<add> case (generic.combo_root_page_id):
<add> return generic.combo_root_url;
<add> case (generic.original_shares_root_page_id):
<ide> return my.original_shares_root_url;
<del> case (defaults.other_shares_root_page_id):
<add> case (generic.other_shares_root_page_id):
<ide> return my.shares_root_url;
<ide> default: return obj; }}
<ide> |
|
JavaScript | mit | 71fdf09630adcf4b56c8781052d9c9fbe8b36291 | 0 | usgoodus/react,psibi/react,ThinkedCoder/react,kamilio/react,maxschmeling/react,prometheansacrifice/react,linqingyicen/react,ianb/react,ericyang321/react,yangshun/react,KevinTCoughlin/react,gitoneman/react,ning-github/react,hawsome/react,wuguanghai45/react,richiethomas/react,supriyantomaftuh/react,silvestrijonathan/react,edvinerikson/react,hawsome/react,sejoker/react,rlugojr/react,marocchino/react,jordanpapaleo/react,TylerBrock/react,inuscript/react,shergin/react,kevin0307/react,gpbl/react,cinic/react,supriyantomaftuh/react,ZhouYong10/react,kamilio/react,Datahero/react,cpojer/react,haoxutong/react,gajus/react,shergin/react,thomasboyt/react,wmydz1/react,VioletLife/react,wesbos/react,dilidili/react,stardev24/react,slongwang/react,quip/react,SpencerCDixon/react,roylee0704/react,salier/react,zenlambda/react,ms-carterk/react,mohitbhatia1994/react,zanjs/react,niole/react,krasimir/react,BorderTravelerX/react,perperyu/react,bitshadow/react,kevin0307/react,joecritch/react,wmydz1/react,chrisbolin/react,Diaosir/react,ManrajGrover/react,ashwin01/react,zhangwei001/react,gougouGet/react,JasonZook/react,joe-strummer/react,digideskio/react,brigand/react,luomiao3/react,guoshencheng/react,leohmoraes/react,niubaba63/react,stanleycyang/react,flarnie/react,AnSavvides/react,jedwards1211/react,jontewks/react,ZhouYong10/react,luomiao3/react,agideo/react,ljhsai/react,jedwards1211/react,gitignorance/react,k-cheng/react,hejld/react,free-memory/react,musofan/react,iOSDevBlog/react,jlongster/react,AlmeroSteyn/react,silvestrijonathan/react,rohannair/react,neusc/react,garbles/react,zhangwei900808/react,IndraVikas/react,chippieTV/react,jessebeach/react,STRML/react,wangyzyoga/react,greyhwndz/react,james4388/react,ms-carterk/react,roth1002/react,benjaffe/react,haoxutong/react,chippieTV/react,guoshencheng/react,jameszhan/react,scottburch/react,wushuyi/react,kalloc/react,gpazo/react,dittos/react,silvestrijonathan/react,andrerpena/react,michaelchum/react,rohannair/react,digideskio/react,ssyang0102/react,digideskio/react,gfogle/react,TaaKey/react,jfschwarz/react,jfschwarz/react,ssyang0102/react,aickin/react,obimod/react,gfogle/react,flarnie/react,lhausermann/react,gold3bear/react,jfschwarz/react,linmic/react,TheBlasfem/react,stanleycyang/react,claudiopro/react,pze/react,reggi/react,yongxu/react,lastjune/react,psibi/react,crsr/react,chrisbolin/react,yangshun/react,yut148/react,mik01aj/react,prathamesh-sonpatki/react,AmericanSundown/react,jameszhan/react,tywinstark/react,ridixcr/react,zigi74/react,rgbkrk/react,ameyms/react,JungMinu/react,christer155/react,kamilio/react,kaushik94/react,Datahero/react,Flip120/react,jontewks/react,kay-is/react,diegobdev/react,lucius-feng/react,kaushik94/react,iOSDevBlog/react,ArunTesco/react,jorrit/react,Jonekee/react,ThinkedCoder/react,pswai/react,jorrit/react,stardev24/react,apaatsio/react,nhunzaker/react,gpazo/react,empyrical/react,huanglp47/react,miaozhirui/react,gleborgne/react,staltz/react,spt110/react,aickin/react,ramortegui/react,jimfb/react,garbles/react,afc163/react,jmptrader/react,vipulnsward/react,dgdblank/react,shadowhunter2/react,camsong/react,zenlambda/react,nLight/react,dortonway/react,ThinkedCoder/react,honger05/react,AmericanSundown/react,VioletLife/react,PeterWangPo/react,dmatteo/react,dmatteo/react,zs99/react,acdlite/react,zhangwei900808/react,sarvex/react,flarnie/react,iOSDevBlog/react,nickdima/react,syranide/react,algolia/react,andreypopp/react,Simek/react,tomocchino/react,agideo/react,yasaricli/react,ipmobiletech/react,tzq668766/react,yongxu/react,Simek/react,ashwin01/react,anushreesubramani/react,temnoregg/react,iammerrick/react,yhagio/react,1yvT0s/react,jmptrader/react,framp/react,flarnie/react,gj262/react,alexanther1012/react,linalu1/react,jontewks/react,kamilio/react,yjyi/react,blue68/react,ms-carterk/react,niole/react,jbonta/react,jbonta/react,skevy/react,lhausermann/react,JoshKaufman/react,pod4g/react,ouyangwenfeng/react,davidmason/react,dortonway/react,magalhas/react,stevemao/react,kolmstead/react,trungda/react,mik01aj/react,kieranjones/react,pwmckenna/react,perterest/react,salier/react,jedwards1211/react,Riokai/react,roylee0704/react,liyayun/react,devonharvey/react,chippieTV/react,edmellum/react,joaomilho/react,nsimmons/react,wushuyi/react,levibuzolic/react,tomocchino/react,davidmason/react,yiminghe/react,apaatsio/react,jsdf/react,hejld/react,leexiaosi/react,TaaKey/react,Jyrno42/react,mohitbhatia1994/react,zorojean/react,carlosipe/react,mnordick/react,linmic/react,iammerrick/react,conorhastings/react,magalhas/react,sitexa/react,JasonZook/react,DigitalCoder/react,IndraVikas/react,mhhegazy/react,salzhrani/react,Diaosir/react,jessebeach/react,wudouxingjun/react,rickbeerendonk/react,dgreensp/react,labs00/react,reggi/react,chenglou/react,facebook/react,obimod/react,neomadara/react,felixgrey/react,PeterWangPo/react,staltz/react,pod4g/react,arush/react,tomocchino/react,tako-black/react-1,bitshadow/react,tywinstark/react,sasumi/react,JoshKaufman/react,deepaksharmacse12/react,ManrajGrover/react,eoin/react,pze/react,facebook/react,alvarojoao/react,airondumael/react,edmellum/react,niole/react,chinakids/react,jedwards1211/react,jquense/react,rohannair/react,wzpan/react,chrisjallen/react,Jyrno42/react,chrismoulton/react,andrewsokolov/react,linmic/react,tako-black/react-1,yhagio/react,arkist/react,terminatorheart/react,yulongge/react,cesine/react,aickin/react,ericyang321/react,8398a7/react,iOSDevBlog/react,mcanthony/react,Datahero/react,syranide/react,BreemsEmporiumMensToiletriesFragrances/react,orzyang/react,JanChw/react,isathish/react,k-cheng/react,Simek/react,willhackett/react,ramortegui/react,yut148/react,reggi/react,KevinTCoughlin/react,reactkr/react,terminatorheart/react,gold3bear/react,patrickgoudjoako/react,arkist/react,chenglou/react,haoxutong/react,facebook/react,quip/react,zofuthan/react,jdlehman/react,bspaulding/react,sugarshin/react,stardev24/react,jorrit/react,kakadiya91/react,jeffchan/react,rlugojr/react,nLight/react,brigand/react,bspaulding/react,Galactix/react,zyt01/react,nomanisan/react,ashwin01/react,dortonway/react,wushuyi/react,phillipalexander/react,darobin/react,andrerpena/react,lina/react,yasaricli/react,huanglp47/react,reactjs-vn/reactjs_vndev,ABaldwinHunter/react-engines,chrisjallen/react,guoshencheng/react,nsimmons/react,TaaKey/react,haoxutong/react,ABaldwinHunter/react-engines,mgmcdermott/react,sugarshin/react,thomasboyt/react,davidmason/react,zenlambda/react,eoin/react,diegobdev/react,jmptrader/react,yut148/react,Jericho25/react,microlv/react,it33/react,jeffchan/react,camsong/react,howtolearntocode/react,nathanmarks/react,dmatteo/react,benchling/react,trellowebinars/react,felixgrey/react,jedwards1211/react,Diaosir/react,yabhis/react,dfosco/react,Galactix/react,sarvex/react,orneryhippo/react,studiowangfei/react,javascriptit/react,trungda/react,quip/react,pswai/react,alvarojoao/react,afc163/react,leohmoraes/react,dortonway/react,greysign/react,ouyangwenfeng/react,silkapp/react,sasumi/react,gitoneman/react,zhangwei001/react,lina/react,trungda/react,aaron-goshine/react,yasaricli/react,lastjune/react,pyitphyoaung/react,joecritch/react,neomadara/react,theseyi/react,arush/react,greysign/react,dittos/react,devonharvey/react,venkateshdaram434/react,camsong/react,yut148/react,cpojer/react,easyfmxu/react,ZhouYong10/react,prometheansacrifice/react,skomski/react,billfeller/react,hejld/react,gxr1020/react,speedyGonzales/react,tomv564/react,sejoker/react,gregrperkins/react,anushreesubramani/react,usgoodus/react,rasj/react,howtolearntocode/react,gregrperkins/react,popovsh6/react,vipulnsward/react,juliocanares/react,VioletLife/react,reactjs-vn/reactjs_vndev,ms-carterk/react,jimfb/react,huanglp47/react,nickpresta/react,ilyachenko/react,dilidili/react,yiminghe/react,ABaldwinHunter/react-classic,inuscript/react,dustin-H/react,linmic/react,brigand/react,perterest/react,AlmeroSteyn/react,demohi/react,panhongzhi02/react,labs00/react,stevemao/react,vincentism/react,1234-/react,Galactix/react,blue68/react,rohannair/react,brigand/react,lastjune/react,yiminghe/react,andrerpena/react,yungsters/react,IndraVikas/react,BreemsEmporiumMensToiletriesFragrances/react,dilidili/react,nhunzaker/react,quip/react,yisbug/react,trueadm/react,mhhegazy/react,jiangzhixiao/react,dgladkov/react,gitoneman/react,stardev24/react,JoshKaufman/react,gxr1020/react,it33/react,digideskio/react,dirkliu/react,1234-/react,zeke/react,Jyrno42/react,niubaba63/react,claudiopro/react,yjyi/react,yongxu/react,jagdeesh109/react,linqingyicen/react,gregrperkins/react,vincentism/react,gougouGet/react,scottburch/react,alvarojoao/react,JanChw/react,silvestrijonathan/react,trungda/react,microlv/react,scottburch/react,acdlite/react,jsdf/react,lennerd/react,billfeller/react,Jericho25/react,easyfmxu/react,nathanmarks/react,salzhrani/react,rricard/react,skyFi/react,chenglou/react,sergej-kucharev/react,conorhastings/react,mhhegazy/react,mjackson/react,gold3bear/react,mjackson/react,cody/react,jdlehman/react,claudiopro/react,roylee0704/react,gleborgne/react,TaaKey/react,jquense/react,niubaba63/react,blainekasten/react,jabhishek/react,marocchino/react,rwwarren/react,Jericho25/react,TheBlasfem/react,christer155/react,usgoodus/react,AlmeroSteyn/react,neomadara/react,devonharvey/react,lhausermann/react,dmitriiabramov/react,acdlite/react,cpojer/react,1234-/react,dfosco/react,trungda/react,brigand/react,richiethomas/react,6feetsong/react,dirkliu/react,stardev24/react,blainekasten/react,isathish/react,salier/react,jzmq/react,patrickgoudjoako/react,obimod/react,xiaxuewuhen001/react,trellowebinars/react,felixgrey/react,kakadiya91/react,jbonta/react,glenjamin/react,marocchino/react,JoshKaufman/react,shergin/react,pwmckenna/react,ning-github/react,insionng/react,kakadiya91/react,0x00evil/react,AnSavvides/react,microlv/react,mjackson/react,leeleo26/react,willhackett/react,iOSDevBlog/react,alvarojoao/react,arasmussen/react,kolmstead/react,orneryhippo/react,TaaKey/react,ramortegui/react,insionng/react,sasumi/react,bspaulding/react,zhangwei001/react,sasumi/react,tom-wang/react,rohannair/react,concerned3rdparty/react,KevinTCoughlin/react,andrescarceller/react,terminatorheart/react,silkapp/react,gxr1020/react,joecritch/react,jabhishek/react,iamchenxin/react,benchling/react,studiowangfei/react,mnordick/react,musofan/react,nhunzaker/react,crsr/react,0x00evil/react,gitignorance/react,mgmcdermott/react,patrickgoudjoako/react,AmericanSundown/react,kaushik94/react,rohannair/react,bestwpw/react,JungMinu/react,joon1030/react,niole/react,elquatro/react,tako-black/react-1,LoQIStar/react,jkcaptain/react,jimfb/react,AlmeroSteyn/react,zhengqiangzi/react,zofuthan/react,jsdf/react,quip/react,prathamesh-sonpatki/react,mcanthony/react,szhigunov/react,ajdinhedzic/react,quip/react,tywinstark/react,Furzikov/react,gfogle/react,yulongge/react,KevinTCoughlin/react,rricard/react,andrescarceller/react,kamilio/react,magalhas/react,ABaldwinHunter/react-engines,chicoxyzzy/react,tlwirtz/react,silvestrijonathan/react,pyitphyoaung/react,jordanpapaleo/react,dittos/react,cmfcmf/react,lonely8rain/react,blainekasten/react,sergej-kucharev/react,orzyang/react,misnet/react,LoQIStar/react,jquense/react,marocchino/react,zofuthan/react,jquense/react,wudouxingjun/react,tzq668766/react,zorojean/react,Flip120/react,bestwpw/react,skevy/react,vincentism/react,obimod/react,bhamodi/react,kamilio/react,wjb12/react,joon1030/react,tywinstark/react,joe-strummer/react,maxschmeling/react,venkateshdaram434/react,theseyi/react,wmydz1/react,iamchenxin/react,Furzikov/react,rlugojr/react,algolia/react,Jonekee/react,laskos/react,Duc-Ngo-CSSE/react,Spotinux/react,JasonZook/react,concerned3rdparty/react,reggi/react,reactkr/react,shadowhunter2/react,brillantesmanuel/react,bspaulding/react,chrismoulton/react,sejoker/react,bhamodi/react,inuscript/react,yungsters/react,sarvex/react,jagdeesh109/react,jlongster/react,silkapp/react,orzyang/react,STRML/react,STRML/react,benjaffe/react,skevy/react,trellowebinars/react,edvinerikson/react,jzmq/react,krasimir/react,k-cheng/react,JasonZook/react,staltz/react,studiowangfei/react,easyfmxu/react,jimfb/react,agideo/react,cinic/react,dittos/react,STRML/react,popovsh6/react,joe-strummer/react,tom-wang/react,empyrical/react,Chiens/react,digideskio/react,jordanpapaleo/react,gajus/react,jameszhan/react,conorhastings/react,laskos/react,staltz/react,zs99/react,nathanmarks/react,STRML/react,Furzikov/react,dilidili/react,bspaulding/react,ledrui/react,airondumael/react,sekiyaeiji/react,yuhualingfeng/react,ms-carterk/react,jdlehman/react,ning-github/react,dfosco/react,gajus/react,tom-wang/react,mhhegazy/react,zs99/react,terminatorheart/react,panhongzhi02/react,cmfcmf/react,lhausermann/react,garbles/react,pyitphyoaung/react,nathanmarks/react,chinakids/react,joshblack/react,wangyzyoga/react,levibuzolic/react,gpazo/react,haoxutong/react,reggi/react,LoQIStar/react,microlv/react,dgdblank/react,staltz/react,cinic/react,zorojean/react,dgdblank/react,ThinkedCoder/react,negativetwelve/react,jfschwarz/react,concerned3rdparty/react,yuhualingfeng/react,darobin/react,Chiens/react,shergin/react,dgreensp/react,jbonta/react,hawsome/react,mhhegazy/react,Duc-Ngo-CSSE/react,luomiao3/react,pswai/react,mnordick/react,dgdblank/react,sasumi/react,davidmason/react,cody/react,mosoft521/react,empyrical/react,mjackson/react,with-git/react,ZhouYong10/react,flarnie/react,zanjs/react,christer155/react,apaatsio/react,gpbl/react,dustin-H/react,edvinerikson/react,afc163/react,hawsome/react,misnet/react,trueadm/react,ABaldwinHunter/react-classic,free-memory/react,usgoodus/react,genome21/react,Furzikov/react,free-memory/react,niubaba63/react,joshblack/react,Riokai/react,reggi/react,AmericanSundown/react,inuscript/react,marocchino/react,sdiaz/react,guoshencheng/react,joecritch/react,levibuzolic/react,nickdima/react,billfeller/react,roth1002/react,Simek/react,tarjei/react,salier/react,pyitphyoaung/react,dfosco/react,chrisjallen/react,zyt01/react,zeke/react,cesine/react,tzq668766/react,brillantesmanuel/react,skyFi/react,pdaddyo/react,IndraVikas/react,easyfmxu/react,framp/react,ZhouYong10/react,yisbug/react,lonely8rain/react,billfeller/react,yongxu/react,Jericho25/react,tarjei/react,andreypopp/react,richiethomas/react,dirkliu/react,sejoker/react,mosoft521/react,zigi74/react,Jonekee/react,hawsome/react,demohi/react,anushreesubramani/react,carlosipe/react,liyayun/react,orneryhippo/react,jzmq/react,ameyms/react,wangyzyoga/react,tomocchino/react,bitshadow/react,jameszhan/react,arkist/react,airondumael/react,bspaulding/react,jameszhan/react,patrickgoudjoako/react,andreypopp/react,prometheansacrifice/react,kaushik94/react,jontewks/react,pswai/react,isathish/react,joecritch/react,glenjamin/react,iamchenxin/react,chippieTV/react,yangshun/react,ianb/react,negativetwelve/react,joaomilho/react,flipactual/react,kolmstead/react,spt110/react,theseyi/react,it33/react,musofan/react,jzmq/react,alvarojoao/react,iamchenxin/react,edmellum/react,yangshun/react,jagdeesh109/react,jbonta/react,billfeller/react,trueadm/react,alexanther1012/react,jmacman007/react,bestwpw/react,insionng/react,apaatsio/react,andrerpena/react,BreemsEmporiumMensToiletriesFragrances/react,davidmason/react,empyrical/react,dittos/react,gfogle/react,roth1002/react,yuhualingfeng/react,garbles/react,Simek/react,joaomilho/react,pze/react,lennerd/react,linmic/react,gpazo/react,glenjamin/react,sdiaz/react,gajus/react,tako-black/react-1,jmptrader/react,arasmussen/react,DigitalCoder/react,cody/react,jlongster/react,yungsters/react,usgoodus/react,Duc-Ngo-CSSE/react,obimod/react,howtolearntocode/react,bleyle/react,rgbkrk/react,prometheansacrifice/react,jorrit/react,christer155/react,terminatorheart/react,kaushik94/react,christer155/react,perperyu/react,sugarshin/react,lucius-feng/react,VioletLife/react,rgbkrk/react,trellowebinars/react,jkcaptain/react,patrickgoudjoako/react,eoin/react,niole/react,deepaksharmacse12/react,joe-strummer/react,STRML/react,gj262/react,yangshun/react,dmitriiabramov/react,javascriptit/react,concerned3rdparty/react,arkist/react,glenjamin/react,zeke/react,bspaulding/react,ms-carterk/react,ajdinhedzic/react,levibuzolic/react,dmitriiabramov/react,brian-murray35/react,gpbl/react,ramortegui/react,camsong/react,ZhouYong10/react,psibi/react,skyFi/react,ameyms/react,zeke/react,roylee0704/react,insionng/react,andrescarceller/react,mohitbhatia1994/react,zorojean/react,conorhastings/react,airondumael/react,chenglou/react,skevy/react,vincentism/react,prathamesh-sonpatki/react,miaozhirui/react,yulongge/react,zhengqiangzi/react,rlugojr/react,Flip120/react,rwwarren/react,mcanthony/react,chinakids/react,TheBlasfem/react,garbles/react,DigitalCoder/react,tomocchino/react,davidmason/react,getshuvo/react,prometheansacrifice/react,honger05/react,thomasboyt/react,ArunTesco/react,rricard/react,brillantesmanuel/react,mik01aj/react,mjackson/react,richiethomas/react,yasaricli/react,blue68/react,sitexa/react,1234-/react,prathamesh-sonpatki/react,ajdinhedzic/react,bleyle/react,huanglp47/react,kieranjones/react,BreemsEmporiumMensToiletriesFragrances/react,JungMinu/react,rasj/react,pandoraui/react,agileurbanite/react,wmydz1/react,vincentism/react,k-cheng/react,0x00evil/react,zhengqiangzi/react,richiethomas/react,salzhrani/react,ABaldwinHunter/react-classic,edmellum/react,jzmq/react,zyt01/react,lastjune/react,kay-is/react,temnoregg/react,yuhualingfeng/react,psibi/react,aickin/react,algolia/react,rricard/react,nathanmarks/react,shergin/react,aaron-goshine/react,gregrperkins/react,vincentnacar02/react,kay-is/react,ledrui/react,Rafe/react,Spotinux/react,jfschwarz/react,acdlite/react,Riokai/react,yiminghe/react,manl1100/react,dilidili/react,lonely8rain/react,levibuzolic/react,chrismoulton/react,manl1100/react,tlwirtz/react,Nieralyte/react,chicoxyzzy/react,speedyGonzales/react,insionng/react,spt110/react,zofuthan/react,jameszhan/react,sarvex/react,afc163/react,spt110/react,chenglou/react,framp/react,brillantesmanuel/react,dgladkov/react,Simek/react,isathish/react,tjsavage/react,jdlehman/react,tom-wang/react,linqingyicen/react,camsong/react,ramortegui/react,zanjs/react,mingyaaaa/react,benchling/react,mosoft521/react,chicoxyzzy/react,lyip1992/react,ledrui/react,pwmckenna/react,evilemon/react,mingyaaaa/react,jsdf/react,stardev24/react,phillipalexander/react,patryknowak/react,jagdeesh109/react,billfeller/react,ledrui/react,sdiaz/react,wmydz1/react,tomv564/react,MotherNature/react,it33/react,jessebeach/react,jorrit/react,yungsters/react,tako-black/react-1,stanleycyang/react,roylee0704/react,aaron-goshine/react,silppuri/react,zilaiyedaren/react,anushreesubramani/react,pyitphyoaung/react,henrik/react,arkist/react,nLight/react,brillantesmanuel/react,PeterWangPo/react,yabhis/react,vincentnacar02/react,pyitphyoaung/react,zenlambda/react,gxr1020/react,apaatsio/react,claudiopro/react,dustin-H/react,jontewks/react,TaaKey/react,with-git/react,ashwin01/react,wzpan/react,nickpresta/react,andrerpena/react,Jyrno42/react,krasimir/react,lonely8rain/react,facebook/react,gregrperkins/react,joaomilho/react,salzhrani/react,zs99/react,neusc/react,JoshKaufman/react,empyrical/react,james4388/react,gpbl/react,AnSavvides/react,jontewks/react,sekiyaeiji/react,slongwang/react,jlongster/react,kaushik94/react,hejld/react,nickpresta/react,honger05/react,ericyang321/react,lina/react,jordanpapaleo/react,jzmq/react,inuscript/react,MotherNature/react,flipactual/react,sugarshin/react,neomadara/react,salier/react,microlv/react,juliocanares/react,TaaKey/react,yongxu/react,laskos/react,nhunzaker/react,mingyaaaa/react,yisbug/react,zorojean/react,dgladkov/react,greglittlefield-wf/react,jeffchan/react,yungsters/react,Flip120/react,JoshKaufman/react,stanleycyang/react,afc163/react,Nieralyte/react,Riokai/react,pze/react,dgdblank/react,alwayrun/react,sekiyaeiji/react,JanChw/react,sarvex/react,yhagio/react,KevinTCoughlin/react,edmellum/react,pandoraui/react,6feetsong/react,claudiopro/react,hawsome/react,krasimir/react,zigi74/react,with-git/react,pdaddyo/react,magalhas/react,rickbeerendonk/react,devonharvey/react,rgbkrk/react,sugarshin/react,laskos/react,gpazo/react,Simek/react,supriyantomaftuh/react,salier/react,mcanthony/react,sugarshin/react,thomasboyt/react,skomski/react,nhunzaker/react,BreemsEmporiumMensToiletriesFragrances/react,jbonta/react,acdlite/react,gitoneman/react,reactjs-vn/reactjs_vndev,reactkr/react,james4388/react,darobin/react,vincentnacar02/react,zilaiyedaren/react,framp/react,TheBlasfem/react,dirkliu/react,andreypopp/react,crsr/react,wzpan/react,dmitriiabramov/react,jimfb/react,chicoxyzzy/react,jsdf/react,arasmussen/react,roth1002/react,chenglou/react,musofan/react,flarnie/react,greyhwndz/react,leexiaosi/react,empyrical/react,arasmussen/react,slongwang/react,reactkr/react,Spotinux/react,0x00evil/react,felixgrey/react,mosoft521/react,with-git/react,framp/react,andrewsokolov/react,guoshencheng/react,tlwirtz/react,easyfmxu/react,dustin-H/react,haoxutong/react,wudouxingjun/react,empyrical/react,joaomilho/react,kolmstead/react,reactkr/react,0x00evil/react,henrik/react,getshuvo/react,studiowangfei/react,rickbeerendonk/react,vincentism/react,Jericho25/react,laskos/react,k-cheng/react,Furzikov/react,dittos/react,diegobdev/react,ianb/react,glenjamin/react,Flip120/react,mgmcdermott/react,acdlite/react,xiaxuewuhen001/react,elquatro/react,skomski/react,pandoraui/react,TaaKey/react,elquatro/react,ashwin01/react,pwmckenna/react,howtolearntocode/react,ridixcr/react,zeke/react,jeffchan/react,ipmobiletech/react,insionng/react,zhangwei001/react,claudiopro/react,AnSavvides/react,yabhis/react,AlmeroSteyn/react,lennerd/react,joon1030/react,perterest/react,nsimmons/react,thomasboyt/react,stevemao/react,dirkliu/react,jmacman007/react,dortonway/react,dmatteo/react,jessebeach/react,jameszhan/react,kalloc/react,ledrui/react,MotherNature/react,blainekasten/react,panhongzhi02/react,richiethomas/react,roth1002/react,silppuri/react,zilaiyedaren/react,gpazo/react,michaelchum/react,chicoxyzzy/react,speedyGonzales/react,prathamesh-sonpatki/react,arasmussen/react,negativetwelve/react,6feetsong/react,mgmcdermott/react,Nieralyte/react,temnoregg/react,slongwang/react,k-cheng/react,camsong/react,devonharvey/react,chrisbolin/react,easyfmxu/react,alwayrun/react,patryknowak/react,linalu1/react,carlosipe/react,Spotinux/react,mardigtch/react,acdlite/react,scottburch/react,evilemon/react,TaaKey/react,lyip1992/react,ilyachenko/react,ericyang321/react,microlv/react,eoin/react,labs00/react,savelichalex/react,dgdblank/react,alvarojoao/react,trungda/react,hejld/react,studiowangfei/react,wuguanghai45/react,panhongzhi02/react,albulescu/react,temnoregg/react,DJCordhose/react,silppuri/react,elquatro/react,vipulnsward/react,levibuzolic/react,STRML/react,mcanthony/react,brigand/react,ridixcr/react,lennerd/react,rricard/react,manl1100/react,marocchino/react,silvestrijonathan/react,niubaba63/react,staltz/react,sergej-kucharev/react,vipulnsward/react,jmacman007/react,pdaddyo/react,richiethomas/react,jeffchan/react,chenglou/react,laskos/react,iamchenxin/react,dgreensp/react,IndraVikas/react,negativetwelve/react,aickin/react,yisbug/react,leeleo26/react,jmptrader/react,gpbl/react,edvinerikson/react,1yvT0s/react,crsr/react,jdlehman/react,albulescu/react,spt110/react,szhigunov/react,cmfcmf/react,mhhegazy/react,lennerd/react,lucius-feng/react,gxr1020/react,0x00evil/react,theseyi/react,nhunzaker/react,yut148/react,kakadiya91/react,rgbkrk/react,wuguanghai45/react,jagdeesh109/react,digideskio/react,nickdima/react,orneryhippo/react,joaomilho/react,gajus/react,gfogle/react,chacbumbum/react,AlmeroSteyn/react,edvinerikson/react,jordanpapaleo/react,supriyantomaftuh/react,AnSavvides/react,bleyle/react,joecritch/react,Rafe/react,sejoker/react,mosoft521/react,leohmoraes/react,jsdf/react,nLight/react,sitexa/react,vipulnsward/react,nomanisan/react,airondumael/react,jlongster/react,nickdima/react,benjaffe/react,yangshun/react,BorderTravelerX/react,dfosco/react,cesine/react,andreypopp/react,tlwirtz/react,evilemon/react,crsr/react,anushreesubramani/react,zyt01/react,jeffchan/react,andrewsokolov/react,yulongge/react,Rafe/react,mosoft521/react,savelichalex/react,tomocchino/react,pdaddyo/react,flowbywind/react,savelichalex/react,mhhegazy/react,silkapp/react,dgreensp/react,ABaldwinHunter/react-classic,yjyi/react,phillipalexander/react,panhongzhi02/react,blainekasten/react,iamchenxin/react,mingyaaaa/react,tomv564/react,panhongzhi02/react,genome21/react,yisbug/react,eoin/react,VioletLife/react,neusc/react,dustin-H/react,brian-murray35/react,gajus/react,ljhsai/react,jorrit/react,apaatsio/react,aaron-goshine/react,facebook/react,flipactual/react,yungsters/react,roylee0704/react,yulongge/react,jmacman007/react,kevin0307/react,ameyms/react,andrescarceller/react,nathanmarks/react,cmfcmf/react,zhangwei900808/react,howtolearntocode/react,hejld/react,ArunTesco/react,lyip1992/react,dilidili/react,jdlehman/react,ericyang321/react,maxschmeling/react,concerned3rdparty/react,syranide/react,Riokai/react,ridixcr/react,concerned3rdparty/react,conorhastings/react,jzmq/react,deepaksharmacse12/react,roth1002/react,flowbywind/react,ipmobiletech/react,ashwin01/react,shergin/react,soulcm/react,nickdima/react,zofuthan/react,andreypopp/react,silkapp/react,IndraVikas/react,wushuyi/react,ABaldwinHunter/react-engines,Jericho25/react,perterest/react,soulcm/react,tjsavage/react,zenlambda/react,savelichalex/react,jkcaptain/react,james4388/react,chacbumbum/react,DJCordhose/react,Chiens/react,tako-black/react-1,agileurbanite/react,nickpresta/react,mjackson/react,bhamodi/react,deepaksharmacse12/react,ericyang321/react,neomadara/react,miaozhirui/react,reactjs-vn/reactjs_vndev,pswai/react,maxschmeling/react,blainekasten/react,leohmoraes/react,zhangwei001/react,spt110/react,mardigtch/react,dgreensp/react,maxschmeling/react,chrisjallen/react,gougouGet/react,yangshun/react,MotherNature/react,Jyrno42/react,greglittlefield-wf/react,dustin-H/react,leexiaosi/react,wesbos/react,mgmcdermott/react,maxschmeling/react,cody/react,with-git/react,linmic/react,lyip1992/react,kalloc/react,tom-wang/react,SpencerCDixon/react,negativetwelve/react,tomocchino/react,neusc/react,savelichalex/react,cody/react,chippieTV/react,AmericanSundown/react,ABaldwinHunter/react-engines,ManrajGrover/react,rickbeerendonk/react,tomv564/react,tarjei/react,musofan/react,conorhastings/react,rwwarren/react,facebook/react,it33/react,reactjs-vn/reactjs_vndev,syranide/react,guoshencheng/react,DJCordhose/react,TheBlasfem/react,glenjamin/react,miaozhirui/react,niubaba63/react,perterest/react,TaaKey/react,pwmckenna/react,temnoregg/react,zhangwei001/react,ilyachenko/react,cpojer/react,skevy/react,lastjune/react,deepaksharmacse12/react,rlugojr/react,bhamodi/react,demohi/react,javascriptit/react,wmydz1/react,chacbumbum/react,trueadm/react,yut148/react,TylerBrock/react,magalhas/react,jordanpapaleo/react,arkist/react,reactjs-vn/reactjs_vndev,VioletLife/react,yuhualingfeng/react,leeleo26/react,salzhrani/react,nLight/react,Furzikov/react,stanleycyang/react,rasj/react,wushuyi/react,gitignorance/react,bitshadow/react,arasmussen/react,kolmstead/react,getshuvo/react,andrescarceller/react,genome21/react,agileurbanite/react,TheBlasfem/react,ABaldwinHunter/react-classic,popovsh6/react,rickbeerendonk/react,linqingyicen/react,nomanisan/react,miaozhirui/react,ouyangwenfeng/react,lyip1992/react,magalhas/react,niubaba63/react,leohmoraes/react,chicoxyzzy/react,joshblack/react,Spotinux/react,aickin/react,joecritch/react,ljhsai/react,pod4g/react,juliocanares/react,liyayun/react,zyt01/react,nickpresta/react,huanglp47/react,psibi/react,vipulnsward/react,AnSavvides/react,devonharvey/react,ThinkedCoder/react,chippieTV/react,JasonZook/react,iOSDevBlog/react,wjb12/react,jeromjoy/react,zigi74/react,gleborgne/react,chicoxyzzy/react,tom-wang/react,nickpresta/react,rickbeerendonk/react,neusc/react,yisbug/react,prometheansacrifice/react,flarnie/react,with-git/react,TaaKey/react,elquatro/react,rlugojr/react,wjb12/react,quip/react,soulcm/react,rlugojr/react,tlwirtz/react,gpbl/react,zs99/react,henrik/react,jordanpapaleo/react,yiminghe/react,cpojer/react,shadowhunter2/react,garbles/react,lhausermann/react,aaron-goshine/react,rickbeerendonk/react,nLight/react,jquense/react,lonely8rain/react,jimfb/react,pze/react,jquense/react,jmacman007/react,wjb12/react,billfeller/react,cmfcmf/react,pdaddyo/react,1234-/react,patrickgoudjoako/react,mgmcdermott/react,stanleycyang/react,trueadm/react,DJCordhose/react,tlwirtz/react,krasimir/react,pswai/react,pandoraui/react,with-git/react,anushreesubramani/react,ericyang321/react,aickin/react,dilidili/react,krasimir/react,8398a7/react,maxschmeling/react,greysign/react,dmitriiabramov/react,jmacman007/react,tarjei/react,rohannair/react,aaron-goshine/react,jedwards1211/react,albulescu/react,flowbywind/react,dirkliu/react,alexanther1012/react,gold3bear/react,terminatorheart/react,linqingyicen/react,mjackson/react,dortonway/react,gfogle/react,xiaxuewuhen001/react,ssyang0102/react,neusc/react,manl1100/react,patryknowak/react,wjb12/react,mcanthony/react,claudiopro/react,zigi74/react,ABaldwinHunter/react-classic,eoin/react,joshblack/react,greyhwndz/react,ridixcr/react,yiminghe/react,facebook/react,trueadm/react,anushreesubramani/react,zenlambda/react,apaatsio/react,nhunzaker/react,joshblack/react,skevy/react,VioletLife/react,musofan/react,ridixcr/react,framp/react,kieranjones/react,honger05/react,slongwang/react,camsong/react,shergin/react,elquatro/react,pyitphyoaung/react,mik01aj/react,iammerrick/react,honger05/react,jquense/react,salzhrani/react,ameyms/react,isathish/react,supriyantomaftuh/react,Diaosir/react,Spotinux/react,theseyi/react,yasaricli/react,gj262/react,lyip1992/react,lhausermann/react,1yvT0s/react,yungsters/react,miaozhirui/react,mardigtch/react,benchling/react,ABaldwinHunter/react-engines,jeromjoy/react,tjsavage/react,edvinerikson/react,usgoodus/react,gitoneman/react,cmfcmf/react,Diaosir/react,benchling/react,DJCordhose/react,reactkr/react,james4388/react,pandoraui/react,theseyi/react,tarjei/react,jiangzhixiao/react,zs99/react,joe-strummer/react,alwayrun/react,iammerrick/react,kakadiya91/react,linalu1/react,zigi74/react,misnet/react,dmitriiabramov/react,cpojer/react,tywinstark/react,roth1002/react,greglittlefield-wf/react,savelichalex/react,DJCordhose/react,dgreensp/react,AlmeroSteyn/react,BorderTravelerX/react,1234-/react,thomasboyt/react,venkateshdaram434/react,wesbos/react,wmydz1/react,ameyms/react,jeromjoy/react,benchling/react,felixgrey/react,Rafe/react,bitshadow/react,arush/react,jorrit/react,mingyaaaa/react,chacbumbum/react,Rafe/react,orneryhippo/react,prathamesh-sonpatki/react,MotherNature/react,8398a7/react,bhamodi/react,szhigunov/react,mosoft521/react,trellowebinars/react,kakadiya91/react,gold3bear/react,KevinTCoughlin/react,yiminghe/react,joe-strummer/react,chrisjallen/react,sarvex/react,trellowebinars/react,glenjamin/react,edvinerikson/react,jlongster/react,andrerpena/react,rricard/react,silvestrijonathan/react,lonely8rain/react,kaushik94/react,willhackett/react,scottburch/react,perperyu/react,bitshadow/react,trueadm/react,SpencerCDixon/react,chacbumbum/react,cody/react,orneryhippo/react,it33/react,james4388/react,brian-murray35/react,brillantesmanuel/react,jiangzhixiao/react,jessebeach/react,cpojer/react,krasimir/react,inuscript/react,manl1100/react,zeke/react,zyt01/react,bhamodi/react,brigand/react,michaelchum/react,tomv564/react,mik01aj/react,howtolearntocode/react,TylerBrock/react,gregrperkins/react,prometheansacrifice/react,Riokai/react,zorojean/react,edmellum/react,Jyrno42/react,jabhishek/react,iammerrick/react,dmatteo/react,jdlehman/react | /**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule HTMLDOMPropertyConfig
*/
/*jslint bitwise: true*/
'use strict';
var DOMProperty = require('DOMProperty');
var ExecutionEnvironment = require('ExecutionEnvironment');
var MUST_USE_ATTRIBUTE = DOMProperty.injection.MUST_USE_ATTRIBUTE;
var MUST_USE_PROPERTY = DOMProperty.injection.MUST_USE_PROPERTY;
var HAS_BOOLEAN_VALUE = DOMProperty.injection.HAS_BOOLEAN_VALUE;
var HAS_SIDE_EFFECTS = DOMProperty.injection.HAS_SIDE_EFFECTS;
var HAS_NUMERIC_VALUE = DOMProperty.injection.HAS_NUMERIC_VALUE;
var HAS_POSITIVE_NUMERIC_VALUE =
DOMProperty.injection.HAS_POSITIVE_NUMERIC_VALUE;
var HAS_OVERLOADED_BOOLEAN_VALUE =
DOMProperty.injection.HAS_OVERLOADED_BOOLEAN_VALUE;
var hasSVG;
if (ExecutionEnvironment.canUseDOM) {
var implementation = document.implementation;
hasSVG = (
implementation &&
implementation.hasFeature &&
implementation.hasFeature(
'http://www.w3.org/TR/SVG11/feature#BasicStructure',
'1.1'
)
);
}
var HTMLDOMPropertyConfig = {
isCustomAttribute: RegExp.prototype.test.bind(
/^(data|aria)-[a-z_][a-z\d_.\-]*$/
),
Properties: {
/**
* Standard Properties
*/
accept: null,
acceptCharset: null,
accessKey: null,
action: null,
allowFullScreen: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
allowTransparency: MUST_USE_ATTRIBUTE,
alt: null,
async: HAS_BOOLEAN_VALUE,
autoComplete: null,
// autoFocus is polyfilled/normalized by AutoFocusMixin
// autoFocus: HAS_BOOLEAN_VALUE,
autoPlay: HAS_BOOLEAN_VALUE,
cellPadding: null,
cellSpacing: null,
charSet: MUST_USE_ATTRIBUTE,
checked: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
classID: MUST_USE_ATTRIBUTE,
// To set className on SVG elements, it's necessary to use .setAttribute;
// this works on HTML elements too in all browsers except IE8. Conveniently,
// IE8 doesn't support SVG and so we can simply use the attribute in
// browsers that support SVG and the property in browsers that don't,
// regardless of whether the element is HTML or SVG.
className: hasSVG ? MUST_USE_ATTRIBUTE : MUST_USE_PROPERTY,
cols: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE,
colSpan: null,
content: null,
contentEditable: null,
contextMenu: MUST_USE_ATTRIBUTE,
controls: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
coords: null,
crossOrigin: null,
data: null, // For `<object />` acts as `src`.
dateTime: MUST_USE_ATTRIBUTE,
defer: HAS_BOOLEAN_VALUE,
dir: null,
disabled: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
download: HAS_OVERLOADED_BOOLEAN_VALUE,
draggable: null,
encType: null,
form: MUST_USE_ATTRIBUTE,
formAction: MUST_USE_ATTRIBUTE,
formEncType: MUST_USE_ATTRIBUTE,
formMethod: MUST_USE_ATTRIBUTE,
formNoValidate: HAS_BOOLEAN_VALUE,
formTarget: MUST_USE_ATTRIBUTE,
frameBorder: MUST_USE_ATTRIBUTE,
headers: null,
height: MUST_USE_ATTRIBUTE,
hidden: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
high: null,
href: null,
hrefLang: null,
htmlFor: null,
httpEquiv: null,
icon: null,
id: MUST_USE_PROPERTY,
label: null,
lang: null,
list: MUST_USE_ATTRIBUTE,
loop: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
low: null,
manifest: MUST_USE_ATTRIBUTE,
marginHeight: null,
marginWidth: null,
max: null,
maxLength: MUST_USE_ATTRIBUTE,
media: MUST_USE_ATTRIBUTE,
mediaGroup: null,
method: null,
min: null,
multiple: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
muted: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
name: null,
noValidate: HAS_BOOLEAN_VALUE,
open: HAS_BOOLEAN_VALUE,
optimum: null,
pattern: null,
placeholder: null,
poster: null,
preload: null,
radioGroup: null,
readOnly: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
rel: null,
required: HAS_BOOLEAN_VALUE,
role: MUST_USE_ATTRIBUTE,
rows: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE,
rowSpan: null,
sandbox: null,
scope: null,
scoped: HAS_BOOLEAN_VALUE,
scrolling: null,
seamless: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
selected: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
shape: null,
size: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE,
sizes: MUST_USE_ATTRIBUTE,
span: HAS_POSITIVE_NUMERIC_VALUE,
spellCheck: null,
src: null,
srcDoc: MUST_USE_PROPERTY,
srcSet: MUST_USE_ATTRIBUTE,
start: HAS_NUMERIC_VALUE,
step: null,
style: null,
tabIndex: null,
target: null,
title: null,
type: null,
useMap: null,
value: MUST_USE_PROPERTY | HAS_SIDE_EFFECTS,
width: MUST_USE_ATTRIBUTE,
wmode: MUST_USE_ATTRIBUTE,
/**
* Non-standard Properties
*/
// autoCapitalize and autoCorrect are supported in Mobile Safari for
// keyboard hints.
autoCapitalize: null,
autoCorrect: null,
// itemProp, itemScope, itemType are for
// Microdata support. See http://schema.org/docs/gs.html
itemProp: MUST_USE_ATTRIBUTE,
itemScope: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
itemType: MUST_USE_ATTRIBUTE,
// itemID and itemRef are for Microdata support as well but
// only specified in the the WHATWG spec document. See
// https://html.spec.whatwg.org/multipage/microdata.html#microdata-dom-api
itemID: MUST_USE_ATTRIBUTE,
itemRef: MUST_USE_ATTRIBUTE,
// property is supported for OpenGraph in meta tags.
property: null,
// IE-only attribute that controls focus behavior
unselectable: MUST_USE_ATTRIBUTE
},
DOMAttributeNames: {
acceptCharset: 'accept-charset',
className: 'class',
htmlFor: 'for',
httpEquiv: 'http-equiv'
},
DOMPropertyNames: {
autoCapitalize: 'autocapitalize',
autoComplete: 'autocomplete',
autoCorrect: 'autocorrect',
autoFocus: 'autofocus',
autoPlay: 'autoplay',
// `encoding` is equivalent to `enctype`, IE8 lacks an `enctype` setter.
// http://www.w3.org/TR/html5/forms.html#dom-fs-encoding
encType: 'encoding',
hrefLang: 'hreflang',
radioGroup: 'radiogroup',
spellCheck: 'spellcheck',
srcDoc: 'srcdoc',
srcSet: 'srcset'
}
};
module.exports = HTMLDOMPropertyConfig;
| src/browser/ui/dom/HTMLDOMPropertyConfig.js | /**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule HTMLDOMPropertyConfig
*/
/*jslint bitwise: true*/
'use strict';
var DOMProperty = require('DOMProperty');
var ExecutionEnvironment = require('ExecutionEnvironment');
var MUST_USE_ATTRIBUTE = DOMProperty.injection.MUST_USE_ATTRIBUTE;
var MUST_USE_PROPERTY = DOMProperty.injection.MUST_USE_PROPERTY;
var HAS_BOOLEAN_VALUE = DOMProperty.injection.HAS_BOOLEAN_VALUE;
var HAS_SIDE_EFFECTS = DOMProperty.injection.HAS_SIDE_EFFECTS;
var HAS_NUMERIC_VALUE = DOMProperty.injection.HAS_NUMERIC_VALUE;
var HAS_POSITIVE_NUMERIC_VALUE =
DOMProperty.injection.HAS_POSITIVE_NUMERIC_VALUE;
var HAS_OVERLOADED_BOOLEAN_VALUE =
DOMProperty.injection.HAS_OVERLOADED_BOOLEAN_VALUE;
var hasSVG;
if (ExecutionEnvironment.canUseDOM) {
var implementation = document.implementation;
hasSVG = (
implementation &&
implementation.hasFeature &&
implementation.hasFeature(
'http://www.w3.org/TR/SVG11/feature#BasicStructure',
'1.1'
)
);
}
var HTMLDOMPropertyConfig = {
isCustomAttribute: RegExp.prototype.test.bind(
/^(data|aria)-[a-z_][a-z\d_.\-]*$/
),
Properties: {
/**
* Standard Properties
*/
accept: null,
acceptCharset: null,
accessKey: null,
action: null,
allowFullScreen: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
allowTransparency: MUST_USE_ATTRIBUTE,
alt: null,
async: HAS_BOOLEAN_VALUE,
autoComplete: null,
// autoFocus is polyfilled/normalized by AutoFocusMixin
// autoFocus: HAS_BOOLEAN_VALUE,
autoPlay: HAS_BOOLEAN_VALUE,
cellPadding: null,
cellSpacing: null,
charSet: MUST_USE_ATTRIBUTE,
checked: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
classID: MUST_USE_ATTRIBUTE,
// To set className on SVG elements, it's necessary to use .setAttribute;
// this works on HTML elements too in all browsers except IE8. Conveniently,
// IE8 doesn't support SVG and so we can simply use the attribute in
// browsers that support SVG and the property in browsers that don't,
// regardless of whether the element is HTML or SVG.
className: hasSVG ? MUST_USE_ATTRIBUTE : MUST_USE_PROPERTY,
cols: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE,
colSpan: null,
content: null,
contentEditable: null,
contextMenu: MUST_USE_ATTRIBUTE,
controls: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
coords: null,
crossOrigin: null,
data: null, // For `<object />` acts as `src`.
dateTime: MUST_USE_ATTRIBUTE,
defer: HAS_BOOLEAN_VALUE,
dir: null,
disabled: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
download: HAS_OVERLOADED_BOOLEAN_VALUE,
draggable: null,
encType: null,
form: MUST_USE_ATTRIBUTE,
formAction: MUST_USE_ATTRIBUTE,
formEncType: MUST_USE_ATTRIBUTE,
formMethod: MUST_USE_ATTRIBUTE,
formNoValidate: HAS_BOOLEAN_VALUE,
formTarget: MUST_USE_ATTRIBUTE,
frameBorder: MUST_USE_ATTRIBUTE,
headers: null,
height: MUST_USE_ATTRIBUTE,
hidden: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
high: null,
href: null,
hrefLang: null,
htmlFor: null,
httpEquiv: null,
icon: null,
id: MUST_USE_PROPERTY,
label: null,
lang: null,
list: MUST_USE_ATTRIBUTE,
loop: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
low: null,
manifest: MUST_USE_ATTRIBUTE,
marginHeight: null,
marginWidth: null,
max: null,
maxLength: MUST_USE_ATTRIBUTE,
media: MUST_USE_ATTRIBUTE,
mediaGroup: null,
method: null,
min: null,
multiple: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
muted: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
name: null,
noValidate: HAS_BOOLEAN_VALUE,
open: HAS_BOOLEAN_VALUE,
optimum: null,
pattern: null,
placeholder: null,
poster: null,
preload: null,
radioGroup: null,
readOnly: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
rel: null,
required: HAS_BOOLEAN_VALUE,
role: MUST_USE_ATTRIBUTE,
rows: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE,
rowSpan: null,
sandbox: null,
scope: null,
scoped: HAS_BOOLEAN_VALUE,
scrolling: null,
seamless: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
selected: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
shape: null,
size: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE,
sizes: MUST_USE_ATTRIBUTE,
span: HAS_POSITIVE_NUMERIC_VALUE,
spellCheck: null,
src: null,
srcDoc: MUST_USE_PROPERTY,
srcSet: MUST_USE_ATTRIBUTE,
start: HAS_NUMERIC_VALUE,
step: null,
style: null,
tabIndex: null,
target: null,
title: null,
type: null,
useMap: null,
value: MUST_USE_PROPERTY | HAS_SIDE_EFFECTS,
width: MUST_USE_ATTRIBUTE,
wmode: MUST_USE_ATTRIBUTE,
/**
* Non-standard Properties
*/
// autoCapitalize and autoCorrect are supported in Mobile Safari for
// keyboard hints.
autoCapitalize: null,
autoCorrect: null,
// itemProp, itemScope, itemType are for
// Microdata support. See http://schema.org/docs/gs.html
itemProp: MUST_USE_ATTRIBUTE,
itemScope: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
itemType: MUST_USE_ATTRIBUTE,
// itemID and itemRef are for Microdata support as well but
// only specified in the the WHATWG spec document. See
// https://html.spec.whatwg.org/multipage/microdata.html#microdata-dom-api
itemID: MUST_USE_ATTRIBUTE,
itemRef: MUST_USE_ATTRIBUTE,
// property is supported for OpenGraph in meta tags.
property: null,
// IE-only attribute that controls focus behavior
unselectable: MUST_USE_ATTRIBUTE,
webkitdirectory: null,
nwdirectory: null
},
DOMAttributeNames: {
acceptCharset: 'accept-charset',
className: 'class',
htmlFor: 'for',
httpEquiv: 'http-equiv'
},
DOMPropertyNames: {
autoCapitalize: 'autocapitalize',
autoComplete: 'autocomplete',
autoCorrect: 'autocorrect',
autoFocus: 'autofocus',
autoPlay: 'autoplay',
// `encoding` is equivalent to `enctype`, IE8 lacks an `enctype` setter.
// http://www.w3.org/TR/html5/forms.html#dom-fs-encoding
encType: 'encoding',
hrefLang: 'hreflang',
radioGroup: 'radiogroup',
spellCheck: 'spellcheck',
srcDoc: 'srcdoc',
srcSet: 'srcset'
}
};
module.exports = HTMLDOMPropertyConfig;
| Revert "Add webkitdirectory and nwdirectory attributes for input file"
| src/browser/ui/dom/HTMLDOMPropertyConfig.js | Revert "Add webkitdirectory and nwdirectory attributes for input file" | <ide><path>rc/browser/ui/dom/HTMLDOMPropertyConfig.js
<ide> // property is supported for OpenGraph in meta tags.
<ide> property: null,
<ide> // IE-only attribute that controls focus behavior
<del> unselectable: MUST_USE_ATTRIBUTE,
<del> webkitdirectory: null,
<del> nwdirectory: null
<add> unselectable: MUST_USE_ATTRIBUTE
<ide> },
<ide> DOMAttributeNames: {
<ide> acceptCharset: 'accept-charset', |
|
Java | mit | ca241aeb22a602a2badad941d475049d6ba6414f | 0 | vicklagad/elevator-java | package kuali.poc;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeSet;
/** The main elevator class **/
public class Elevator {
//any change in relevant properties of this elevator should
//trigger an event on its listener
private List<PropertyChangeListener> listeners = new ArrayList<PropertyChangeListener>();
private int currentFloor; //current floor this elevator is on
public static enum ElevatorStatus {
UNDER_MAINTENANCE, MOVING_UP, MOVING_DOWN, IDLE
};
public static enum DoorStatus {
OPEN, CLOSED
}
private Elevator.ElevatorStatus status;
private Elevator.DoorStatus doorStatus;
private static final int STUB_WAIT_TIME = 1000; //some wait time for tests
private int maxCapacity; //max weight it can hold
private int tripCount;
private int floorsPassed;
private int maxFloors;
private TreeSet<Integer> currentFloorsToReach;
public Elevator(int currentFloor, int maxFloors) {
this.status = Elevator.ElevatorStatus.IDLE;
this.currentFloor = currentFloor;
this.doorStatus = Elevator.DoorStatus.CLOSED;
this.maxFloors = maxFloors;
this.currentFloorsToReach = new TreeSet<Integer>();
}
public void addFloorToService(int floor) {
this.currentFloorsToReach.add(floor);
}
private void checkCurrentState() {
//check current state of itself
if (this.currentFloor == this.currentFloorsToReach.first()) {
this.currentFloorsToReach.remove(currentFloorsToReach.first());
openDoor();
closeDoor();
if (this.currentFloorsToReach.size()==0) {
//no more requests to serve, trip over
addTripsMade();
if (this.tripCount >=100) {
//too many trips.. maintenance now
this.status = ElevatorStatus.UNDER_MAINTENANCE;
} else {
//ready to serve
this.status = ElevatorStatus.IDLE;
}
}
}
if (this.currentFloor < this.currentFloorsToReach.first()) {
//elevator is under the requested floor
try {
moveUp(); //move it up
} catch (Exception e) {
// TODO Handle exceptions
e.printStackTrace();
}
}
if (this.currentFloor > this.currentFloorsToReach.first()) {
//elevator is above the requested floor
try {
moveDown(); //move it down
} catch (Exception e) {
// TODO Handle exceptions
e.printStackTrace();
}
}
}
private void addFloorsVisited() {
this.floorsPassed ++;
}
private void addTripsMade() {
this.tripCount++;
}
public void moveUp() throws Exception {
try {
if (this.currentFloor >= this.maxFloors) {
throw new IllegalStateException("Elevator cannot go up. It is at the top most floor");
}
Thread.sleep(Elevator.STUB_WAIT_TIME);
checkCurrentState(); //check own current state
synchronized (this){
this.status = Elevator.ElevatorStatus.MOVING_UP;
this.currentFloor++;
notifyListeners(this, Constants.ELEVATOR_EVT_FLOOR_CHANGED,
String.valueOf(this.currentFloor + 1),
String.valueOf(currentFloor)); //elevator floor changed event fired
}
} catch (InterruptedException e) {
throw new Exception("Thread wait issue.");
}
}
public void moveDown() throws Exception {
try {
if (this.currentFloor <= 1) {
throw new IllegalStateException("Elevator cannot go down. It is at the bottom most floor");
}
Thread.sleep(Elevator.STUB_WAIT_TIME);
checkCurrentState(); //check own current state
synchronized (this){
this.status = Elevator.ElevatorStatus.MOVING_DOWN;
this.currentFloor--;
notifyListeners(this, Constants.ELEVATOR_EVT_FLOOR_CHANGED,
String.valueOf(this.currentFloor - 1),
String.valueOf(currentFloor)); //todo: refactoring needed
}
} catch (InterruptedException e) {
throw new Exception("Thread wait issue.");
}
}
// public abstract void decomission();
// public abstract void stop();
// public abstract void start();
public void openDoor() {
System.out.println("Open doors for people to get out..");
try {
notifyListeners(this, Constants.DOOR_EVT_OPENED,
"",
""); //event itself is self explanatory. no need for old and new values
Thread.sleep(Elevator.STUB_WAIT_TIME);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void closeDoor() {
System.out.println("Closing doors");
try {
Thread.sleep(Elevator.STUB_WAIT_TIME);
notifyListeners(this, Constants.DOOR_EVT_CLOSED,
"",
""); //event itself is self explanatory. no need for old and new values
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// public abstract void closeDoor();
//
private void notifyListeners(Object object, String property, String oldValue, String newValue) {
for (PropertyChangeListener listener : listeners) {
listener.propertyChange(new PropertyChangeEvent(this, property, oldValue, newValue));
}
}
public void addChangeListener(PropertyChangeListener newListener) {
listeners.add(newListener);
}
public int getCurrentFloor() {
return currentFloor;
}
public Elevator.ElevatorStatus getStatus() {
return status;
}
public Elevator.DoorStatus getDoorStatus() {
return doorStatus;
}
public int getMaxCapacity() {
return maxCapacity;
}
public void setMaxCapacity(int maxCapacity) {
this.maxCapacity = maxCapacity;
}
public int getTripCount() {
return tripCount;
}
public int getFloorsPassed() {
return floorsPassed;
}
}
| src/main/java/kuali/poc/Elevator.java | package kuali.poc;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
/** The main elevator class **/
public class Elevator {
//any change in relevant properties of this elevator should
//trigger an event on its listener
private List<PropertyChangeListener> listeners = new ArrayList<PropertyChangeListener>();
private int currentFloor; //current floor this elevator is on
public static enum ElevatorStatus {
UNDER_MAINTENANCE, MOVING_UP, MOVING_DOWN, IDLE
};
public static enum DoorStatus {
OPEN, CLOSED
}
private Elevator.ElevatorStatus status;
private Elevator.DoorStatus doorStatus;
private static final int STUB_WAIT_TIME = 1000; //some wait time for tests
private int maxCapacity; //max weight it can hold
private int tripCount;
private int floorsPassed;
private int maxFloors;
private TreeSet<Integer> currentFloorsToReach;
public Elevator(int currentFloor, int maxFloors) {
this.status = Elevator.ElevatorStatus.IDLE;
this.currentFloor = currentFloor;
this.doorStatus = Elevator.DoorStatus.CLOSED;
this.maxFloors = maxFloors;
this.currentFloorsToReach = new TreeSet<Integer>();
}
public void addFloorToService(int floor) {
this.currentFloorsToReach.add(floor);
}
private void checkCurrentState() {
//check current state of itself
if (this.currentFloor == this.currentFloorsToReach.first()) {
this.currentFloorsToReach.remove(currentFloorsToReach.first());
openDoor();
closeDoor();
if (this.currentFloorsToReach.size()==0) {
//no more requests to serve, trip over
addTripsMade();
if (this.tripCount >=100) {
//too many trips.. maintenance now
this.status = ElevatorStatus.UNDER_MAINTENANCE;
} else {
//ready to serve
this.status = ElevatorStatus.IDLE;
}
}
}
if (this.currentFloor < this.currentFloorsToReach.first()) {
//elevator is under the requested floor
try {
moveUp(); //move it up
} catch (Exception e) {
// TODO Handle exceptions
e.printStackTrace();
}
}
if (this.currentFloor > this.currentFloorsToReach.first()) {
//elevator is above the requested floor
try {
moveDown(); //move it down
} catch (Exception e) {
// TODO Handle exceptions
e.printStackTrace();
}
}
}
private void addFloorsVisited() {
this.floorsPassed ++;
}
private void addTripsMade() {
this.tripCount++;
}
public void moveUp() throws Exception {
try {
if (this.currentFloor >= this.maxFloors) {
throw new IllegalStateException("Elevator cannot go up. It is at the top most floor");
}
Thread.sleep(Elevator.STUB_WAIT_TIME);
checkCurrentState(); //check own current state
synchronized (this){
this.status = Elevator.ElevatorStatus.MOVING_UP;
this.currentFloor++;
notifyListeners(this, Constants.ELEVATOR_EVT_FLOOR_CHANGED,
String.valueOf(this.currentFloor + 1),
String.valueOf(currentFloor)); //elevator floor changed event fired
}
} catch (InterruptedException e) {
throw new Exception("Thread wait issue.");
}
}
public void moveDown() throws Exception {
try {
if (this.currentFloor <= 1) {
throw new IllegalStateException("Elevator cannot go down. It is at the bottom most floor");
}
Thread.sleep(Elevator.STUB_WAIT_TIME);
checkCurrentState(); //check own current state
synchronized (this){
this.status = Elevator.ElevatorStatus.MOVING_DOWN;
this.currentFloor--;
notifyListeners(this, Constants.ELEVATOR_EVT_FLOOR_CHANGED,
String.valueOf(this.currentFloor - 1),
String.valueOf(currentFloor)); //todo: refactoring needed
}
} catch (InterruptedException e) {
throw new Exception("Thread wait issue.");
}
}
// public abstract void decomission();
// public abstract void stop();
// public abstract void start();
public void openDoor() {
System.out.println("Open doors for people to get out..");
try {
notifyListeners(this, Constants.DOOR_EVT_OPENED,
"",
""); //event itself is self explanatory. no need for old and new values
Thread.sleep(Elevator.STUB_WAIT_TIME);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void closeDoor() {
System.out.println("Closing doors");
try {
Thread.sleep(Elevator.STUB_WAIT_TIME);
notifyListeners(this, Constants.DOOR_EVT_CLOSED,
"",
""); //event itself is self explanatory. no need for old and new values
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// public abstract void closeDoor();
//
private void notifyListeners(Object object, String property, String oldValue, String newValue) {
for (PropertyChangeListener listener : listeners) {
listener.propertyChange(new PropertyChangeEvent(this, property, oldValue, newValue));
}
}
public void addChangeListener(PropertyChangeListener newListener) {
listeners.add(newListener);
}
public int getCurrentFloor() {
return currentFloor;
}
public Elevator.ElevatorStatus getStatus() {
return status;
}
public Elevator.DoorStatus getDoorStatus() {
return doorStatus;
}
public int getMaxCapacity() {
return maxCapacity;
}
public void setMaxCapacity(int maxCapacity) {
this.maxCapacity = maxCapacity;
}
public int getTripCount() {
return tripCount;
}
public int getFloorsPassed() {
return floorsPassed;
}
}
| Restarting work..
| src/main/java/kuali/poc/Elevator.java | Restarting work.. | <ide><path>rc/main/java/kuali/poc/Elevator.java
<ide> import java.beans.PropertyChangeListener;
<ide> import java.util.ArrayList;
<ide> import java.util.List;
<del>import java.util.Set;
<ide> import java.util.TreeSet;
<ide>
<ide> /** The main elevator class **/ |
|
Java | apache-2.0 | b472de108dd4bde57a511bdb170dc19c84f056c5 | 0 | mbezjak/vhdllab,mbezjak/vhdllab,mbezjak/vhdllab | /*******************************************************************************
* See the NOTICE file distributed with this work for additional information
* regarding copyright ownership.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package hr.fer.zemris.vhdllab.applets.simulations;
import java.awt.Dimension;
import java.awt.Graphics;
import java.util.Arrays;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
/**
* Skala uzima vrijednosti koje generira VcdParser i vrsi sve proracune kod
* event-hendlanja. Prilikom svakog povecanja proracunava trajanje valnih
* oblika u pikselima.
*
* @author Boris Ozegovic
*/
class Scale extends JPanel
{
/**
* Konstanta s kojom se mnozi trenutne vrijednosti ako je mjerna jedinica u
* femto sekundama
*/
private static final byte FEMTO_SECONDS = 1;
/**
* Konstanta s kojom se mnozi trenutne vrijednosti ako je mjerna jedinica u
* pico sekundama
*/
private static final double PICO_SECONDS = 1e-3;
/**
* Konstanta s kojom se mnozi trenutne vrijednosti ako je mjerna jedinica u
* nano sekundama
*/
private static final double NANO_SECONDS = 1e-6;
/**
* Konstanta s kojom se mnozi trenutne vrijednosti ako je mjerna jedinica u
* micro sekundama
*/
private static final double MICRO_SECONDS = 1e-9;
/**
* Konstanta s kojom se mnozi trenutne vrijednosti ako je mjerna jedinica u
* mili sekundama
*/
private static final double MILI_SECONDS = 1e-12;
/**
* Konstanta s kojom se mnozi trenutne vrijednosti ako je mjerna jedinica u
* sekundama
*/
private static final double SECONDS = 1e-15;
/** Razmak izmedu dvije tocke na skali je uvijek 100 piksela */
private static final int SCALE_STEP_IN_PIXELS = 100;
/** Visina skale */
private static final int SCALE_HEIGHT = 30;
/** Piksel na kojem pocinje iscrtavanje skale */
private static int SCALE_START_POINT_IN_PIXELS = 0;
/** Svaki vrijednost na skali pocinje od 19. piksela */
private static final int SCALE_VALUE_YAXIS = 19;
/** Os pocinje od 4. piksela */
private static final int SCALE_MAIN_LINE_YAXIS = 4;
/** Svaka crtica pocinje od 2. piksela */
private static final int SCALE_TAG_LINE_YSTART = 2;
/** Svaka crtica zavrsava na 6. pikselu */
private static final int SCALE_TAG_LINE_YEND = 6;
/** Tocke u kojima nastaju promjene vrijednosti signala */
private long[] transitionPoints;
/** GHDL simulator generira sve u femtosekundama */
private double[] durationsInFemtoSeconds;
/** Trajanje pojedenih intervala u vremenskoj jedinici */
private int[] durationsInTime;
/** Trajanje u pikselima koje id direktno za crtanje valnih oblika */
private int[] durationsInPixels;
/** Minimalna vrijednost trajanja signala izemdu dvije promjene */
private int minimumDurationInTime;
/** Povecava/smanjuje skalu za neku vrijednost */
private double scaleFactor = 1f;
/** Povecava/smanjuje time/pixel faktor */
private double pixelFactor;
/** Ime mjerne jedinice */
private String measureUnitName;
/** Mjerna jedinica */
private double measureUnit;
/** U pikselima - odreduje tocno odredeni piksel na kojem skala zavrsava */
private int scaleEndPointInPixels;
/** Korak skale u vremenu, ovisno o scaleFactor */
private double scaleStepInTime;
/** Vrijednost koja se kumulativno povecava, ovisno o scaleStepInTime */
private double scaleValue;
/**
* Ovisno o trenutnom offsetu scrollbara. Ako je offset npr. 1350, onda se
* interno preracuna u 1300 i od 1300 se crta skala
*/
private int screenStartPointInPixels;
/**
* Podrazumijevana velicina ekrana - skale ne iscrtava automatski sve
* vrijednost vec vrsi proracuna na temelju offseta i iscrtava samo trenutnu
* velicinu komponente
*/
private int screenSizeInPixels;
/** ScreenStartPointInPixels + trenutna duljina komponente */
private int screenEndPointInPixels;
/** Sve podrzane mjerne jedinice **/
private final String[] units = {"fs", "ps", "ns", "us", "ms", "s", "ks", "ms"};
/** Offset trenutni */
private int offsetXAxis;
/** Horizontalni scrollbar */
private JScrollBar horizontalScrollbar;
/** Boje */
private ThemeColor themeColor;
/** SerialVersionUID */
private static final long serialVersionUID = -4934785363261778378L;
/**
* Constructor
*
* @param horizontalScrollbar horizontalni scrollbar
* @param themeColor trneutna tema
*/
public Scale (JScrollBar horizontalScrollbar, ThemeColor themeColor)
{
this.themeColor = themeColor;
this.horizontalScrollbar = horizontalScrollbar;
}
/**
* Metoda postavlja novu vrijednosti skale, u ovisnosti o rezultatu kojeg je
* parsirao GHDLResults
*
* @param results rezultati koje je parsirao GhldResults
*/
public void setContent(GhdlResults results) {
this.transitionPoints = results.getTransitionPoints();
durationsInFemtoSeconds = new double[transitionPoints.length - 1];
durationsInTime = new int[durationsInFemtoSeconds.length];
durationsInPixels = new int[durationsInFemtoSeconds.length];
for (int i = 0; i < durationsInFemtoSeconds.length; i++)
{
double operand1 = transitionPoints[i + 1];
double operand2 = transitionPoints[i];
durationsInFemtoSeconds[i] = operand1 - operand2;
}
// fix for http://morgoth.zemris.fer.hr/trac/vhdllab/ticket/39
if (Arrays.equals(durationsInFemtoSeconds, new double[] {0.0})) {
durationsInFemtoSeconds[0] = 1.0;
}
/* crta pocetne valne oblike sa scaleFaktorom 1 */
drawDefaultWave();
}
/**
* Metoda koja crta pocetne oblike
*/
public void drawDefaultWave ()
{
/* radi lokalnu kopiju jer sortiranje mijenja poredak */
double[] temporaryDurations = durationsInFemtoSeconds.clone();
Arrays.sort(temporaryDurations);
/*
* nakon sortiranja minimalno se trajanje nalazi na prvom mjestu u polju
* i na temelju tog minimalnog trajanja odreduje pocetnu jedinicu (ns,
* ps, itd). Castanje zbog toga da ne produ znamenke iza dec. zareza.
* Pomocu string.length() izracunava broj znamenki i na temelju broj
* znamenki odreduje mjernu jedinicu. Odreduje se najmanja promjena, te
* se na temelju nje postavlja skala u najmanju jedinicu i mnozi ostatak s
* odgovarajucim 10^x faktorom.
* */
String minimumDuration = String.valueOf((long)temporaryDurations[0]);
//System.out.println("minimalna razlika je " + minimumDuration);
int numberOfEndZeroes = 0;
char[] tempArray = minimumDuration.toCharArray();
for (int i = tempArray.length - 1; i >= 0; i--) {
if (tempArray[i] == '0') {
numberOfEndZeroes++;
} else {
break;
}
}
switch (numberOfEndZeroes)
{
case 0 :
case 1 :
case 2 :
measureUnitName = "fs";
measureUnit = FEMTO_SECONDS;
break;
case 3 :
case 4 :
case 5 :
measureUnitName = "ps";
measureUnit = PICO_SECONDS;
break;
case 6 :
case 7 :
case 8 :
measureUnitName = "ns";
measureUnit = NANO_SECONDS;
break;
case 9 :
case 10 :
case 11 :
measureUnitName = "us";
measureUnit = MICRO_SECONDS;
break;
case 12 :
case 13 :
case 14 :
measureUnitName = "ms";
measureUnit = MILI_SECONDS;
break;
case 15 :
case 16 :
case 17 :
measureUnitName = "s";
measureUnit = SECONDS;
break;
}
scaleEndPointInPixels = 0;
minimumDurationInTime = (int)(durationsInFemtoSeconds[0] * measureUnit);
for (int i = 0; i < durationsInTime.length; i++)
{
durationsInTime[i] = (int)(durationsInFemtoSeconds[i] * measureUnit);
if (durationsInTime[i] < minimumDurationInTime) {
minimumDurationInTime = durationsInTime[i];
}
scaleEndPointInPixels += durationsInTime[i];
}
scaleStepInTime = minimumDurationInTime;
pixelFactor = 100 / scaleStepInTime;
scaleEndPointInPixels *= pixelFactor;
for (int i = 0; i < transitionPoints.length; i++) {
transitionPoints[i] = (int)(transitionPoints[i] * measureUnit);
}
// izracunaj durationsInPixels
for (int j = 0; j < durationsInPixels.length; j++) {
durationsInPixels[j] = (int)(transitionPoints[j + 1] * pixelFactor) -
(int)(transitionPoints[j] * pixelFactor);
}
}
/**
* Metoda koja se brine o trajanju piksela nakon event-hendlanja i o tocnom
* postavljanju scaleEndPointInPixels
*/
public void setDurationsInPixelsAfterZoom (double scaleFactor)
{
scaleStepInTime /= scaleFactor;
pixelFactor *= scaleFactor;
scaleEndPointInPixels = 0;
for (int i = 0; i < durationsInTime.length; i++)
{
/* s istim 10^x faktorom mnozi se cijelo vrijeme */
durationsInTime[i] = (int)(durationsInFemtoSeconds[i] * measureUnit);
scaleEndPointInPixels += durationsInTime[i];
}
scaleEndPointInPixels *= pixelFactor;
// izracunaj durationsInPixels
for (int i = 0; i < durationsInPixels.length; i++) {
durationsInPixels[i] = (int)(transitionPoints[i + 1] * pixelFactor) -
(int)(transitionPoints[i] * pixelFactor);
}
this.scaleFactor *= scaleFactor;
}
/**
* Getter trajanje u pikselima za valne oblike
*/
public int[] getDurationInPixels()
{
return durationsInPixels;
}
/**
* Setter postavlja scaleFactor
*
* @param scaleFactor Zeljeni faktor
*/
public void setScaleFactor (float scaleFactor)
{
this.scaleFactor = scaleFactor;
}
/**
* Vraca trenutni scale faktor
*/
public double getScaleFactor ()
{
return scaleFactor;
}
/**
* Getter koji je potreban event-hendleru za precizno oznacavanje pozicije
*/
public String getMeasureUnitName ()
{
return measureUnitName;
}
/**
* Setter koji postavlja horizontalni offset u ovisnosti i scrollbaru
*
* @param offset Zeljeni offset
*/
public void setHorizontalOffset (int offset)
{
this.offsetXAxis = offset;
}
/**
* Trenutni horizontalni offset
*/
public int getHorizontalOffset ()
{
return offsetXAxis;
}
/**
* Getter koji daje krajnju tocku u pikselima, potreban za postavljanje nove
* vrijednosti scrollbara prilikom povecanja/smanjenja
*/
public int getScaleEndPointInPixels ()
{
return scaleEndPointInPixels;
}
/**
* Getter koji daje trenutnu vrijednost skale u vremenu (npr. 345 ns na 100
* piksela)
*/
public double getScaleStepInTime ()
{
return scaleStepInTime;
}
/**
* Preferirane dimenzije
*/
@Override
public Dimension getPreferredSize ()
{
return new Dimension(scaleEndPointInPixels, SCALE_HEIGHT);
}
/**
* Zumiraj tako da sve stane u jedan prozor
*/
public void fitToWindow() {
scaleFactor = (double)800 / scaleEndPointInPixels;
setDurationsInPixelsAfterZoom(scaleFactor);
}
/**
* Metoda vraca u defaultno stanje
*/
public void unfitToWindow() {
scaleFactor = 1;
scaleStepInTime = minimumDurationInTime;
pixelFactor = 100 / scaleStepInTime;
scaleEndPointInPixels *= pixelFactor;
setDurationsInPixelsAfterZoom(scaleFactor);
// System.out.println("da");
}
/**
* Crtanje komponente
*/
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
setBackground(themeColor.getScale());
g.setColor(themeColor.getLetters());
/* postavlja novu vrijednost scrollbara */
int horizontalValue = this.scaleEndPointInPixels -
this.getWidth() + 45;
if (horizontalValue >= 0) {
horizontalScrollbar.setMaximum(horizontalValue);
}
/*
* Bilo koja vrijednost postavlja se na visekratnik broja 100. Znaci, ako je
* offset bio 1450, stavit ce 1400 i poceti crtati od 1400
*/
screenStartPointInPixels = offsetXAxis - offsetXAxis % 100;
/*
* Duljina trenutno aktivnog ekrana koji ce se iscrtati je duljina panela + 200
* Skala se ne crta kompletno, vec samo dio koji trenutno upada u offset
*/
screenSizeInPixels = getWidth() + 200;
screenEndPointInPixels = screenStartPointInPixels + screenSizeInPixels;
scaleFactor = Math.round(scaleFactor * 1e13d) / 1e13d;
/* scaleStepInTime ostaje fiksan jer je potrebna pocetna vrijednost */
double tempScaleStepInTime = scaleStepInTime;
/* x se mijenja u koracima od 100 piksela */
int x = 0;
/*
* samo ako je screenStartPointInPixels == 0 npr offset = 30, crta od
* nultog piksela, ali pomatnut ulijevo za offset, pa 30 pocinje od
* nultog piksela
*/
if (screenStartPointInPixels == SCALE_START_POINT_IN_PIXELS)
{
g.drawLine(x - offsetXAxis, SCALE_TAG_LINE_YSTART, x - offsetXAxis,
SCALE_TAG_LINE_YEND);
g.drawString("0", x - offsetXAxis, SCALE_VALUE_YAXIS);
x = SCALE_STEP_IN_PIXELS;
scaleValue = scaleStepInTime;
}
/*
* inace moze biti npr. 2500. scaleValue se odmah postavlja na pocetnu
* vrijednost u skladu s brojem od kojeg pocinje crtanje
*/
else
{
x = screenStartPointInPixels;
scaleValue = screenStartPointInPixels / 100 * scaleStepInTime;
}
int endPoint = screenEndPointInPixels;
g.drawLine(screenStartPointInPixels - offsetXAxis, SCALE_MAIN_LINE_YAXIS,
endPoint - offsetXAxis, SCALE_MAIN_LINE_YAXIS);
String tempMeasureUnitName = measureUnitName;
int endPointInPixels = endPoint;
double potention = 1;
while (x < endPointInPixels)
{
/* svaka se vrijednost zaokruzuje na 10 decimala */
scaleValue = Math.round(scaleValue * 1e13d) / 1e13d;
/*
* ako vrijednost prijede 1000, prebacuje se na sljedecu vecu
* jedinicu i ujedno smanjuje scaleStepInTime za 1000
*/
if (scaleValue >= 1000)
{
for (int i = 0; i < units.length; i++)
{
if (units[i].equals(tempMeasureUnitName) && i < units.length - 1)
{
tempMeasureUnitName = units[i + 1];
scaleValue /= 1000.0;
tempScaleStepInTime /= 1000;
potention *= 1000;
break;
}
}
}
/* inace ako prijede u manju jedinicu */
else if (scaleValue < 1 && scaleValue != 0)
{
for (int i = 0; i < units.length; i++)
{
if (units[i].equals(tempMeasureUnitName) && i > 0)
{
tempMeasureUnitName = units[i - 1];
scaleValue *= 1000;
tempScaleStepInTime *= 1000;
potention /= 1000;
break;
}
}
}
/*
* bez obzira na vrijednost x, sve se crta pomaknuto za offset, tako
* da na ekranu bude slika od nultog piksela
*/
g.drawLine(x - offsetXAxis, SCALE_TAG_LINE_YSTART,
x - offsetXAxis, SCALE_TAG_LINE_YEND);
g.drawString((Math.round(scaleValue * 1000000d) / 1000000.0d)
+ tempMeasureUnitName,
x -(((Math.round(scaleValue * 1000000d) / 1000000.0d)
+ tempMeasureUnitName).length() * 5) / 2
- offsetXAxis, SCALE_VALUE_YAXIS);
scaleValue += tempScaleStepInTime;
// System.out.println("pixelFactor " + pixelFactor);
// System.out.println("potention " + potention);
x = (int)(scaleValue * potention * pixelFactor);
}
}
}
| vhdllab-client/src/main/java/hr/fer/zemris/vhdllab/applets/simulations/Scale.java | /*******************************************************************************
* See the NOTICE file distributed with this work for additional information
* regarding copyright ownership.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package hr.fer.zemris.vhdllab.applets.simulations;
import java.awt.Dimension;
import java.awt.Graphics;
import java.util.Arrays;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
/**
* Skala uzima vrijednosti koje generira VcdParser i vrsi sve proracune kod
* event-hendlanja. Prilikom svakog povecanja proracunava trajanje valnih
* oblika u pikselima.
*
* @author Boris Ozegovic
*/
class Scale extends JPanel
{
/**
* Konstanta s kojom se mnozi trenutne vrijednosti ako je mjerna jedinica u
* femto sekundama
*/
private static final byte FEMTO_SECONDS = 1;
/**
* Konstanta s kojom se mnozi trenutne vrijednosti ako je mjerna jedinica u
* pico sekundama
*/
private static final double PICO_SECONDS = 1e-3;
/**
* Konstanta s kojom se mnozi trenutne vrijednosti ako je mjerna jedinica u
* nano sekundama
*/
private static final double NANO_SECONDS = 1e-6;
/**
* Konstanta s kojom se mnozi trenutne vrijednosti ako je mjerna jedinica u
* micro sekundama
*/
private static final double MICRO_SECONDS = 1e-9;
/**
* Konstanta s kojom se mnozi trenutne vrijednosti ako je mjerna jedinica u
* mili sekundama
*/
private static final double MILI_SECONDS = 1e-12;
/**
* Konstanta s kojom se mnozi trenutne vrijednosti ako je mjerna jedinica u
* sekundama
*/
private static final double SECONDS = 1e-15;
/** Razmak izmedu dvije tocke na skali je uvijek 100 piksela */
private static final int SCALE_STEP_IN_PIXELS = 100;
/** Visina skale */
private static final int SCALE_HEIGHT = 30;
/** Piksel na kojem pocinje iscrtavanje skale */
private static int SCALE_START_POINT_IN_PIXELS = 0;
/** Svaki vrijednost na skali pocinje od 19. piksela */
private static final int SCALE_VALUE_YAXIS = 19;
/** Os pocinje od 4. piksela */
private static final int SCALE_MAIN_LINE_YAXIS = 4;
/** Svaka crtica pocinje od 2. piksela */
private static final int SCALE_TAG_LINE_YSTART = 2;
/** Svaka crtica zavrsava na 6. pikselu */
private static final int SCALE_TAG_LINE_YEND = 6;
/** Tocke u kojima nastaju promjene vrijednosti signala */
private long[] transitionPoints;
/** GHDL simulator generira sve u femtosekundama */
private double[] durationsInFemtoSeconds;
/** Trajanje pojedenih intervala u vremenskoj jedinici */
private int[] durationsInTime;
/** Trajanje u pikselima koje id direktno za crtanje valnih oblika */
private int[] durationsInPixels;
/** Minimalna vrijednost trajanja signala izemdu dvije promjene */
private int minimumDurationInTime;
/** Povecava/smanjuje skalu za neku vrijednost */
private double scaleFactor = 1f;
/** Povecava/smanjuje time/pixel faktor */
private double pixelFactor;
/** Ime mjerne jedinice */
private String measureUnitName;
/** Mjerna jedinica */
private double measureUnit;
/** U pikselima - odreduje tocno odredeni piksel na kojem skala zavrsava */
private int scaleEndPointInPixels;
/** Korak skale u vremenu, ovisno o scaleFactor */
private double scaleStepInTime;
/** Vrijednost koja se kumulativno povecava, ovisno o scaleStepInTime */
private double scaleValue;
/**
* Ovisno o trenutnom offsetu scrollbara. Ako je offset npr. 1350, onda se
* interno preracuna u 1300 i od 1300 se crta skala
*/
private int screenStartPointInPixels;
/**
* Podrazumijevana velicina ekrana - skale ne iscrtava automatski sve
* vrijednost vec vrsi proracuna na temelju offseta i iscrtava samo trenutnu
* velicinu komponente
*/
private int screenSizeInPixels;
/** ScreenStartPointInPixels + trenutna duljina komponente */
private int screenEndPointInPixels;
/** Sve podrzane mjerne jedinice **/
private final String[] units = {"fs", "ps", "ns", "us", "ms", "s", "ks", "ms"};
/** Offset trenutni */
private int offsetXAxis;
/** Horizontalni scrollbar */
private JScrollBar horizontalScrollbar;
/** Boje */
private ThemeColor themeColor;
/** SerialVersionUID */
private static final long serialVersionUID = -4934785363261778378L;
/**
* Constructor
*
* @param horizontalScrollbar horizontalni scrollbar
* @param themeColor trneutna tema
*/
public Scale (JScrollBar horizontalScrollbar, ThemeColor themeColor)
{
this.themeColor = themeColor;
this.horizontalScrollbar = horizontalScrollbar;
}
/**
* Metoda postavlja novu vrijednosti skale, u ovisnosti o rezultatu kojeg je
* parsirao GHDLResults
*
* @param results rezultati koje je parsirao GhldResults
*/
public void setContent(GhdlResults results) {
this.transitionPoints = results.getTransitionPoints();
durationsInFemtoSeconds = new double[transitionPoints.length - 1];
durationsInTime = new int[durationsInFemtoSeconds.length];
durationsInPixels = new int[durationsInFemtoSeconds.length];
for (int i = 0; i < durationsInFemtoSeconds.length; i++)
{
double operand1 = transitionPoints[i + 1];
double operand2 = transitionPoints[i];
durationsInFemtoSeconds[i] = operand1 - operand2;
}
/* crta pocetne valne oblike sa scaleFaktorom 1 */
drawDefaultWave();
}
/**
* Metoda koja crta pocetne oblike
*/
public void drawDefaultWave ()
{
/* radi lokalnu kopiju jer sortiranje mijenja poredak */
double[] temporaryDurations = durationsInFemtoSeconds.clone();
Arrays.sort(temporaryDurations);
/*
* nakon sortiranja minimalno se trajanje nalazi na prvom mjestu u polju
* i na temelju tog minimalnog trajanja odreduje pocetnu jedinicu (ns,
* ps, itd). Castanje zbog toga da ne produ znamenke iza dec. zareza.
* Pomocu string.length() izracunava broj znamenki i na temelju broj
* znamenki odreduje mjernu jedinicu. Odreduje se najmanja promjena, te
* se na temelju nje postavlja skala u najmanju jedinicu i mnozi ostatak s
* odgovarajucim 10^x faktorom.
* */
String minimumDuration = String.valueOf((long)temporaryDurations[0]);
//System.out.println("minimalna razlika je " + minimumDuration);
int numberOfEndZeroes = 0;
char[] tempArray = minimumDuration.toCharArray();
for (int i = tempArray.length - 1; i >= 0; i--) {
if (tempArray[i] == '0') {
numberOfEndZeroes++;
} else {
break;
}
}
switch (numberOfEndZeroes)
{
case 0 :
case 1 :
case 2 :
measureUnitName = "fs";
measureUnit = FEMTO_SECONDS;
break;
case 3 :
case 4 :
case 5 :
measureUnitName = "ps";
measureUnit = PICO_SECONDS;
break;
case 6 :
case 7 :
case 8 :
measureUnitName = "ns";
measureUnit = NANO_SECONDS;
break;
case 9 :
case 10 :
case 11 :
measureUnitName = "us";
measureUnit = MICRO_SECONDS;
break;
case 12 :
case 13 :
case 14 :
measureUnitName = "ms";
measureUnit = MILI_SECONDS;
break;
case 15 :
case 16 :
case 17 :
measureUnitName = "s";
measureUnit = SECONDS;
break;
}
scaleEndPointInPixels = 0;
minimumDurationInTime = (int)(durationsInFemtoSeconds[0] * measureUnit);
for (int i = 0; i < durationsInTime.length; i++)
{
durationsInTime[i] = (int)(durationsInFemtoSeconds[i] * measureUnit);
if (durationsInTime[i] < minimumDurationInTime) {
minimumDurationInTime = durationsInTime[i];
}
scaleEndPointInPixels += durationsInTime[i];
}
scaleStepInTime = minimumDurationInTime;
pixelFactor = 100 / scaleStepInTime;
scaleEndPointInPixels *= pixelFactor;
for (int i = 0; i < transitionPoints.length; i++) {
transitionPoints[i] = (int)(transitionPoints[i] * measureUnit);
}
// izracunaj durationsInPixels
for (int j = 0; j < durationsInPixels.length; j++) {
durationsInPixels[j] = (int)(transitionPoints[j + 1] * pixelFactor) -
(int)(transitionPoints[j] * pixelFactor);
}
}
/**
* Metoda koja se brine o trajanju piksela nakon event-hendlanja i o tocnom
* postavljanju scaleEndPointInPixels
*/
public void setDurationsInPixelsAfterZoom (double scaleFactor)
{
scaleStepInTime /= scaleFactor;
pixelFactor *= scaleFactor;
scaleEndPointInPixels = 0;
for (int i = 0; i < durationsInTime.length; i++)
{
/* s istim 10^x faktorom mnozi se cijelo vrijeme */
durationsInTime[i] = (int)(durationsInFemtoSeconds[i] * measureUnit);
scaleEndPointInPixels += durationsInTime[i];
}
scaleEndPointInPixels *= pixelFactor;
// izracunaj durationsInPixels
for (int i = 0; i < durationsInPixels.length; i++) {
durationsInPixels[i] = (int)(transitionPoints[i + 1] * pixelFactor) -
(int)(transitionPoints[i] * pixelFactor);
}
this.scaleFactor *= scaleFactor;
}
/**
* Getter trajanje u pikselima za valne oblike
*/
public int[] getDurationInPixels()
{
return durationsInPixels;
}
/**
* Setter postavlja scaleFactor
*
* @param scaleFactor Zeljeni faktor
*/
public void setScaleFactor (float scaleFactor)
{
this.scaleFactor = scaleFactor;
}
/**
* Vraca trenutni scale faktor
*/
public double getScaleFactor ()
{
return scaleFactor;
}
/**
* Getter koji je potreban event-hendleru za precizno oznacavanje pozicije
*/
public String getMeasureUnitName ()
{
return measureUnitName;
}
/**
* Setter koji postavlja horizontalni offset u ovisnosti i scrollbaru
*
* @param offset Zeljeni offset
*/
public void setHorizontalOffset (int offset)
{
this.offsetXAxis = offset;
}
/**
* Trenutni horizontalni offset
*/
public int getHorizontalOffset ()
{
return offsetXAxis;
}
/**
* Getter koji daje krajnju tocku u pikselima, potreban za postavljanje nove
* vrijednosti scrollbara prilikom povecanja/smanjenja
*/
public int getScaleEndPointInPixels ()
{
return scaleEndPointInPixels;
}
/**
* Getter koji daje trenutnu vrijednost skale u vremenu (npr. 345 ns na 100
* piksela)
*/
public double getScaleStepInTime ()
{
return scaleStepInTime;
}
/**
* Preferirane dimenzije
*/
@Override
public Dimension getPreferredSize ()
{
return new Dimension(scaleEndPointInPixels, SCALE_HEIGHT);
}
/**
* Zumiraj tako da sve stane u jedan prozor
*/
public void fitToWindow() {
scaleFactor = (double)800 / scaleEndPointInPixels;
setDurationsInPixelsAfterZoom(scaleFactor);
}
/**
* Metoda vraca u defaultno stanje
*/
public void unfitToWindow() {
scaleFactor = 1;
scaleStepInTime = minimumDurationInTime;
pixelFactor = 100 / scaleStepInTime;
scaleEndPointInPixels *= pixelFactor;
setDurationsInPixelsAfterZoom(scaleFactor);
// System.out.println("da");
}
/**
* Crtanje komponente
*/
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
setBackground(themeColor.getScale());
g.setColor(themeColor.getLetters());
/* postavlja novu vrijednost scrollbara */
int horizontalValue = this.scaleEndPointInPixels -
this.getWidth() + 45;
if (horizontalValue >= 0) {
horizontalScrollbar.setMaximum(horizontalValue);
}
/*
* Bilo koja vrijednost postavlja se na visekratnik broja 100. Znaci, ako je
* offset bio 1450, stavit ce 1400 i poceti crtati od 1400
*/
screenStartPointInPixels = offsetXAxis - offsetXAxis % 100;
/*
* Duljina trenutno aktivnog ekrana koji ce se iscrtati je duljina panela + 200
* Skala se ne crta kompletno, vec samo dio koji trenutno upada u offset
*/
screenSizeInPixels = getWidth() + 200;
screenEndPointInPixels = screenStartPointInPixels + screenSizeInPixels;
scaleFactor = Math.round(scaleFactor * 1e13d) / 1e13d;
/* scaleStepInTime ostaje fiksan jer je potrebna pocetna vrijednost */
double tempScaleStepInTime = scaleStepInTime;
/* x se mijenja u koracima od 100 piksela */
int x = 0;
/*
* samo ako je screenStartPointInPixels == 0 npr offset = 30, crta od
* nultog piksela, ali pomatnut ulijevo za offset, pa 30 pocinje od
* nultog piksela
*/
if (screenStartPointInPixels == SCALE_START_POINT_IN_PIXELS)
{
g.drawLine(x - offsetXAxis, SCALE_TAG_LINE_YSTART, x - offsetXAxis,
SCALE_TAG_LINE_YEND);
g.drawString("0", x - offsetXAxis, SCALE_VALUE_YAXIS);
x = SCALE_STEP_IN_PIXELS;
scaleValue = scaleStepInTime;
}
/*
* inace moze biti npr. 2500. scaleValue se odmah postavlja na pocetnu
* vrijednost u skladu s brojem od kojeg pocinje crtanje
*/
else
{
x = screenStartPointInPixels;
scaleValue = screenStartPointInPixels / 100 * scaleStepInTime;
}
int endPoint = screenEndPointInPixels;
g.drawLine(screenStartPointInPixels - offsetXAxis, SCALE_MAIN_LINE_YAXIS,
endPoint - offsetXAxis, SCALE_MAIN_LINE_YAXIS);
String tempMeasureUnitName = measureUnitName;
int endPointInPixels = endPoint;
double potention = 1;
while (x < endPointInPixels)
{
/* svaka se vrijednost zaokruzuje na 10 decimala */
scaleValue = Math.round(scaleValue * 1e13d) / 1e13d;
/*
* ako vrijednost prijede 1000, prebacuje se na sljedecu vecu
* jedinicu i ujedno smanjuje scaleStepInTime za 1000
*/
if (scaleValue >= 1000)
{
for (int i = 0; i < units.length; i++)
{
if (units[i].equals(tempMeasureUnitName) && i < units.length - 1)
{
tempMeasureUnitName = units[i + 1];
scaleValue /= 1000.0;
tempScaleStepInTime /= 1000;
potention *= 1000;
break;
}
}
}
/* inace ako prijede u manju jedinicu */
else if (scaleValue < 1 && scaleValue != 0)
{
for (int i = 0; i < units.length; i++)
{
if (units[i].equals(tempMeasureUnitName) && i > 0)
{
tempMeasureUnitName = units[i - 1];
scaleValue *= 1000;
tempScaleStepInTime *= 1000;
potention /= 1000;
break;
}
}
}
/*
* bez obzira na vrijednost x, sve se crta pomaknuto za offset, tako
* da na ekranu bude slika od nultog piksela
*/
g.drawLine(x - offsetXAxis, SCALE_TAG_LINE_YSTART,
x - offsetXAxis, SCALE_TAG_LINE_YEND);
g.drawString((Math.round(scaleValue * 1000000d) / 1000000.0d)
+ tempMeasureUnitName,
x -(((Math.round(scaleValue * 1000000d) / 1000000.0d)
+ tempMeasureUnitName).length() * 5) / 2
- offsetXAxis, SCALE_VALUE_YAXIS);
scaleValue += tempScaleStepInTime;
// System.out.println("pixelFactor " + pixelFactor);
// System.out.println("potention " + potention);
x = (int)(scaleValue * potention * pixelFactor);
}
}
}
| Complete - # 39: beskonacna petlja pri pokusaju simuliranja
http://morgoth.zemris.fer.hr/trac/vhdllab/ticket/39
git-svn-id: d95c8f1468e72ac88b0e8aadd926028cc15263fe@1302 cbae1e92-611c-0410-ab7b-b19ac7dee622
| vhdllab-client/src/main/java/hr/fer/zemris/vhdllab/applets/simulations/Scale.java | Complete - # 39: beskonacna petlja pri pokusaju simuliranja http://morgoth.zemris.fer.hr/trac/vhdllab/ticket/39 | <ide><path>hdllab-client/src/main/java/hr/fer/zemris/vhdllab/applets/simulations/Scale.java
<ide> double operand2 = transitionPoints[i];
<ide> durationsInFemtoSeconds[i] = operand1 - operand2;
<ide> }
<add>
<add> // fix for http://morgoth.zemris.fer.hr/trac/vhdllab/ticket/39
<add> if (Arrays.equals(durationsInFemtoSeconds, new double[] {0.0})) {
<add> durationsInFemtoSeconds[0] = 1.0;
<add> }
<add>
<ide> /* crta pocetne valne oblike sa scaleFaktorom 1 */
<ide> drawDefaultWave();
<ide> } |
|
Java | apache-2.0 | 821c8e1aced91b2b532a90433f8672be853dd84d | 0 | pdxrunner/geode,PurelyApplied/geode,davebarnes97/geode,jdeppe-pivotal/geode,jdeppe-pivotal/geode,davinash/geode,PurelyApplied/geode,PurelyApplied/geode,davinash/geode,pdxrunner/geode,masaki-yamakawa/geode,pdxrunner/geode,masaki-yamakawa/geode,smgoller/geode,jdeppe-pivotal/geode,pdxrunner/geode,deepakddixit/incubator-geode,jdeppe-pivotal/geode,PurelyApplied/geode,deepakddixit/incubator-geode,pdxrunner/geode,PurelyApplied/geode,masaki-yamakawa/geode,deepakddixit/incubator-geode,jdeppe-pivotal/geode,deepakddixit/incubator-geode,masaki-yamakawa/geode,davinash/geode,davebarnes97/geode,jdeppe-pivotal/geode,davebarnes97/geode,deepakddixit/incubator-geode,davinash/geode,smgoller/geode,davebarnes97/geode,masaki-yamakawa/geode,davinash/geode,PurelyApplied/geode,pdxrunner/geode,masaki-yamakawa/geode,davinash/geode,PurelyApplied/geode,davebarnes97/geode,masaki-yamakawa/geode,jdeppe-pivotal/geode,deepakddixit/incubator-geode,davinash/geode,pdxrunner/geode,smgoller/geode,smgoller/geode,smgoller/geode,smgoller/geode,davebarnes97/geode,deepakddixit/incubator-geode,davebarnes97/geode,smgoller/geode | /*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.apache.geode.cache.client.internal;
import static org.apache.geode.distributed.ConfigurationProperties.SSL_ENABLED_COMPONENTS;
import static org.apache.geode.distributed.ConfigurationProperties.SSL_ENDPOINT_IDENTIFICATION_ENABLED;
import static org.apache.geode.distributed.ConfigurationProperties.SSL_KEYSTORE;
import static org.apache.geode.distributed.ConfigurationProperties.SSL_REQUIRE_AUTHENTICATION;
import static org.apache.geode.distributed.ConfigurationProperties.SSL_TRUSTSTORE;
import static org.apache.geode.distributed.ConfigurationProperties.SSL_USE_DEFAULT_CONTEXT;
import static org.apache.geode.security.SecurableCommunicationChannels.ALL;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import java.io.IOException;
import java.net.InetAddress;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.util.Properties;
import javax.net.ssl.SSLContext;
import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.RegionFactory;
import org.apache.geode.cache.RegionShortcut;
import org.apache.geode.cache.client.ClientCache;
import org.apache.geode.cache.client.ClientCacheFactory;
import org.apache.geode.cache.client.ClientRegionFactory;
import org.apache.geode.cache.client.ClientRegionShortcut;
import org.apache.geode.cache.client.NoAvailableServersException;
import org.apache.geode.cache.client.internal.provider.CustomKeyManagerFactory;
import org.apache.geode.cache.client.internal.provider.CustomTrustManagerFactory;
import org.apache.geode.cache.ssl.CertStores;
import org.apache.geode.cache.ssl.TestSSLUtils.CertificateBuilder;
import org.apache.geode.distributed.internal.tcpserver.LocatorCancelException;
import org.apache.geode.internal.net.SocketCreatorFactory;
import org.apache.geode.test.dunit.IgnoredException;
import org.apache.geode.test.dunit.rules.ClusterStartupRule;
import org.apache.geode.test.dunit.rules.MemberVM;
import org.apache.geode.test.junit.categories.ClientServerTest;
@Category({ClientServerTest.class})
public class CustomSSLProviderDistributedTest {
private static MemberVM locator;
private static MemberVM server;
@Rule
public ClusterStartupRule cluster = new ClusterStartupRule();
private CustomKeyManagerFactory.PKIXFactory keyManagerFactory;
private CustomTrustManagerFactory.PKIXFactory trustManagerFactory;
private void setupCluster(Properties locatorSSLProps, Properties serverSSLProps) {
// create a cluster
locator = cluster.startLocatorVM(0, locatorSSLProps);
server = cluster.startServerVM(1, serverSSLProps, locator.getPort());
// create region
server.invoke(CustomSSLProviderDistributedTest::createServerRegion);
locator.waitUntilRegionIsReadyOnExactlyThisManyServers("/region", 1);
}
private static void createServerRegion() {
RegionFactory factory =
ClusterStartupRule.getCache().createRegionFactory(RegionShortcut.REPLICATE);
Region r = factory.create("region");
r.put("serverkey", "servervalue");
}
@Test
public void hostNameIsValidatedWhenUsingDefaultContext() throws Exception {
CertificateBuilder locatorCertificate = new CertificateBuilder()
.commonName("locator")
// ClusterStartupRule uses 'localhost' as locator host
.sanDnsName(InetAddress.getLoopbackAddress().getHostName())
.sanDnsName(InetAddress.getLocalHost().getHostName())
.sanDnsName(InetAddress.getLocalHost().getCanonicalHostName())
.sanIpAddress(InetAddress.getLocalHost())
.sanIpAddress(InetAddress.getByName("0.0.0.0")); // to pass on windows
CertificateBuilder serverCertificate = new CertificateBuilder()
.commonName("server")
.sanDnsName(InetAddress.getLocalHost().getHostName())
.sanIpAddress(InetAddress.getLocalHost());
CertificateBuilder clientCertificate = new CertificateBuilder()
.commonName("client");
validateClientSSLConnection(locatorCertificate, serverCertificate, clientCertificate, true,
true, false, null);
}
@Test
public void clientCanChooseNotToValidateHostName() throws Exception {
CertificateBuilder locatorCertificate = new CertificateBuilder()
.commonName("locator");
CertificateBuilder serverCertificate = new CertificateBuilder()
.commonName("server");
CertificateBuilder clientCertificate = new CertificateBuilder()
.commonName("client");
validateClientSSLConnection(locatorCertificate, serverCertificate, clientCertificate, false,
false, true, null);
}
@Test
public void clientConnectionFailsIfNoHostNameInLocatorKey() throws Exception {
CertificateBuilder locatorCertificate = new CertificateBuilder()
.commonName("locator");
CertificateBuilder serverCertificate = new CertificateBuilder()
.commonName("server");
CertificateBuilder clientCertificate = new CertificateBuilder()
.commonName("client");
validateClientSSLConnection(locatorCertificate, serverCertificate, clientCertificate, false,
false, false, LocatorCancelException.class);
}
@Test
public void clientConnectionFailsWhenWrongHostNameInLocatorKey() throws Exception {
CertificateBuilder locatorCertificate = new CertificateBuilder()
.commonName("locator")
.sanDnsName("example.com");;
CertificateBuilder serverCertificate = new CertificateBuilder()
.commonName("server")
.sanDnsName("example.com");;
CertificateBuilder clientCertificate = new CertificateBuilder()
.commonName("client");
validateClientSSLConnection(locatorCertificate, serverCertificate, clientCertificate, false,
false,
false,
LocatorCancelException.class);
}
@Test
public void expectConnectionFailureWhenNoHostNameInServerKey() throws Exception {
CertificateBuilder locatorCertificateWithSan = new CertificateBuilder()
.commonName("locator")
.sanDnsName(InetAddress.getLoopbackAddress().getHostName())
.sanDnsName(InetAddress.getLocalHost().getHostName())
.sanDnsName(InetAddress.getLocalHost().getCanonicalHostName())
.sanIpAddress(InetAddress.getLocalHost());
CertificateBuilder serverCertificateWithNoSan = new CertificateBuilder()
.commonName("server");
CertificateBuilder clientCertificate = new CertificateBuilder()
.commonName("client");
validateClientSSLConnection(locatorCertificateWithSan, serverCertificateWithNoSan,
clientCertificate, false, false, false,
NoAvailableServersException.class);
}
private void validateClientSSLConnection(CertificateBuilder locatorCertificate,
CertificateBuilder serverCertificate, CertificateBuilder clientCertificate,
boolean enableHostNameVerficationForLocator, boolean enableHostNameVerificationForServer,
boolean disableHostNameVerificationForClient,
Class expectedExceptionOnClient)
throws GeneralSecurityException, IOException {
CertStores locatorStore = CertStores.locatorStore();
locatorStore.withCertificate(locatorCertificate);
CertStores serverStore = CertStores.serverStore();
serverStore.withCertificate(serverCertificate);
CertStores clientStore = CertStores.clientStore();
clientStore.withCertificate(clientCertificate);
Properties locatorSSLProps = locatorStore
.trustSelf()
.trust(serverStore.alias(), serverStore.certificate())
.trust(clientStore.alias(), clientStore.certificate())
.propertiesWith(ALL, false, enableHostNameVerficationForLocator);
Properties serverSSLProps = serverStore
.trustSelf()
.trust(locatorStore.alias(), locatorStore.certificate())
.trust(clientStore.alias(), clientStore.certificate())
.propertiesWith(ALL, true, enableHostNameVerificationForServer);
// this props is only to create temp keystore and truststore and get paths
Properties clientSSLProps = clientStore
.trust(locatorStore.alias(), locatorStore.certificate())
.trust(serverStore.alias(), serverStore.certificate())
.propertiesWith(ALL, true, true);
setupCluster(locatorSSLProps, serverSSLProps);
// setup client
keyManagerFactory =
new CustomKeyManagerFactory.PKIXFactory(clientSSLProps.getProperty(SSL_KEYSTORE));
keyManagerFactory.engineInit(null, null);
trustManagerFactory =
new CustomTrustManagerFactory.PKIXFactory(clientSSLProps.getProperty(SSL_TRUSTSTORE));
trustManagerFactory.engineInit((KeyStore) null);
SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
sslContext.init(keyManagerFactory.engineGetKeyManagers(),
trustManagerFactory.engineGetTrustManagers(), null);
// set default context
SSLContext.setDefault(sslContext);
Properties clientSSLProperties = new Properties();
clientSSLProperties.setProperty(SSL_ENABLED_COMPONENTS, ALL);
clientSSLProperties.setProperty(SSL_REQUIRE_AUTHENTICATION, String.valueOf("true"));
clientSSLProperties.setProperty(SSL_USE_DEFAULT_CONTEXT, String.valueOf("true"));
if (disableHostNameVerificationForClient) {
// client chose to override default
clientSSLProperties.setProperty(SSL_ENDPOINT_IDENTIFICATION_ENABLED, String.valueOf("false"));
}
ClientCacheFactory clientCacheFactory = new ClientCacheFactory(clientSSLProperties);
clientCacheFactory.addPoolLocator(locator.getVM().getHost().getHostName(), locator.getPort());
ClientCache clientCache = clientCacheFactory.create();
ClientRegionFactory<String, String> regionFactory =
clientCache.createClientRegionFactory(ClientRegionShortcut.PROXY);
if (expectedExceptionOnClient != null) {
IgnoredException.addIgnoredException("javax.net.ssl.SSLHandshakeException");
IgnoredException.addIgnoredException("java.net.SocketException");
Region<String, String> clientRegion = regionFactory.create("region");
assertThatExceptionOfType(expectedExceptionOnClient)
.isThrownBy(() -> clientRegion.put("clientkey", "clientvalue"));
} else {
// test client can read and write to server
Region<String, String> clientRegion = regionFactory.create("region");
assertThat("servervalue").isEqualTo(clientRegion.get("serverkey"));
clientRegion.put("clientkey", "clientvalue");
// test server can see data written by client
server.invoke(CustomSSLProviderDistributedTest::doServerRegionTest);
}
SocketCreatorFactory.close();
}
private static void doServerRegionTest() {
Region<String, String> region = ClusterStartupRule.getCache().getRegion("region");
assertThat("servervalue").isEqualTo(region.get("serverkey"));
assertThat("clientvalue").isEqualTo(region.get("clientkey"));
}
}
| geode-core/src/distributedTest/java/org/apache/geode/cache/client/internal/CustomSSLProviderDistributedTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.apache.geode.cache.client.internal;
import static org.apache.geode.distributed.ConfigurationProperties.SSL_ENABLED_COMPONENTS;
import static org.apache.geode.distributed.ConfigurationProperties.SSL_ENDPOINT_IDENTIFICATION_ENABLED;
import static org.apache.geode.distributed.ConfigurationProperties.SSL_KEYSTORE;
import static org.apache.geode.distributed.ConfigurationProperties.SSL_REQUIRE_AUTHENTICATION;
import static org.apache.geode.distributed.ConfigurationProperties.SSL_TRUSTSTORE;
import static org.apache.geode.distributed.ConfigurationProperties.SSL_USE_DEFAULT_CONTEXT;
import static org.apache.geode.security.SecurableCommunicationChannels.ALL;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import java.io.IOException;
import java.net.InetAddress;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.util.Properties;
import javax.net.ssl.SSLContext;
import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.RegionFactory;
import org.apache.geode.cache.RegionShortcut;
import org.apache.geode.cache.client.ClientCache;
import org.apache.geode.cache.client.ClientCacheFactory;
import org.apache.geode.cache.client.ClientRegionFactory;
import org.apache.geode.cache.client.ClientRegionShortcut;
import org.apache.geode.cache.client.NoAvailableServersException;
import org.apache.geode.cache.client.internal.provider.CustomKeyManagerFactory;
import org.apache.geode.cache.client.internal.provider.CustomTrustManagerFactory;
import org.apache.geode.cache.ssl.CertStores;
import org.apache.geode.cache.ssl.TestSSLUtils.CertificateBuilder;
import org.apache.geode.distributed.internal.tcpserver.LocatorCancelException;
import org.apache.geode.internal.net.SocketCreatorFactory;
import org.apache.geode.test.dunit.IgnoredException;
import org.apache.geode.test.dunit.rules.ClusterStartupRule;
import org.apache.geode.test.dunit.rules.MemberVM;
import org.apache.geode.test.junit.categories.ClientServerTest;
@Category({ClientServerTest.class})
public class CustomSSLProviderDistributedTest {
private static MemberVM locator;
private static MemberVM server;
@Rule
public ClusterStartupRule cluster = new ClusterStartupRule();
private CustomKeyManagerFactory.PKIXFactory keyManagerFactory;
private CustomTrustManagerFactory.PKIXFactory trustManagerFactory;
private void setupCluster(Properties locatorSSLProps, Properties serverSSLProps) {
// create a cluster
locator = cluster.startLocatorVM(0, locatorSSLProps);
server = cluster.startServerVM(1, serverSSLProps, locator.getPort());
// create region
server.invoke(CustomSSLProviderDistributedTest::createServerRegion);
locator.waitUntilRegionIsReadyOnExactlyThisManyServers("/region", 1);
}
private static void createServerRegion() {
RegionFactory factory =
ClusterStartupRule.getCache().createRegionFactory(RegionShortcut.REPLICATE);
Region r = factory.create("region");
r.put("serverkey", "servervalue");
}
@Test
public void hostNameIsValidatedWhenUsingDefaultContext() throws Exception {
CertificateBuilder locatorCertificate = new CertificateBuilder()
.commonName("locator")
// ClusterStartupRule uses 'localhost' as locator host
.sanDnsName(InetAddress.getLoopbackAddress().getHostName())
.sanDnsName(InetAddress.getLocalHost().getHostName())
.sanIpAddress(InetAddress.getLocalHost())
.sanIpAddress(InetAddress.getByName("0.0.0.0")); // to pass on windows
CertificateBuilder serverCertificate = new CertificateBuilder()
.commonName("server")
.sanDnsName(InetAddress.getLocalHost().getHostName())
.sanIpAddress(InetAddress.getLocalHost());
CertificateBuilder clientCertificate = new CertificateBuilder()
.commonName("client");
validateClientSSLConnection(locatorCertificate, serverCertificate, clientCertificate, true,
true, false, null);
}
@Test
public void clientCanChooseNotToValidateHostName() throws Exception {
CertificateBuilder locatorCertificate = new CertificateBuilder()
.commonName("locator");
CertificateBuilder serverCertificate = new CertificateBuilder()
.commonName("server");
CertificateBuilder clientCertificate = new CertificateBuilder()
.commonName("client");
validateClientSSLConnection(locatorCertificate, serverCertificate, clientCertificate, false,
false, true, null);
}
@Test
public void clientConnectionFailsIfNoHostNameInLocatorKey() throws Exception {
CertificateBuilder locatorCertificate = new CertificateBuilder()
.commonName("locator");
CertificateBuilder serverCertificate = new CertificateBuilder()
.commonName("server");
CertificateBuilder clientCertificate = new CertificateBuilder()
.commonName("client");
validateClientSSLConnection(locatorCertificate, serverCertificate, clientCertificate, false,
false, false, LocatorCancelException.class);
}
@Test
public void clientConnectionFailsWhenWrongHostNameInLocatorKey() throws Exception {
CertificateBuilder locatorCertificate = new CertificateBuilder()
.commonName("locator")
.sanDnsName("example.com");;
CertificateBuilder serverCertificate = new CertificateBuilder()
.commonName("server")
.sanDnsName("example.com");;
CertificateBuilder clientCertificate = new CertificateBuilder()
.commonName("client");
validateClientSSLConnection(locatorCertificate, serverCertificate, clientCertificate, false,
false,
false,
LocatorCancelException.class);
}
@Test
public void expectConnectionFailureWhenNoHostNameInServerKey() throws Exception {
CertificateBuilder locatorCertificateWithSan = new CertificateBuilder()
.commonName("locator")
.sanDnsName(InetAddress.getLoopbackAddress().getHostName())
.sanDnsName(InetAddress.getLocalHost().getHostName())
.sanIpAddress(InetAddress.getLocalHost());
CertificateBuilder serverCertificateWithNoSan = new CertificateBuilder()
.commonName("server");
CertificateBuilder clientCertificate = new CertificateBuilder()
.commonName("client");
validateClientSSLConnection(locatorCertificateWithSan, serverCertificateWithNoSan,
clientCertificate, false, false, false,
NoAvailableServersException.class);
}
private void validateClientSSLConnection(CertificateBuilder locatorCertificate,
CertificateBuilder serverCertificate, CertificateBuilder clientCertificate,
boolean enableHostNameVerficationForLocator, boolean enableHostNameVerificationForServer,
boolean disableHostNameVerificationForClient,
Class expectedExceptionOnClient)
throws GeneralSecurityException, IOException {
CertStores locatorStore = CertStores.locatorStore();
locatorStore.withCertificate(locatorCertificate);
CertStores serverStore = CertStores.serverStore();
serverStore.withCertificate(serverCertificate);
CertStores clientStore = CertStores.clientStore();
clientStore.withCertificate(clientCertificate);
Properties locatorSSLProps = locatorStore
.trustSelf()
.trust(serverStore.alias(), serverStore.certificate())
.trust(clientStore.alias(), clientStore.certificate())
.propertiesWith(ALL, false, enableHostNameVerficationForLocator);
Properties serverSSLProps = serverStore
.trustSelf()
.trust(locatorStore.alias(), locatorStore.certificate())
.trust(clientStore.alias(), clientStore.certificate())
.propertiesWith(ALL, true, enableHostNameVerificationForServer);
// this props is only to create temp keystore and truststore and get paths
Properties clientSSLProps = clientStore
.trust(locatorStore.alias(), locatorStore.certificate())
.trust(serverStore.alias(), serverStore.certificate())
.propertiesWith(ALL, true, true);
setupCluster(locatorSSLProps, serverSSLProps);
// setup client
keyManagerFactory =
new CustomKeyManagerFactory.PKIXFactory(clientSSLProps.getProperty(SSL_KEYSTORE));
keyManagerFactory.engineInit(null, null);
trustManagerFactory =
new CustomTrustManagerFactory.PKIXFactory(clientSSLProps.getProperty(SSL_TRUSTSTORE));
trustManagerFactory.engineInit((KeyStore) null);
SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
sslContext.init(keyManagerFactory.engineGetKeyManagers(),
trustManagerFactory.engineGetTrustManagers(), null);
// set default context
SSLContext.setDefault(sslContext);
Properties clientSSLProperties = new Properties();
clientSSLProperties.setProperty(SSL_ENABLED_COMPONENTS, ALL);
clientSSLProperties.setProperty(SSL_REQUIRE_AUTHENTICATION, String.valueOf("true"));
clientSSLProperties.setProperty(SSL_USE_DEFAULT_CONTEXT, String.valueOf("true"));
if (disableHostNameVerificationForClient) {
// client chose to override default
clientSSLProperties.setProperty(SSL_ENDPOINT_IDENTIFICATION_ENABLED, String.valueOf("false"));
}
ClientCacheFactory clientCacheFactory = new ClientCacheFactory(clientSSLProperties);
clientCacheFactory.addPoolLocator(locator.getVM().getHost().getHostName(), locator.getPort());
ClientCache clientCache = clientCacheFactory.create();
ClientRegionFactory<String, String> regionFactory =
clientCache.createClientRegionFactory(ClientRegionShortcut.PROXY);
if (expectedExceptionOnClient != null) {
IgnoredException.addIgnoredException("javax.net.ssl.SSLHandshakeException");
IgnoredException.addIgnoredException("java.net.SocketException");
Region<String, String> clientRegion = regionFactory.create("region");
assertThatExceptionOfType(expectedExceptionOnClient)
.isThrownBy(() -> clientRegion.put("clientkey", "clientvalue"));
} else {
// test client can read and write to server
Region<String, String> clientRegion = regionFactory.create("region");
assertThat("servervalue").isEqualTo(clientRegion.get("serverkey"));
clientRegion.put("clientkey", "clientvalue");
// test server can see data written by client
server.invoke(CustomSSLProviderDistributedTest::doServerRegionTest);
}
SocketCreatorFactory.close();
}
private static void doServerRegionTest() {
Region<String, String> region = ClusterStartupRule.getCache().getRegion("region");
assertThat("servervalue").isEqualTo(region.get("serverkey"));
assertThat("clientvalue").isEqualTo(region.get("clientkey"));
}
}
| GEODE-5212: Also use the host's canonical (fully qualified) name as a SAN in the certificate (#2536)
| geode-core/src/distributedTest/java/org/apache/geode/cache/client/internal/CustomSSLProviderDistributedTest.java | GEODE-5212: Also use the host's canonical (fully qualified) name as a SAN in the certificate (#2536) | <ide><path>eode-core/src/distributedTest/java/org/apache/geode/cache/client/internal/CustomSSLProviderDistributedTest.java
<ide> // ClusterStartupRule uses 'localhost' as locator host
<ide> .sanDnsName(InetAddress.getLoopbackAddress().getHostName())
<ide> .sanDnsName(InetAddress.getLocalHost().getHostName())
<add> .sanDnsName(InetAddress.getLocalHost().getCanonicalHostName())
<ide> .sanIpAddress(InetAddress.getLocalHost())
<ide> .sanIpAddress(InetAddress.getByName("0.0.0.0")); // to pass on windows
<ide>
<ide> .commonName("locator")
<ide> .sanDnsName(InetAddress.getLoopbackAddress().getHostName())
<ide> .sanDnsName(InetAddress.getLocalHost().getHostName())
<add> .sanDnsName(InetAddress.getLocalHost().getCanonicalHostName())
<ide> .sanIpAddress(InetAddress.getLocalHost());
<ide>
<ide> CertificateBuilder serverCertificateWithNoSan = new CertificateBuilder() |
|
Java | mit | ca38a4b13bc424b9430f3ad812c7c9d57eb6b0a9 | 0 | TooTallNate/Java-WebSocket,marci4/Java-WebSocket-Dev,marci4/Java-WebSocket-Dev,TooTallNate/Java-WebSocket | /*
* Copyright (c) 2010-2020 Nathan Rajlich
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
package org.java_websocket.server;
import java.io.IOException;
import java.net.*;
import java.nio.ByteBuffer;
import java.nio.channels.CancelledKeyException;
import java.nio.channels.ClosedByInterruptException;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.*;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import org.java_websocket.*;
import org.java_websocket.drafts.Draft;
import org.java_websocket.exceptions.WebsocketNotConnectedException;
import org.java_websocket.exceptions.WrappedIOException;
import org.java_websocket.framing.CloseFrame;
import org.java_websocket.framing.Framedata;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.handshake.Handshakedata;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <tt>WebSocketServer</tt> is an abstract class that only takes care of the
* HTTP handshake portion of WebSockets. It's up to a subclass to add
* functionality/purpose to the server.
*
*/
public abstract class WebSocketServer extends AbstractWebSocket implements Runnable {
private static final int AVAILABLE_PROCESSORS = Runtime.getRuntime().availableProcessors();
/**
* Logger instance
*
* @since 1.4.0
*/
private final Logger log = LoggerFactory.getLogger(WebSocketServer.class);
/**
* Holds the list of active WebSocket connections. "Active" means WebSocket
* handshake is complete and socket can be written to, or read from.
*/
private final Collection<WebSocket> connections;
/**
* The port number that this WebSocket server should listen on. Default is
* WebSocketImpl.DEFAULT_PORT.
*/
private final InetSocketAddress address;
/**
* The socket channel for this WebSocket server.
*/
private ServerSocketChannel server;
/**
* The 'Selector' used to get event keys from the underlying socket.
*/
private Selector selector;
/**
* The Draft of the WebSocket protocol the Server is adhering to.
*/
private List<Draft> drafts;
private Thread selectorthread;
private final AtomicBoolean isclosed = new AtomicBoolean( false );
protected List<WebSocketWorker> decoders;
private List<WebSocketImpl> iqueue;
private BlockingQueue<ByteBuffer> buffers;
private int queueinvokes = 0;
private final AtomicInteger queuesize = new AtomicInteger( 0 );
private WebSocketServerFactory wsf = new DefaultWebSocketServerFactory();
/**
* Attribute which allows you to configure the socket "backlog" parameter
* which determines how many client connections can be queued.
* @since 1.5.0
*/
private int maxPendingConnections = -1;
/**
* Creates a WebSocketServer that will attempt to
* listen on port <var>WebSocketImpl.DEFAULT_PORT</var>.
*
* @see #WebSocketServer(InetSocketAddress, int, List, Collection) more details here
*/
public WebSocketServer() {
this( new InetSocketAddress( WebSocketImpl.DEFAULT_PORT ), AVAILABLE_PROCESSORS, null );
}
/**
* Creates a WebSocketServer that will attempt to bind/listen on the given <var>address</var>.
*
* @see #WebSocketServer(InetSocketAddress, int, List, Collection) more details here
* @param address The address to listen to
*/
public WebSocketServer( InetSocketAddress address ) {
this( address, AVAILABLE_PROCESSORS, null );
}
/**
* @see #WebSocketServer(InetSocketAddress, int, List, Collection) more details here
* @param address
* The address (host:port) this server should listen on.
* @param decodercount
* The number of {@link WebSocketWorker}s that will be used to process the incoming network data. By default this will be <code>Runtime.getRuntime().availableProcessors()</code>
*/
public WebSocketServer( InetSocketAddress address , int decodercount ) {
this( address, decodercount, null );
}
/**
* @see #WebSocketServer(InetSocketAddress, int, List, Collection) more details here
*
* @param address
* The address (host:port) this server should listen on.
* @param drafts
* The versions of the WebSocket protocol that this server
* instance should comply to. Clients that use an other protocol version will be rejected.
*
*/
public WebSocketServer( InetSocketAddress address , List<Draft> drafts ) {
this( address, AVAILABLE_PROCESSORS, drafts );
}
/**
* @see #WebSocketServer(InetSocketAddress, int, List, Collection) more details here
*
* @param address
* The address (host:port) this server should listen on.
* @param decodercount
* The number of {@link WebSocketWorker}s that will be used to process the incoming network data. By default this will be <code>Runtime.getRuntime().availableProcessors()</code>
* @param drafts
* The versions of the WebSocket protocol that this server
* instance should comply to. Clients that use an other protocol version will be rejected.
*/
public WebSocketServer( InetSocketAddress address , int decodercount , List<Draft> drafts ) {
this( address, decodercount, drafts, new HashSet<WebSocket>() );
}
/**
* Creates a WebSocketServer that will attempt to bind/listen on the given <var>address</var>,
* and comply with <tt>Draft</tt> version <var>draft</var>.
*
* @param address
* The address (host:port) this server should listen on.
* @param decodercount
* The number of {@link WebSocketWorker}s that will be used to process the incoming network data. By default this will be <code>Runtime.getRuntime().availableProcessors()</code>
* @param drafts
* The versions of the WebSocket protocol that this server
* instance should comply to. Clients that use an other protocol version will be rejected.
*
* @param connectionscontainer
* Allows to specify a collection that will be used to store the websockets in. <br>
* If you plan to often iterate through the currently connected websockets you may want to use a collection that does not require synchronization like a {@link CopyOnWriteArraySet}. In that case make sure that you overload {@link #removeConnection(WebSocket)} and {@link #addConnection(WebSocket)}.<br>
* By default a {@link HashSet} will be used.
*
* @see #removeConnection(WebSocket) for more control over syncronized operation
* @see <a href="https://github.com/TooTallNate/Java-WebSocket/wiki/Drafts" > more about drafts</a>
*/
public WebSocketServer( InetSocketAddress address , int decodercount , List<Draft> drafts , Collection<WebSocket> connectionscontainer ) {
if( address == null || decodercount < 1 || connectionscontainer == null ) {
throw new IllegalArgumentException( "address and connectionscontainer must not be null and you need at least 1 decoder" );
}
if( drafts == null )
this.drafts = Collections.emptyList();
else
this.drafts = drafts;
this.address = address;
this.connections = connectionscontainer;
setTcpNoDelay(false);
setReuseAddr(false);
iqueue = new LinkedList<WebSocketImpl>();
decoders = new ArrayList<WebSocketWorker>( decodercount );
buffers = new LinkedBlockingQueue<ByteBuffer>();
for( int i = 0 ; i < decodercount ; i++ ) {
WebSocketWorker ex = new WebSocketWorker();
decoders.add( ex );
}
}
/**
* Starts the server selectorthread that binds to the currently set port number and
* listeners for WebSocket connection requests. Creates a fixed thread pool with the size {@link WebSocketServer#AVAILABLE_PROCESSORS}<br>
* May only be called once.
*
* Alternatively you can call {@link WebSocketServer#run()} directly.
*
* @throws IllegalStateException Starting an instance again
*/
public void start() {
if( selectorthread != null )
throw new IllegalStateException( getClass().getName() + " can only be started once." );
new Thread( this ).start();
}
/**
* Closes all connected clients sockets, then closes the underlying
* ServerSocketChannel, effectively killing the server socket selectorthread,
* freeing the port the server was bound to and stops all internal workerthreads.
*
* If this method is called before the server is started it will never start.
*
* @param timeout
* Specifies how many milliseconds the overall close handshaking may take altogether before the connections are closed without proper close handshaking.<br>
*
* @throws InterruptedException Interrupt
*/
public void stop( int timeout ) throws InterruptedException {
if( !isclosed.compareAndSet( false, true ) ) { // this also makes sure that no further connections will be added to this.connections
return;
}
List<WebSocket> socketsToClose;
// copy the connections in a list (prevent callback deadlocks)
synchronized ( connections ) {
socketsToClose = new ArrayList<WebSocket>( connections );
}
for( WebSocket ws : socketsToClose ) {
ws.close( CloseFrame.GOING_AWAY );
}
wsf.close();
synchronized ( this ) {
if( selectorthread != null && selector != null) {
selector.wakeup();
selectorthread.join( timeout );
}
}
}
public void stop() throws IOException , InterruptedException {
stop( 0 );
}
/**
* Returns all currently connected clients.
* This collection does not allow any modification e.g. removing a client.
*
* @return A unmodifiable collection of all currently connected clients
* @since 1.3.8
*/
public Collection<WebSocket> getConnections() {
synchronized (connections) {
return Collections.unmodifiableCollection( new ArrayList<WebSocket>(connections) );
}
}
public InetSocketAddress getAddress() {
return this.address;
}
/**
* Gets the port number that this server listens on.
*
* @return The port number.
*/
public int getPort() {
int port = getAddress().getPort();
if( port == 0 && server != null ) {
port = server.socket().getLocalPort();
}
return port;
}
/**
* Get the list of active drafts
* @return the available drafts for this server
*/
public List<Draft> getDraft() {
return Collections.unmodifiableList( drafts );
}
/**
* Set the requested maximum number of pending connections on the socket. The exact semantics are implementation
* specific. The value provided should be greater than 0. If it is less than or equal to 0, then
* an implementation specific default will be used. This option will be passed as "backlog" parameter to {@link ServerSocket#bind(SocketAddress, int)}
* @since 1.5.0
*/
public void setMaxPendingConnections(int numberOfConnections) {
maxPendingConnections = numberOfConnections;
}
/**
* Returns the currently configured maximum number of pending connections.
*
* @see #setMaxPendingConnections(int)
* @since 1.5.0
*/
public int getMaxPendingConnections() {
return maxPendingConnections;
}
// Runnable IMPLEMENTATION /////////////////////////////////////////////////
public void run() {
if (!doEnsureSingleThread()) {
return;
}
if (!doSetupSelectorAndServerThread()) {
return;
}
try {
int iShutdownCount = 5;
int selectTimeout = 0;
while ( !selectorthread.isInterrupted() && iShutdownCount != 0) {
SelectionKey key = null;
try {
if (isclosed.get()) {
selectTimeout = 5;
}
int keyCount = selector.select( selectTimeout );
if (keyCount == 0 && isclosed.get()) {
iShutdownCount--;
}
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
if( !key.isValid() ) {
continue;
}
if( key.isAcceptable() ) {
doAccept(key, i);
continue;
}
if( key.isReadable() && !doRead(key, i)) {
continue;
}
if( key.isWritable() ) {
doWrite(key);
}
}
doAdditionalRead();
} catch ( CancelledKeyException e ) {
// an other thread may cancel the key
} catch ( ClosedByInterruptException e ) {
return; // do the same stuff as when InterruptedException is thrown
} catch ( WrappedIOException ex) {
handleIOException( key, ex.getConnection(), ex.getIOException());
} catch ( IOException ex ) {
handleIOException( key, null, ex );
} catch ( InterruptedException e ) {
// FIXME controlled shutdown (e.g. take care of buffermanagement)
Thread.currentThread().interrupt();
}
}
} catch ( RuntimeException e ) {
// should hopefully never occur
handleFatal( null, e );
} finally {
doServerShutdown();
}
}
/**
* Do an additional read
* @throws InterruptedException thrown by taking a buffer
* @throws IOException if an error happened during read
*/
private void doAdditionalRead() throws InterruptedException, IOException {
WebSocketImpl conn;
while ( !iqueue.isEmpty() ) {
conn = iqueue.remove( 0 );
WrappedByteChannel c = ( (WrappedByteChannel) conn.getChannel() );
ByteBuffer buf = takeBuffer();
try {
if( SocketChannelIOHelper.readMore( buf, conn, c ) )
iqueue.add( conn );
if( buf.hasRemaining() ) {
conn.inQueue.put( buf );
queue( conn );
} else {
pushBuffer( buf );
}
} catch ( IOException e ) {
pushBuffer( buf );
throw e;
}
}
}
/**
* Execute a accept operation
* @param key the selectionkey to read off
* @param i the iterator for the selection keys
* @throws InterruptedException thrown by taking a buffer
* @throws IOException if an error happened during accept
*/
private void doAccept(SelectionKey key, Iterator<SelectionKey> i) throws IOException, InterruptedException {
if( !onConnect( key ) ) {
key.cancel();
return;
}
SocketChannel channel = server.accept();
if(channel==null){
return;
}
channel.configureBlocking( false );
Socket socket = channel.socket();
socket.setTcpNoDelay( isTcpNoDelay() );
socket.setKeepAlive( true );
WebSocketImpl w = wsf.createWebSocket( this, drafts );
w.setSelectionKey(channel.register( selector, SelectionKey.OP_READ, w ));
try {
w.setChannel( wsf.wrapChannel( channel, w.getSelectionKey() ));
i.remove();
allocateBuffers( w );
} catch (IOException ex) {
if( w.getSelectionKey() != null )
w.getSelectionKey().cancel();
handleIOException( w.getSelectionKey(), null, ex );
}
}
/**
* Execute a read operation
* @param key the selectionkey to read off
* @param i the iterator for the selection keys
* @return true, if the read was successful, or false if there was an error
* @throws InterruptedException thrown by taking a buffer
* @throws IOException if an error happened during read
*/
private boolean doRead(SelectionKey key, Iterator<SelectionKey> i) throws InterruptedException, WrappedIOException {
WebSocketImpl conn = (WebSocketImpl) key.attachment();
ByteBuffer buf = takeBuffer();
if(conn.getChannel() == null){
key.cancel();
handleIOException( key, conn, new IOException() );
return false;
}
try {
if( SocketChannelIOHelper.read( buf, conn, conn.getChannel() ) ) {
if( buf.hasRemaining() ) {
conn.inQueue.put( buf );
queue( conn );
i.remove();
if( conn.getChannel() instanceof WrappedByteChannel && ( (WrappedByteChannel) conn.getChannel() ).isNeedRead() ) {
iqueue.add( conn );
}
} else {
pushBuffer(buf);
}
} else {
pushBuffer( buf );
}
} catch ( IOException e ) {
pushBuffer( buf );
throw new WrappedIOException(conn, e);
}
return true;
}
/**
* Execute a write operation
* @param key the selectionkey to write on
* @throws IOException if an error happened during batch
*/
private void doWrite(SelectionKey key) throws WrappedIOException {
WebSocketImpl conn = (WebSocketImpl) key.attachment();
try {
if (SocketChannelIOHelper.batch(conn, conn.getChannel())) {
if (key.isValid()) {
key.interestOps(SelectionKey.OP_READ);
}
}
} catch (IOException e) {
throw new WrappedIOException(conn, e);
}
}
/**
* Setup the selector thread as well as basic server settings
* @return true, if everything was successful, false if some error happened
*/
private boolean doSetupSelectorAndServerThread() {
selectorthread.setName( "WebSocketSelector-" + selectorthread.getId() );
try {
server = ServerSocketChannel.open();
server.configureBlocking( false );
ServerSocket socket = server.socket();
socket.setReceiveBufferSize( WebSocketImpl.RCVBUF );
socket.setReuseAddress( isReuseAddr() );
socket.bind( address, getMaxPendingConnections() );
selector = Selector.open();
server.register( selector, server.validOps() );
startConnectionLostTimer();
for( WebSocketWorker ex : decoders ){
ex.start();
}
onStart();
} catch ( IOException ex ) {
handleFatal( null, ex );
return false;
}
return true;
}
/**
* The websocket server can only be started once
* @return true, if the server can be started, false if already a thread is running
*/
private boolean doEnsureSingleThread() {
synchronized ( this ) {
if( selectorthread != null )
throw new IllegalStateException( getClass().getName() + " can only be started once." );
selectorthread = Thread.currentThread();
if( isclosed.get() ) {
return false;
}
}
return true;
}
/**
* Clean up everything after a shutdown
*/
private void doServerShutdown() {
stopConnectionLostTimer();
if( decoders != null ) {
for( WebSocketWorker w : decoders ) {
w.interrupt();
}
}
if( selector != null ) {
try {
selector.close();
} catch ( IOException e ) {
log.error( "IOException during selector.close", e );
onError( null, e );
}
}
if( server != null ) {
try {
server.close();
} catch ( IOException e ) {
log.error( "IOException during server.close", e );
onError( null, e );
}
}
}
protected void allocateBuffers( WebSocket c ) throws InterruptedException {
if( queuesize.get() >= 2 * decoders.size() + 1 ) {
return;
}
queuesize.incrementAndGet();
buffers.put( createBuffer() );
}
protected void releaseBuffers( WebSocket c ) throws InterruptedException {
// queuesize.decrementAndGet();
// takeBuffer();
}
public ByteBuffer createBuffer() {
return ByteBuffer.allocate( WebSocketImpl.RCVBUF );
}
protected void queue( WebSocketImpl ws ) throws InterruptedException {
if( ws.getWorkerThread() == null ) {
ws.setWorkerThread(decoders.get( queueinvokes % decoders.size() ));
queueinvokes++;
}
ws.getWorkerThread().put( ws );
}
private ByteBuffer takeBuffer() throws InterruptedException {
return buffers.take();
}
private void pushBuffer( ByteBuffer buf ) throws InterruptedException {
if( buffers.size() > queuesize.intValue() )
return;
buffers.put( buf );
}
private void handleIOException( SelectionKey key, WebSocket conn, IOException ex ) {
// onWebsocketError( conn, ex );// conn may be null here
if (key != null) {
key.cancel();
}
if( conn != null ) {
conn.closeConnection( CloseFrame.ABNORMAL_CLOSE, ex.getMessage() );
} else if( key != null ) {
SelectableChannel channel = key.channel();
if( channel != null && channel.isOpen() ) { // this could be the case if the IOException ex is a SSLException
try {
channel.close();
} catch ( IOException e ) {
// there is nothing that must be done here
}
log.trace("Connection closed because of exception",ex);
}
}
}
private void handleFatal( WebSocket conn, Exception e ) {
log.error( "Shutdown due to fatal error", e );
onError( conn, e );
//Shutting down WebSocketWorkers, see #222
if( decoders != null ) {
for( WebSocketWorker w : decoders ) {
w.interrupt();
}
}
if (selectorthread != null) {
selectorthread.interrupt();
}
try {
stop();
} catch ( IOException e1 ) {
log.error( "Error during shutdown", e1 );
onError( null, e1 );
} catch ( InterruptedException e1 ) {
Thread.currentThread().interrupt();
log.error( "Interrupt during stop", e );
onError( null, e1 );
}
}
@Override
public final void onWebsocketMessage( WebSocket conn, String message ) {
onMessage( conn, message );
}
@Override
public final void onWebsocketMessage( WebSocket conn, ByteBuffer blob ) {
onMessage( conn, blob );
}
@Override
public final void onWebsocketOpen( WebSocket conn, Handshakedata handshake ) {
if( addConnection( conn ) ) {
onOpen( conn, (ClientHandshake) handshake );
}
}
@Override
public final void onWebsocketClose( WebSocket conn, int code, String reason, boolean remote ) {
selector.wakeup();
try {
if( removeConnection( conn ) ) {
onClose( conn, code, reason, remote );
}
} finally {
try {
releaseBuffers( conn );
} catch ( InterruptedException e ) {
Thread.currentThread().interrupt();
}
}
}
/**
* This method performs remove operations on the connection and therefore also gives control over whether the operation shall be synchronized
* <p>
* {@link #WebSocketServer(InetSocketAddress, int, List, Collection)} allows to specify a collection which will be used to store current connections in.<br>
* Depending on the type on the connection, modifications of that collection may have to be synchronized.
* @param ws The Websocket connection which should be removed
* @return Removing connection successful
*/
protected boolean removeConnection( WebSocket ws ) {
boolean removed = false;
synchronized ( connections ) {
if (this.connections.contains( ws )) {
removed = this.connections.remove( ws );
} else {
//Don't throw an assert error if the ws is not in the list. e.g. when the other endpoint did not send any handshake. see #512
log.trace("Removing connection which is not in the connections collection! Possible no handshake recieved! {}", ws);
}
}
if( isclosed.get() && connections.isEmpty() ) {
selectorthread.interrupt();
}
return removed;
}
/**
* @see #removeConnection(WebSocket)
* @param ws the Websocket connection which should be added
* @return Adding connection successful
*/
protected boolean addConnection( WebSocket ws ) {
if( !isclosed.get() ) {
synchronized ( connections ) {
return this.connections.add( ws );
}
} else {
// This case will happen when a new connection gets ready while the server is already stopping.
ws.close( CloseFrame.GOING_AWAY );
return true;// for consistency sake we will make sure that both onOpen will be called
}
}
@Override
public final void onWebsocketError( WebSocket conn, Exception ex ) {
onError( conn, ex );
}
@Override
public final void onWriteDemand( WebSocket w ) {
WebSocketImpl conn = (WebSocketImpl) w;
try {
conn.getSelectionKey().interestOps( SelectionKey.OP_READ | SelectionKey.OP_WRITE );
} catch ( CancelledKeyException e ) {
// the thread which cancels key is responsible for possible cleanup
conn.outQueue.clear();
}
selector.wakeup();
}
@Override
public void onWebsocketCloseInitiated( WebSocket conn, int code, String reason ) {
onCloseInitiated( conn, code, reason );
}
@Override
public void onWebsocketClosing( WebSocket conn, int code, String reason, boolean remote ) {
onClosing( conn, code, reason, remote );
}
public void onCloseInitiated( WebSocket conn, int code, String reason ) {
}
public void onClosing( WebSocket conn, int code, String reason, boolean remote ) {
}
public final void setWebSocketFactory( WebSocketServerFactory wsf ) {
if (this.wsf != null)
this.wsf.close();
this.wsf = wsf;
}
public final WebSocketFactory getWebSocketFactory() {
return wsf;
}
/**
* Returns whether a new connection shall be accepted or not.<br>
* Therefore method is well suited to implement some kind of connection limitation.<br>
*
* @see #onOpen(WebSocket, ClientHandshake)
* @see #onWebsocketHandshakeReceivedAsServer(WebSocket, Draft, ClientHandshake)
* @param key the SelectionKey for the new connection
* @return Can this new connection be accepted
**/
protected boolean onConnect( SelectionKey key ) {
return true;
}
/**
* Getter to return the socket used by this specific connection
* @param conn The specific connection
* @return The socket used by this connection
*/
private Socket getSocket( WebSocket conn ) {
WebSocketImpl impl = (WebSocketImpl) conn;
return ( (SocketChannel) impl.getSelectionKey().channel() ).socket();
}
@Override
public InetSocketAddress getLocalSocketAddress( WebSocket conn ) {
return (InetSocketAddress) getSocket( conn ).getLocalSocketAddress();
}
@Override
public InetSocketAddress getRemoteSocketAddress( WebSocket conn ) {
return (InetSocketAddress) getSocket( conn ).getRemoteSocketAddress();
}
/** Called after an opening handshake has been performed and the given websocket is ready to be written on.
* @param conn The <tt>WebSocket</tt> instance this event is occuring on.
* @param handshake The handshake of the websocket instance
*/
public abstract void onOpen( WebSocket conn, ClientHandshake handshake );
/**
* Called after the websocket connection has been closed.
*
* @param conn The <tt>WebSocket</tt> instance this event is occuring on.
* @param code
* The codes can be looked up here: {@link CloseFrame}
* @param reason
* Additional information string
* @param remote
* Returns whether or not the closing of the connection was initiated by the remote host.
**/
public abstract void onClose( WebSocket conn, int code, String reason, boolean remote );
/**
* Callback for string messages received from the remote host
*
* @see #onMessage(WebSocket, ByteBuffer)
* @param conn The <tt>WebSocket</tt> instance this event is occuring on.
* @param message The UTF-8 decoded message that was received.
**/
public abstract void onMessage( WebSocket conn, String message );
/**
* Called when errors occurs. If an error causes the websocket connection to fail {@link #onClose(WebSocket, int, String, boolean)} will be called additionally.<br>
* This method will be called primarily because of IO or protocol errors.<br>
* If the given exception is an RuntimeException that probably means that you encountered a bug.<br>
*
* @param conn Can be null if there error does not belong to one specific websocket. For example if the servers port could not be bound.
* @param ex The exception causing this error
**/
public abstract void onError( WebSocket conn, Exception ex );
/**
* Called when the server started up successfully.
*
* If any error occured, onError is called instead.
*/
public abstract void onStart();
/**
* Callback for binary messages received from the remote host
*
* @see #onMessage(WebSocket, ByteBuffer)
*
* @param conn
* The <tt>WebSocket</tt> instance this event is occurring on.
* @param message
* The binary message that was received.
**/
public void onMessage( WebSocket conn, ByteBuffer message ) {
}
/**
* Send a text to all connected endpoints
* @param text the text to send to the endpoints
*/
public void broadcast(String text) {
broadcast( text, connections );
}
/**
* Send a byte array to all connected endpoints
* @param data the data to send to the endpoints
*/
public void broadcast(byte[] data) {
broadcast( data, connections );
}
/**
* Send a ByteBuffer to all connected endpoints
* @param data the data to send to the endpoints
*/
public void broadcast(ByteBuffer data) {
broadcast(data, connections);
}
/**
* Send a byte array to a specific collection of websocket connections
* @param data the data to send to the endpoints
* @param clients a collection of endpoints to whom the text has to be send
*/
public void broadcast(byte[] data, Collection<WebSocket> clients) {
if (data == null || clients == null) {
throw new IllegalArgumentException();
}
broadcast(ByteBuffer.wrap(data), clients);
}
/**
* Send a ByteBuffer to a specific collection of websocket connections
* @param data the data to send to the endpoints
* @param clients a collection of endpoints to whom the text has to be send
*/
public void broadcast(ByteBuffer data, Collection<WebSocket> clients) {
if (data == null || clients == null) {
throw new IllegalArgumentException();
}
doBroadcast(data, clients);
}
/**
* Send a text to a specific collection of websocket connections
* @param text the text to send to the endpoints
* @param clients a collection of endpoints to whom the text has to be send
*/
public void broadcast(String text, Collection<WebSocket> clients) {
if (text == null || clients == null) {
throw new IllegalArgumentException();
}
doBroadcast(text, clients);
}
/**
* Private method to cache all the frames to improve memory footprint and conversion time
* @param data the data to broadcast
* @param clients the clients to send the message to
*/
private void doBroadcast(Object data, Collection<WebSocket> clients) {
String sData = null;
if (data instanceof String) {
sData = (String)data;
}
ByteBuffer bData = null;
if (data instanceof ByteBuffer) {
bData = (ByteBuffer)data;
}
if (sData == null && bData == null) {
return;
}
Map<Draft, List<Framedata>> draftFrames = new HashMap<Draft, List<Framedata>>();
List<WebSocket> clientCopy;
synchronized (clients) {
clientCopy = new ArrayList<WebSocket>(clients);
}
for (WebSocket client : clientCopy) {
if (client != null) {
Draft draft = client.getDraft();
fillFrames(draft, draftFrames, sData, bData);
try {
client.sendFrame(draftFrames.get(draft));
} catch (WebsocketNotConnectedException e) {
//Ignore this exception in this case
}
}
}
}
/**
* Fills the draftFrames with new data for the broadcast
* @param draft The draft to use
* @param draftFrames The list of frames per draft to fill
* @param sData the string data, can be null
* @param bData the bytebuffer data, can be null
*/
private void fillFrames(Draft draft, Map<Draft, List<Framedata>> draftFrames, String sData, ByteBuffer bData) {
if( !draftFrames.containsKey( draft ) ) {
List<Framedata> frames = null;
if (sData != null) {
frames = draft.createFrames( sData, false );
}
if (bData != null) {
frames = draft.createFrames( bData, false );
}
if (frames != null) {
draftFrames.put(draft, frames);
}
}
}
/**
* This class is used to process incoming data
*/
public class WebSocketWorker extends Thread {
private BlockingQueue<WebSocketImpl> iqueue;
public WebSocketWorker() {
iqueue = new LinkedBlockingQueue<WebSocketImpl>();
setName( "WebSocketWorker-" + getId() );
setUncaughtExceptionHandler( new UncaughtExceptionHandler() {
@Override
public void uncaughtException( Thread t, Throwable e ) {
log.error("Uncaught exception in thread {}: {}", t.getName(), e);
}
} );
}
public void put( WebSocketImpl ws ) throws InterruptedException {
iqueue.put( ws );
}
@Override
public void run() {
WebSocketImpl ws = null;
try {
while ( true ) {
ByteBuffer buf;
ws = iqueue.take();
buf = ws.inQueue.poll();
assert ( buf != null );
doDecode(ws, buf);
ws = null;
}
} catch ( InterruptedException e ) {
Thread.currentThread().interrupt();
} catch ( RuntimeException e ) {
handleFatal( ws, e );
}
}
/**
* call ws.decode on the bytebuffer
* @param ws the Websocket
* @param buf the buffer to decode to
* @throws InterruptedException thrown by pushBuffer
*/
private void doDecode(WebSocketImpl ws, ByteBuffer buf) throws InterruptedException {
try {
ws.decode( buf );
} catch(Exception e){
log.error("Error while reading from remote connection", e);
}
finally {
pushBuffer( buf );
}
}
}
}
| src/main/java/org/java_websocket/server/WebSocketServer.java | /*
* Copyright (c) 2010-2020 Nathan Rajlich
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
package org.java_websocket.server;
import java.io.IOException;
import java.net.*;
import java.nio.ByteBuffer;
import java.nio.channels.CancelledKeyException;
import java.nio.channels.ClosedByInterruptException;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.*;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import org.java_websocket.*;
import org.java_websocket.drafts.Draft;
import org.java_websocket.exceptions.WebsocketNotConnectedException;
import org.java_websocket.exceptions.WrappedIOException;
import org.java_websocket.framing.CloseFrame;
import org.java_websocket.framing.Framedata;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.handshake.Handshakedata;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <tt>WebSocketServer</tt> is an abstract class that only takes care of the
* HTTP handshake portion of WebSockets. It's up to a subclass to add
* functionality/purpose to the server.
*
*/
public abstract class WebSocketServer extends AbstractWebSocket implements Runnable {
private static final int AVAILABLE_PROCESSORS = Runtime.getRuntime().availableProcessors();
/**
* Logger instance
*
* @since 1.4.0
*/
private final Logger log = LoggerFactory.getLogger(WebSocketServer.class);
/**
* Holds the list of active WebSocket connections. "Active" means WebSocket
* handshake is complete and socket can be written to, or read from.
*/
private final Collection<WebSocket> connections;
/**
* The port number that this WebSocket server should listen on. Default is
* WebSocketImpl.DEFAULT_PORT.
*/
private final InetSocketAddress address;
/**
* The socket channel for this WebSocket server.
*/
private ServerSocketChannel server;
/**
* The 'Selector' used to get event keys from the underlying socket.
*/
private Selector selector;
/**
* The Draft of the WebSocket protocol the Server is adhering to.
*/
private List<Draft> drafts;
private Thread selectorthread;
private final AtomicBoolean isclosed = new AtomicBoolean( false );
protected List<WebSocketWorker> decoders;
private List<WebSocketImpl> iqueue;
private BlockingQueue<ByteBuffer> buffers;
private int queueinvokes = 0;
private final AtomicInteger queuesize = new AtomicInteger( 0 );
private WebSocketServerFactory wsf = new DefaultWebSocketServerFactory();
/**
* Attribute which allows you to configure the socket "backlog" parameter
* which determines how many client connections can be queued.
*/
private int maxPendingConnections = -1;
/**
* Creates a WebSocketServer that will attempt to
* listen on port <var>WebSocketImpl.DEFAULT_PORT</var>.
*
* @see #WebSocketServer(InetSocketAddress, int, List, Collection) more details here
*/
public WebSocketServer() {
this( new InetSocketAddress( WebSocketImpl.DEFAULT_PORT ), AVAILABLE_PROCESSORS, null );
}
/**
* Creates a WebSocketServer that will attempt to bind/listen on the given <var>address</var>.
*
* @see #WebSocketServer(InetSocketAddress, int, List, Collection) more details here
* @param address The address to listen to
*/
public WebSocketServer( InetSocketAddress address ) {
this( address, AVAILABLE_PROCESSORS, null );
}
/**
* @see #WebSocketServer(InetSocketAddress, int, List, Collection) more details here
* @param address
* The address (host:port) this server should listen on.
* @param decodercount
* The number of {@link WebSocketWorker}s that will be used to process the incoming network data. By default this will be <code>Runtime.getRuntime().availableProcessors()</code>
*/
public WebSocketServer( InetSocketAddress address , int decodercount ) {
this( address, decodercount, null );
}
/**
* @see #WebSocketServer(InetSocketAddress, int, List, Collection) more details here
*
* @param address
* The address (host:port) this server should listen on.
* @param drafts
* The versions of the WebSocket protocol that this server
* instance should comply to. Clients that use an other protocol version will be rejected.
*
*/
public WebSocketServer( InetSocketAddress address , List<Draft> drafts ) {
this( address, AVAILABLE_PROCESSORS, drafts );
}
/**
* @see #WebSocketServer(InetSocketAddress, int, List, Collection) more details here
*
* @param address
* The address (host:port) this server should listen on.
* @param decodercount
* The number of {@link WebSocketWorker}s that will be used to process the incoming network data. By default this will be <code>Runtime.getRuntime().availableProcessors()</code>
* @param drafts
* The versions of the WebSocket protocol that this server
* instance should comply to. Clients that use an other protocol version will be rejected.
*/
public WebSocketServer( InetSocketAddress address , int decodercount , List<Draft> drafts ) {
this( address, decodercount, drafts, new HashSet<WebSocket>() );
}
/**
* Creates a WebSocketServer that will attempt to bind/listen on the given <var>address</var>,
* and comply with <tt>Draft</tt> version <var>draft</var>.
*
* @param address
* The address (host:port) this server should listen on.
* @param decodercount
* The number of {@link WebSocketWorker}s that will be used to process the incoming network data. By default this will be <code>Runtime.getRuntime().availableProcessors()</code>
* @param drafts
* The versions of the WebSocket protocol that this server
* instance should comply to. Clients that use an other protocol version will be rejected.
*
* @param connectionscontainer
* Allows to specify a collection that will be used to store the websockets in. <br>
* If you plan to often iterate through the currently connected websockets you may want to use a collection that does not require synchronization like a {@link CopyOnWriteArraySet}. In that case make sure that you overload {@link #removeConnection(WebSocket)} and {@link #addConnection(WebSocket)}.<br>
* By default a {@link HashSet} will be used.
*
* @see #removeConnection(WebSocket) for more control over syncronized operation
* @see <a href="https://github.com/TooTallNate/Java-WebSocket/wiki/Drafts" > more about drafts</a>
*/
public WebSocketServer( InetSocketAddress address , int decodercount , List<Draft> drafts , Collection<WebSocket> connectionscontainer ) {
if( address == null || decodercount < 1 || connectionscontainer == null ) {
throw new IllegalArgumentException( "address and connectionscontainer must not be null and you need at least 1 decoder" );
}
if( drafts == null )
this.drafts = Collections.emptyList();
else
this.drafts = drafts;
this.address = address;
this.connections = connectionscontainer;
setTcpNoDelay(false);
setReuseAddr(false);
iqueue = new LinkedList<WebSocketImpl>();
decoders = new ArrayList<WebSocketWorker>( decodercount );
buffers = new LinkedBlockingQueue<ByteBuffer>();
for( int i = 0 ; i < decodercount ; i++ ) {
WebSocketWorker ex = new WebSocketWorker();
decoders.add( ex );
}
}
/**
* Starts the server selectorthread that binds to the currently set port number and
* listeners for WebSocket connection requests. Creates a fixed thread pool with the size {@link WebSocketServer#AVAILABLE_PROCESSORS}<br>
* May only be called once.
*
* Alternatively you can call {@link WebSocketServer#run()} directly.
*
* @throws IllegalStateException Starting an instance again
*/
public void start() {
if( selectorthread != null )
throw new IllegalStateException( getClass().getName() + " can only be started once." );
new Thread( this ).start();
}
/**
* Closes all connected clients sockets, then closes the underlying
* ServerSocketChannel, effectively killing the server socket selectorthread,
* freeing the port the server was bound to and stops all internal workerthreads.
*
* If this method is called before the server is started it will never start.
*
* @param timeout
* Specifies how many milliseconds the overall close handshaking may take altogether before the connections are closed without proper close handshaking.<br>
*
* @throws InterruptedException Interrupt
*/
public void stop( int timeout ) throws InterruptedException {
if( !isclosed.compareAndSet( false, true ) ) { // this also makes sure that no further connections will be added to this.connections
return;
}
List<WebSocket> socketsToClose;
// copy the connections in a list (prevent callback deadlocks)
synchronized ( connections ) {
socketsToClose = new ArrayList<WebSocket>( connections );
}
for( WebSocket ws : socketsToClose ) {
ws.close( CloseFrame.GOING_AWAY );
}
wsf.close();
synchronized ( this ) {
if( selectorthread != null && selector != null) {
selector.wakeup();
selectorthread.join( timeout );
}
}
}
public void stop() throws IOException , InterruptedException {
stop( 0 );
}
/**
* Returns all currently connected clients.
* This collection does not allow any modification e.g. removing a client.
*
* @return A unmodifiable collection of all currently connected clients
* @since 1.3.8
*/
public Collection<WebSocket> getConnections() {
synchronized (connections) {
return Collections.unmodifiableCollection( new ArrayList<WebSocket>(connections) );
}
}
public InetSocketAddress getAddress() {
return this.address;
}
/**
* Gets the port number that this server listens on.
*
* @return The port number.
*/
public int getPort() {
int port = getAddress().getPort();
if( port == 0 && server != null ) {
port = server.socket().getLocalPort();
}
return port;
}
/**
* Get the list of active drafts
* @return the available drafts for this server
*/
public List<Draft> getDraft() {
return Collections.unmodifiableList( drafts );
}
/**
* Set the requested maximum number of pending connections on the socket. The exact semantics are implementation
* specific. The value provided should be greater than 0. If it is less than or equal to 0, then
* an implementation specific default will be used. This option will be passed as "backlog" parameter to {@link ServerSocket#bind(SocketAddress, int)}
*/
public void setMaxPendingConnections(int numberOfConnections) {
maxPendingConnections = numberOfConnections;
}
/**
* Returns the currently configured maximum number of pending connections.
*
* @see #setMaxPendingConnections(int)
*/
public int getMaxPendingConnections() {
return maxPendingConnections;
}
// Runnable IMPLEMENTATION /////////////////////////////////////////////////
public void run() {
if (!doEnsureSingleThread()) {
return;
}
if (!doSetupSelectorAndServerThread()) {
return;
}
try {
int iShutdownCount = 5;
int selectTimeout = 0;
while ( !selectorthread.isInterrupted() && iShutdownCount != 0) {
SelectionKey key = null;
try {
if (isclosed.get()) {
selectTimeout = 5;
}
int keyCount = selector.select( selectTimeout );
if (keyCount == 0 && isclosed.get()) {
iShutdownCount--;
}
Set<SelectionKey> keys = selector.selectedKeys();
Iterator<SelectionKey> i = keys.iterator();
while ( i.hasNext() ) {
key = i.next();
if( !key.isValid() ) {
continue;
}
if( key.isAcceptable() ) {
doAccept(key, i);
continue;
}
if( key.isReadable() && !doRead(key, i)) {
continue;
}
if( key.isWritable() ) {
doWrite(key);
}
}
doAdditionalRead();
} catch ( CancelledKeyException e ) {
// an other thread may cancel the key
} catch ( ClosedByInterruptException e ) {
return; // do the same stuff as when InterruptedException is thrown
} catch ( WrappedIOException ex) {
handleIOException( key, ex.getConnection(), ex.getIOException());
} catch ( IOException ex ) {
handleIOException( key, null, ex );
} catch ( InterruptedException e ) {
// FIXME controlled shutdown (e.g. take care of buffermanagement)
Thread.currentThread().interrupt();
}
}
} catch ( RuntimeException e ) {
// should hopefully never occur
handleFatal( null, e );
} finally {
doServerShutdown();
}
}
/**
* Do an additional read
* @throws InterruptedException thrown by taking a buffer
* @throws IOException if an error happened during read
*/
private void doAdditionalRead() throws InterruptedException, IOException {
WebSocketImpl conn;
while ( !iqueue.isEmpty() ) {
conn = iqueue.remove( 0 );
WrappedByteChannel c = ( (WrappedByteChannel) conn.getChannel() );
ByteBuffer buf = takeBuffer();
try {
if( SocketChannelIOHelper.readMore( buf, conn, c ) )
iqueue.add( conn );
if( buf.hasRemaining() ) {
conn.inQueue.put( buf );
queue( conn );
} else {
pushBuffer( buf );
}
} catch ( IOException e ) {
pushBuffer( buf );
throw e;
}
}
}
/**
* Execute a accept operation
* @param key the selectionkey to read off
* @param i the iterator for the selection keys
* @throws InterruptedException thrown by taking a buffer
* @throws IOException if an error happened during accept
*/
private void doAccept(SelectionKey key, Iterator<SelectionKey> i) throws IOException, InterruptedException {
if( !onConnect( key ) ) {
key.cancel();
return;
}
SocketChannel channel = server.accept();
if(channel==null){
return;
}
channel.configureBlocking( false );
Socket socket = channel.socket();
socket.setTcpNoDelay( isTcpNoDelay() );
socket.setKeepAlive( true );
WebSocketImpl w = wsf.createWebSocket( this, drafts );
w.setSelectionKey(channel.register( selector, SelectionKey.OP_READ, w ));
try {
w.setChannel( wsf.wrapChannel( channel, w.getSelectionKey() ));
i.remove();
allocateBuffers( w );
} catch (IOException ex) {
if( w.getSelectionKey() != null )
w.getSelectionKey().cancel();
handleIOException( w.getSelectionKey(), null, ex );
}
}
/**
* Execute a read operation
* @param key the selectionkey to read off
* @param i the iterator for the selection keys
* @return true, if the read was successful, or false if there was an error
* @throws InterruptedException thrown by taking a buffer
* @throws IOException if an error happened during read
*/
private boolean doRead(SelectionKey key, Iterator<SelectionKey> i) throws InterruptedException, WrappedIOException {
WebSocketImpl conn = (WebSocketImpl) key.attachment();
ByteBuffer buf = takeBuffer();
if(conn.getChannel() == null){
key.cancel();
handleIOException( key, conn, new IOException() );
return false;
}
try {
if( SocketChannelIOHelper.read( buf, conn, conn.getChannel() ) ) {
if( buf.hasRemaining() ) {
conn.inQueue.put( buf );
queue( conn );
i.remove();
if( conn.getChannel() instanceof WrappedByteChannel && ( (WrappedByteChannel) conn.getChannel() ).isNeedRead() ) {
iqueue.add( conn );
}
} else {
pushBuffer(buf);
}
} else {
pushBuffer( buf );
}
} catch ( IOException e ) {
pushBuffer( buf );
throw new WrappedIOException(conn, e);
}
return true;
}
/**
* Execute a write operation
* @param key the selectionkey to write on
* @throws IOException if an error happened during batch
*/
private void doWrite(SelectionKey key) throws WrappedIOException {
WebSocketImpl conn = (WebSocketImpl) key.attachment();
try {
if (SocketChannelIOHelper.batch(conn, conn.getChannel())) {
if (key.isValid()) {
key.interestOps(SelectionKey.OP_READ);
}
}
} catch (IOException e) {
throw new WrappedIOException(conn, e);
}
}
/**
* Setup the selector thread as well as basic server settings
* @return true, if everything was successful, false if some error happened
*/
private boolean doSetupSelectorAndServerThread() {
selectorthread.setName( "WebSocketSelector-" + selectorthread.getId() );
try {
server = ServerSocketChannel.open();
server.configureBlocking( false );
ServerSocket socket = server.socket();
socket.setReceiveBufferSize( WebSocketImpl.RCVBUF );
socket.setReuseAddress( isReuseAddr() );
socket.bind( address, getMaxPendingConnections() );
selector = Selector.open();
server.register( selector, server.validOps() );
startConnectionLostTimer();
for( WebSocketWorker ex : decoders ){
ex.start();
}
onStart();
} catch ( IOException ex ) {
handleFatal( null, ex );
return false;
}
return true;
}
/**
* The websocket server can only be started once
* @return true, if the server can be started, false if already a thread is running
*/
private boolean doEnsureSingleThread() {
synchronized ( this ) {
if( selectorthread != null )
throw new IllegalStateException( getClass().getName() + " can only be started once." );
selectorthread = Thread.currentThread();
if( isclosed.get() ) {
return false;
}
}
return true;
}
/**
* Clean up everything after a shutdown
*/
private void doServerShutdown() {
stopConnectionLostTimer();
if( decoders != null ) {
for( WebSocketWorker w : decoders ) {
w.interrupt();
}
}
if( selector != null ) {
try {
selector.close();
} catch ( IOException e ) {
log.error( "IOException during selector.close", e );
onError( null, e );
}
}
if( server != null ) {
try {
server.close();
} catch ( IOException e ) {
log.error( "IOException during server.close", e );
onError( null, e );
}
}
}
protected void allocateBuffers( WebSocket c ) throws InterruptedException {
if( queuesize.get() >= 2 * decoders.size() + 1 ) {
return;
}
queuesize.incrementAndGet();
buffers.put( createBuffer() );
}
protected void releaseBuffers( WebSocket c ) throws InterruptedException {
// queuesize.decrementAndGet();
// takeBuffer();
}
public ByteBuffer createBuffer() {
return ByteBuffer.allocate( WebSocketImpl.RCVBUF );
}
protected void queue( WebSocketImpl ws ) throws InterruptedException {
if( ws.getWorkerThread() == null ) {
ws.setWorkerThread(decoders.get( queueinvokes % decoders.size() ));
queueinvokes++;
}
ws.getWorkerThread().put( ws );
}
private ByteBuffer takeBuffer() throws InterruptedException {
return buffers.take();
}
private void pushBuffer( ByteBuffer buf ) throws InterruptedException {
if( buffers.size() > queuesize.intValue() )
return;
buffers.put( buf );
}
private void handleIOException( SelectionKey key, WebSocket conn, IOException ex ) {
// onWebsocketError( conn, ex );// conn may be null here
if (key != null) {
key.cancel();
}
if( conn != null ) {
conn.closeConnection( CloseFrame.ABNORMAL_CLOSE, ex.getMessage() );
} else if( key != null ) {
SelectableChannel channel = key.channel();
if( channel != null && channel.isOpen() ) { // this could be the case if the IOException ex is a SSLException
try {
channel.close();
} catch ( IOException e ) {
// there is nothing that must be done here
}
log.trace("Connection closed because of exception",ex);
}
}
}
private void handleFatal( WebSocket conn, Exception e ) {
log.error( "Shutdown due to fatal error", e );
onError( conn, e );
//Shutting down WebSocketWorkers, see #222
if( decoders != null ) {
for( WebSocketWorker w : decoders ) {
w.interrupt();
}
}
if (selectorthread != null) {
selectorthread.interrupt();
}
try {
stop();
} catch ( IOException e1 ) {
log.error( "Error during shutdown", e1 );
onError( null, e1 );
} catch ( InterruptedException e1 ) {
Thread.currentThread().interrupt();
log.error( "Interrupt during stop", e );
onError( null, e1 );
}
}
@Override
public final void onWebsocketMessage( WebSocket conn, String message ) {
onMessage( conn, message );
}
@Override
public final void onWebsocketMessage( WebSocket conn, ByteBuffer blob ) {
onMessage( conn, blob );
}
@Override
public final void onWebsocketOpen( WebSocket conn, Handshakedata handshake ) {
if( addConnection( conn ) ) {
onOpen( conn, (ClientHandshake) handshake );
}
}
@Override
public final void onWebsocketClose( WebSocket conn, int code, String reason, boolean remote ) {
selector.wakeup();
try {
if( removeConnection( conn ) ) {
onClose( conn, code, reason, remote );
}
} finally {
try {
releaseBuffers( conn );
} catch ( InterruptedException e ) {
Thread.currentThread().interrupt();
}
}
}
/**
* This method performs remove operations on the connection and therefore also gives control over whether the operation shall be synchronized
* <p>
* {@link #WebSocketServer(InetSocketAddress, int, List, Collection)} allows to specify a collection which will be used to store current connections in.<br>
* Depending on the type on the connection, modifications of that collection may have to be synchronized.
* @param ws The Websocket connection which should be removed
* @return Removing connection successful
*/
protected boolean removeConnection( WebSocket ws ) {
boolean removed = false;
synchronized ( connections ) {
if (this.connections.contains( ws )) {
removed = this.connections.remove( ws );
} else {
//Don't throw an assert error if the ws is not in the list. e.g. when the other endpoint did not send any handshake. see #512
log.trace("Removing connection which is not in the connections collection! Possible no handshake recieved! {}", ws);
}
}
if( isclosed.get() && connections.isEmpty() ) {
selectorthread.interrupt();
}
return removed;
}
/**
* @see #removeConnection(WebSocket)
* @param ws the Websocket connection which should be added
* @return Adding connection successful
*/
protected boolean addConnection( WebSocket ws ) {
if( !isclosed.get() ) {
synchronized ( connections ) {
return this.connections.add( ws );
}
} else {
// This case will happen when a new connection gets ready while the server is already stopping.
ws.close( CloseFrame.GOING_AWAY );
return true;// for consistency sake we will make sure that both onOpen will be called
}
}
@Override
public final void onWebsocketError( WebSocket conn, Exception ex ) {
onError( conn, ex );
}
@Override
public final void onWriteDemand( WebSocket w ) {
WebSocketImpl conn = (WebSocketImpl) w;
try {
conn.getSelectionKey().interestOps( SelectionKey.OP_READ | SelectionKey.OP_WRITE );
} catch ( CancelledKeyException e ) {
// the thread which cancels key is responsible for possible cleanup
conn.outQueue.clear();
}
selector.wakeup();
}
@Override
public void onWebsocketCloseInitiated( WebSocket conn, int code, String reason ) {
onCloseInitiated( conn, code, reason );
}
@Override
public void onWebsocketClosing( WebSocket conn, int code, String reason, boolean remote ) {
onClosing( conn, code, reason, remote );
}
public void onCloseInitiated( WebSocket conn, int code, String reason ) {
}
public void onClosing( WebSocket conn, int code, String reason, boolean remote ) {
}
public final void setWebSocketFactory( WebSocketServerFactory wsf ) {
if (this.wsf != null)
this.wsf.close();
this.wsf = wsf;
}
public final WebSocketFactory getWebSocketFactory() {
return wsf;
}
/**
* Returns whether a new connection shall be accepted or not.<br>
* Therefore method is well suited to implement some kind of connection limitation.<br>
*
* @see #onOpen(WebSocket, ClientHandshake)
* @see #onWebsocketHandshakeReceivedAsServer(WebSocket, Draft, ClientHandshake)
* @param key the SelectionKey for the new connection
* @return Can this new connection be accepted
**/
protected boolean onConnect( SelectionKey key ) {
return true;
}
/**
* Getter to return the socket used by this specific connection
* @param conn The specific connection
* @return The socket used by this connection
*/
private Socket getSocket( WebSocket conn ) {
WebSocketImpl impl = (WebSocketImpl) conn;
return ( (SocketChannel) impl.getSelectionKey().channel() ).socket();
}
@Override
public InetSocketAddress getLocalSocketAddress( WebSocket conn ) {
return (InetSocketAddress) getSocket( conn ).getLocalSocketAddress();
}
@Override
public InetSocketAddress getRemoteSocketAddress( WebSocket conn ) {
return (InetSocketAddress) getSocket( conn ).getRemoteSocketAddress();
}
/** Called after an opening handshake has been performed and the given websocket is ready to be written on.
* @param conn The <tt>WebSocket</tt> instance this event is occuring on.
* @param handshake The handshake of the websocket instance
*/
public abstract void onOpen( WebSocket conn, ClientHandshake handshake );
/**
* Called after the websocket connection has been closed.
*
* @param conn The <tt>WebSocket</tt> instance this event is occuring on.
* @param code
* The codes can be looked up here: {@link CloseFrame}
* @param reason
* Additional information string
* @param remote
* Returns whether or not the closing of the connection was initiated by the remote host.
**/
public abstract void onClose( WebSocket conn, int code, String reason, boolean remote );
/**
* Callback for string messages received from the remote host
*
* @see #onMessage(WebSocket, ByteBuffer)
* @param conn The <tt>WebSocket</tt> instance this event is occuring on.
* @param message The UTF-8 decoded message that was received.
**/
public abstract void onMessage( WebSocket conn, String message );
/**
* Called when errors occurs. If an error causes the websocket connection to fail {@link #onClose(WebSocket, int, String, boolean)} will be called additionally.<br>
* This method will be called primarily because of IO or protocol errors.<br>
* If the given exception is an RuntimeException that probably means that you encountered a bug.<br>
*
* @param conn Can be null if there error does not belong to one specific websocket. For example if the servers port could not be bound.
* @param ex The exception causing this error
**/
public abstract void onError( WebSocket conn, Exception ex );
/**
* Called when the server started up successfully.
*
* If any error occured, onError is called instead.
*/
public abstract void onStart();
/**
* Callback for binary messages received from the remote host
*
* @see #onMessage(WebSocket, ByteBuffer)
*
* @param conn
* The <tt>WebSocket</tt> instance this event is occurring on.
* @param message
* The binary message that was received.
**/
public void onMessage( WebSocket conn, ByteBuffer message ) {
}
/**
* Send a text to all connected endpoints
* @param text the text to send to the endpoints
*/
public void broadcast(String text) {
broadcast( text, connections );
}
/**
* Send a byte array to all connected endpoints
* @param data the data to send to the endpoints
*/
public void broadcast(byte[] data) {
broadcast( data, connections );
}
/**
* Send a ByteBuffer to all connected endpoints
* @param data the data to send to the endpoints
*/
public void broadcast(ByteBuffer data) {
broadcast(data, connections);
}
/**
* Send a byte array to a specific collection of websocket connections
* @param data the data to send to the endpoints
* @param clients a collection of endpoints to whom the text has to be send
*/
public void broadcast(byte[] data, Collection<WebSocket> clients) {
if (data == null || clients == null) {
throw new IllegalArgumentException();
}
broadcast(ByteBuffer.wrap(data), clients);
}
/**
* Send a ByteBuffer to a specific collection of websocket connections
* @param data the data to send to the endpoints
* @param clients a collection of endpoints to whom the text has to be send
*/
public void broadcast(ByteBuffer data, Collection<WebSocket> clients) {
if (data == null || clients == null) {
throw new IllegalArgumentException();
}
doBroadcast(data, clients);
}
/**
* Send a text to a specific collection of websocket connections
* @param text the text to send to the endpoints
* @param clients a collection of endpoints to whom the text has to be send
*/
public void broadcast(String text, Collection<WebSocket> clients) {
if (text == null || clients == null) {
throw new IllegalArgumentException();
}
doBroadcast(text, clients);
}
/**
* Private method to cache all the frames to improve memory footprint and conversion time
* @param data the data to broadcast
* @param clients the clients to send the message to
*/
private void doBroadcast(Object data, Collection<WebSocket> clients) {
String sData = null;
if (data instanceof String) {
sData = (String)data;
}
ByteBuffer bData = null;
if (data instanceof ByteBuffer) {
bData = (ByteBuffer)data;
}
if (sData == null && bData == null) {
return;
}
Map<Draft, List<Framedata>> draftFrames = new HashMap<Draft, List<Framedata>>();
List<WebSocket> clientCopy;
synchronized (clients) {
clientCopy = new ArrayList<WebSocket>(clients);
}
for (WebSocket client : clientCopy) {
if (client != null) {
Draft draft = client.getDraft();
fillFrames(draft, draftFrames, sData, bData);
try {
client.sendFrame(draftFrames.get(draft));
} catch (WebsocketNotConnectedException e) {
//Ignore this exception in this case
}
}
}
}
/**
* Fills the draftFrames with new data for the broadcast
* @param draft The draft to use
* @param draftFrames The list of frames per draft to fill
* @param sData the string data, can be null
* @param bData the bytebuffer data, can be null
*/
private void fillFrames(Draft draft, Map<Draft, List<Framedata>> draftFrames, String sData, ByteBuffer bData) {
if( !draftFrames.containsKey( draft ) ) {
List<Framedata> frames = null;
if (sData != null) {
frames = draft.createFrames( sData, false );
}
if (bData != null) {
frames = draft.createFrames( bData, false );
}
if (frames != null) {
draftFrames.put(draft, frames);
}
}
}
/**
* This class is used to process incoming data
*/
public class WebSocketWorker extends Thread {
private BlockingQueue<WebSocketImpl> iqueue;
public WebSocketWorker() {
iqueue = new LinkedBlockingQueue<WebSocketImpl>();
setName( "WebSocketWorker-" + getId() );
setUncaughtExceptionHandler( new UncaughtExceptionHandler() {
@Override
public void uncaughtException( Thread t, Throwable e ) {
log.error("Uncaught exception in thread {}: {}", t.getName(), e);
}
} );
}
public void put( WebSocketImpl ws ) throws InterruptedException {
iqueue.put( ws );
}
@Override
public void run() {
WebSocketImpl ws = null;
try {
while ( true ) {
ByteBuffer buf;
ws = iqueue.take();
buf = ws.inQueue.poll();
assert ( buf != null );
doDecode(ws, buf);
ws = null;
}
} catch ( InterruptedException e ) {
Thread.currentThread().interrupt();
} catch ( RuntimeException e ) {
handleFatal( ws, e );
}
}
/**
* call ws.decode on the bytebuffer
* @param ws the Websocket
* @param buf the buffer to decode to
* @throws InterruptedException thrown by pushBuffer
*/
private void doDecode(WebSocketImpl ws, ByteBuffer buf) throws InterruptedException {
try {
ws.decode( buf );
} catch(Exception e){
log.error("Error while reading from remote connection", e);
}
finally {
pushBuffer( buf );
}
}
}
}
| Add "since 1.5.0" tag to new methods | src/main/java/org/java_websocket/server/WebSocketServer.java | Add "since 1.5.0" tag to new methods | <ide><path>rc/main/java/org/java_websocket/server/WebSocketServer.java
<ide> /**
<ide> * Attribute which allows you to configure the socket "backlog" parameter
<ide> * which determines how many client connections can be queued.
<add> * @since 1.5.0
<ide> */
<ide> private int maxPendingConnections = -1;
<ide>
<ide> * Set the requested maximum number of pending connections on the socket. The exact semantics are implementation
<ide> * specific. The value provided should be greater than 0. If it is less than or equal to 0, then
<ide> * an implementation specific default will be used. This option will be passed as "backlog" parameter to {@link ServerSocket#bind(SocketAddress, int)}
<add> * @since 1.5.0
<ide> */
<ide> public void setMaxPendingConnections(int numberOfConnections) {
<ide> maxPendingConnections = numberOfConnections;
<ide> * Returns the currently configured maximum number of pending connections.
<ide> *
<ide> * @see #setMaxPendingConnections(int)
<add> * @since 1.5.0
<ide> */
<ide> public int getMaxPendingConnections() {
<ide> return maxPendingConnections; |
|
Java | mit | 27711d707d7183b58a9c69f7170b34b2b1868619 | 0 | bpow/varitas,bpow/varitas,bpow/varitas | /* The MIT License
Copyright (c) 2010 Broad Institute.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/* Contact: Heng Li <[email protected]> */
package org.drpowell.grandannotator;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import net.sf.samtools.util.BlockCompressedInputStream;
public class TabixReader
{
public final String filename;
private BlockCompressedInputStream mFp;
private final int mPreset;
public final int sequenceColumn;
public final int beginColumn;
public final int endColumn;
public final int metaCharacter;
public final String meta;
public final int linesToSkip;
private final String[] mSeq;
private ArrayList<String> headers;
private final HashMap<String, Integer> mChr2tid;
private static int MAX_BIN = 37450;
private static int TAD_MIN_CHUNK_GAP = 32768;
private static int TAD_LIDX_SHIFT = 14;
private class TPair64 implements Comparable<TPair64> {
final long u;
final long v;
public TPair64(final long _u, final long _v) {
u = _u; v = _v;
}
public int compareTo(final TPair64 p) {
return u == p.u? 0 : ((u < p.u) ^ (u < 0) ^ (p.u < 0))? -1 : 1; // unsigned 64-bit comparison
}
};
private class TIndex {
HashMap<Integer, TPair64[]> b; // binning index
long[] l; // linear index
};
private TIndex[] mIndex;
private class TIntv {
Integer tid;
int beg, end;
};
private static boolean less64(final long u, final long v) { // unsigned 64-bit comparison
return (u < v) ^ (u < 0) ^ (v < 0);
}
/**
* The constructor which will use the default index (basename + ".tbi")
*
* @param filename File name of the data file
*/
public TabixReader(final String filename) throws IOException {
this(filename, filename+".tbi");
}
/**
* The constructor where a separate index file is specified.
*
* @param filename
* @param indexFileName
* @throws IOException
*/
public TabixReader(final String filename, final String indexFileName) throws IOException {
this.filename = filename;
mFp = new BlockCompressedInputStream(new File(filename));
BlockCompressedInputStream is = new BlockCompressedInputStream(new File(filename + ".tbi"));
// readIndex
byte[] buf = new byte[4];
is.read(buf, 0, 4); // read "TBI\1"
mSeq = new String[readInt(is)]; // # sequences
mChr2tid = new HashMap<String, Integer>();
mPreset = readInt(is);
sequenceColumn = readInt(is);
beginColumn = readInt(is);
endColumn = readInt(is);
metaCharacter = readInt(is);
meta = String.valueOf(metaCharacter);
linesToSkip = readInt(is);
// TODO - everything final has been assigned by now, could move the rest out of the constructor
// read sequence dictionary
int i, j, k, l = readInt(is);
buf = new byte[l];
is.read(buf);
for (i = j = k = 0; i < buf.length; ++i) {
if (buf[i] == 0) {
byte[] b = new byte[i - j];
System.arraycopy(buf, j, b, 0, b.length);
String s = new String(b);
mChr2tid.put(s, k);
mSeq[k++] = s;
j = i + 1;
}
}
// read the index
mIndex = new TIndex[mSeq.length];
for (i = 0; i < mSeq.length; ++i) {
// the binning index
int n_bin = readInt(is);
mIndex[i] = new TIndex();
mIndex[i].b = new HashMap<Integer, TPair64[]>();
for (j = 0; j < n_bin; ++j) {
int bin = readInt(is);
TPair64[] chunks = new TPair64[readInt(is)];
for (k = 0; k < chunks.length; ++k) {
long u = readLong(is);
long v = readLong(is);
chunks[k] = new TPair64(u, v); // in C, this is inefficient
}
mIndex[i].b.put(bin, chunks);
}
// the linear index
mIndex[i].l = new long[readInt(is)];
for (k = 0; k < mIndex[i].l.length; ++k)
mIndex[i].l[k] = readLong(is);
}
// close
is.close();
}
/**
* Calculates the bins that overlap a given region.
*
* Although this is an implementation detail, it may be more useful in general since the
* same binning index is used elsewhere (in bam files, for instance). Heng Li's reg2bin had
* used an int[37450] which was allocated for each query. While this results in more object
* allocations (for the ArrayList and Integer objects), it actually works faster (with my
* testing) for the common case where there are not many overlapped regions).
*
* @param beg Start coordinate (0 based, inclusive)
* @param end End coordinate (0 based, exclusive)
* @return A list of bins
*/
public static ArrayList<Integer> reg2bins(int beg, int end) {
if (beg >= end) { return new ArrayList<Integer>(0); }
// any given point will overlap 6 regions, go ahead and allocate a few extra spots by default
ArrayList<Integer> bins = new ArrayList<Integer>(8);
int k;
if (end >= 1<<29) end = 1<<29;
--end;
bins.add(0); // everything can overlap the 0th bin!
for (k = 1 + (beg>>26); k <= 1 + (end>>26); ++k) bins.add(k);
for (k = 9 + (beg>>23); k <= 9 + (end>>23); ++k) bins.add(k);
for (k = 73 + (beg>>20); k <= 73 + (end>>20); ++k) bins.add(k);
for (k = 585 + (beg>>17); k <= 585 + (end>>17); ++k) bins.add(k);
for (k = 4681 + (beg>>14); k <= 4681 + (end>>14); ++k) bins.add(k);
return bins;
}
public static int readInt(final InputStream is) throws IOException {
byte[] buf = new byte[4];
is.read(buf);
return ByteBuffer.wrap(buf).order(ByteOrder.LITTLE_ENDIAN).getInt();
}
public static long readLong(final InputStream is) throws IOException {
byte[] buf = new byte[8];
is.read(buf);
return ByteBuffer.wrap(buf).order(ByteOrder.LITTLE_ENDIAN).getLong();
}
/**
* Read one line from the data file.
*/
public String readLine() throws IOException {
return mFp.readLine();
}
public Integer getIdForChromosome(final String chromosome) {
return mChr2tid.get(chromosome);
}
/**
* Parse a region in the format of "chr1", "chr1:100" or "chr1:100-1000"
*
* @param reg Region string
* @return An array where the three elements are sequence_id,
* region_begin and region_end. On failure, sequence_id==-1.
*/
public int[] parseReg(final String reg) { // FIXME: NOT working when the sequence name contains : or -.
String chr;
int colon, hyphen;
int[] ret = new int[3];
colon = reg.lastIndexOf(':'); hyphen = reg.lastIndexOf('-');
chr = colon >= 0? reg.substring(0, colon) : reg;
ret[1] = colon >= 0? Integer.parseInt(reg.substring(colon+1, hyphen >= 0? hyphen : reg.length())) - 1 : 0;
ret[2] = hyphen >= 0? Integer.parseInt(reg.substring(hyphen+1)) : 0x7fffffff;
Integer tid = getIdForChromosome(chr);
ret[0] = tid == null? -1 : tid.intValue();
return ret;
}
private TIntv getIntv(final String s[]) {
TIntv intv = new TIntv();
intv.tid = getIdForChromosome(s[sequenceColumn-1]);
// begin
intv.beg = Integer.parseInt(s[beginColumn-1]);
intv.end = intv.beg;
if ((mPreset&0x10000) != 0) ++intv.end;
else --intv.beg;
if (intv.beg < 0) intv.beg = 0;
if (intv.end < 1) intv.end = 1;
if ((mPreset&0xffff) == 0) { // generic
intv.end = Integer.parseInt(s[endColumn-1]);
} else if ((mPreset&0xffff) == 1) { // SAM
String cigar = s[5];
int cigarLen = 0, i, j;
for (i = j = 0; i < cigar.length(); ++i) {
if (cigar.charAt(i) > '9') {
int op = cigar.charAt(i);
if (op == 'M' || op == 'D' || op == 'N')
cigarLen += Integer.parseInt(cigar.substring(j, i));
}
}
intv.end = intv.beg + cigarLen;
} else if ((mPreset&0xffff) == 2) { // VCF
String ref = s[3];
if (ref.length() > 0) intv.end = intv.beg + ref.length();
// check in the INFO field for an END
String info = s[7];
int endOffsetInInfo = -1;
if (info.startsWith("END=")) {
endOffsetInInfo = 4;
intv.end = Integer.parseInt(info.substring(endOffsetInInfo).split(";",2)[0]);
} else if ((endOffsetInInfo = info.indexOf(";END=")) > 0){
intv.end = Integer.parseInt(info.substring(endOffsetInInfo+5).split(";",2)[0]);
}
}
return intv;
}
public List<String> readHeaders() throws IOException {
if (headers == null) {
ArrayList<String> tmpHeaders = new ArrayList<String>(linesToSkip);
int skiplinesRemaining = linesToSkip;
mFp.seek(0);
String line;
while ((line = mFp.readLine()) != null) {
skiplinesRemaining--;
if (skiplinesRemaining >= 0 || line.charAt(0) == metaCharacter) {
tmpHeaders.add(line);
} else {
break;
}
}
headers = tmpHeaders;
}
return Collections.unmodifiableList(headers);
}
public class Iterator {
private int i, n_seeks;
private int tid, beg, end;
private TPair64[] off;
private long curr_off;
private boolean iseof;
public Iterator(final int _tid, final int _beg, final int _end, final TPair64[] _off) {
i = -1; n_seeks = 0; curr_off = 0; iseof = false;
off = _off; tid = _tid; beg = _beg; end = _end;
}
public String [] next() throws IOException {
if (iseof) return null;
for (;;) {
if (curr_off == 0 || !less64(curr_off, off[i].v)) { // then jump to the next chunk
if (i == off.length - 1) break; // no more chunks
if (i >= 0) assert(curr_off == off[i].v); // otherwise bug
if (i < 0 || off[i].v != off[i+1].u) { // not adjacent chunks; then seek
mFp.seek(off[i+1].u);
curr_off = mFp.getFilePointer();
++n_seeks;
}
++i;
}
String s;
if ((s = readLine()) != null) {
curr_off = mFp.getFilePointer();
if (s.length() == 0 || s.startsWith(meta)) continue;
String [] row = s.split("\t");
TIntv intv;
try {
intv = getIntv(row);
} catch (NumberFormatException nfe) {
nfe.printStackTrace();
System.err.println("Skipping...");
continue;
}
if (intv.tid != tid || intv.beg >= end) break; // no need to proceed
else if (intv.end > beg && intv.beg < end) return row; // overlap; return
} else break; // end of file
}
iseof = true;
return null;
}
};
public Iterator query(final int tid, final int beg, final int end) {
TPair64[] off, chunks;
long min_off;
TIndex idx = mIndex[tid];
List<Integer> bins = reg2bins(beg, end);
int i, l, n_off;
if (idx.l.length > 0)
min_off = (beg>>TAD_LIDX_SHIFT >= idx.l.length)? idx.l[idx.l.length-1] : idx.l[beg>>TAD_LIDX_SHIFT];
else min_off = 0;
ArrayList<TPair64> offList = new ArrayList<TPair64>();
for (Integer bin : bins) {
if ((chunks = idx.b.get(bin)) != null ) {
for (TPair64 chunk : chunks) {
if (less64(min_off, chunk.v)) offList.add(chunk);
}
}
}
if (offList.isEmpty()) return new Iterator(tid, beg, end, new TPair64[0]);
n_off = offList.size();
off = (TPair64 []) offList.toArray(new TPair64 [n_off]);
// resolve completely contained adjacent blocks
for (i = 1, l = 0; i < n_off; ++i) {
if (less64(off[l].v, off[i].v)) {
++l;
off[l] = off[i];
}
}
n_off = l + 1;
// resolve overlaps between adjacent blocks; this may happen due to the merge in indexing
for (i = 1; i < n_off; ++i)
if (!less64(off[i-1].v, off[i].u)) off[i-1] = new TPair64(off[i-1].u, off[i].u);
// merge adjacent blocks
for (i = 1, l = 0; i < n_off; ++i) {
if (off[l].v>>16 == off[i].u>>16) off[l] = new TPair64(off[l].u, off[i].v);
else {
++l;
off[l] = off[i];
}
}
n_off = l + 1;
// return
TPair64[] ret = Arrays.copyOf(off, n_off);
if (ret.length == 1 && ret[0] == null) ret = new TPair64[0]; // not sure how this would happen
return new TabixReader.Iterator(tid, beg, end, ret);
}
public Iterator query(final String reg) {
int[] x = parseReg(reg);
return query(x[0], x[1], x[2]);
}
public static String join(String [] strings, String delimiter) {
// the most-rewritten function in the java language
if (strings.length == 0) return "";
StringBuilder sb = new StringBuilder(strings[0]);
for (int i = 1; i < strings.length; i++) {
sb.append(delimiter).append(strings[i]);
}
return sb.toString();
}
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("Usage: java -cp .:sam.jar TabixReader <in.gz> [region]");
System.exit(1);
}
try {
TabixReader tr = new TabixReader(args[0]);
String s;
if (args.length == 1) { // no region is specified; print the whole file
while ((s = tr.readLine()) != null)
System.out.println(s);
} else { // a region is specified; random access
String [] row;
TabixReader.Iterator iter = tr.query(args[1]); // get the iterator
while (iter != null && (row = iter.next()) != null)
System.out.println(join(row, "\t"));
}
} catch (IOException e) {
}
}
}
| src/org/drpowell/grandannotator/TabixReader.java | /* The MIT License
Copyright (c) 2010 Broad Institute.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/* Contact: Heng Li <[email protected]> */
package org.drpowell.grandannotator;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import net.sf.samtools.util.BlockCompressedInputStream;
public class TabixReader
{
public final String filename;
private BlockCompressedInputStream mFp;
private final int mPreset;
public final int sequenceColumn;
public final int beginColumn;
public final int endColumn;
public final int metaCharacter;
public final String meta;
public final int linesToSkip;
private final String[] mSeq;
private ArrayList<String> headers;
private final HashMap<String, Integer> mChr2tid;
private static int MAX_BIN = 37450;
private static int TAD_MIN_CHUNK_GAP = 32768;
private static int TAD_LIDX_SHIFT = 14;
private class TPair64 implements Comparable<TPair64> {
final long u;
final long v;
public TPair64(final long _u, final long _v) {
u = _u; v = _v;
}
public int compareTo(final TPair64 p) {
return u == p.u? 0 : ((u < p.u) ^ (u < 0) ^ (p.u < 0))? -1 : 1; // unsigned 64-bit comparison
}
};
private class TIndex {
HashMap<Integer, TPair64[]> b; // binning index
long[] l; // linear index
};
private TIndex[] mIndex;
private class TIntv {
Integer tid;
int beg, end;
};
private static boolean less64(final long u, final long v) { // unsigned 64-bit comparison
return (u < v) ^ (u < 0) ^ (v < 0);
}
/**
* The constructor which will use the default index (basename + ".tbi")
*
* @param filename File name of the data file
*/
public TabixReader(final String filename) throws IOException {
this(filename, filename+".tbi");
}
/**
* The constructor where a separate index file is specified.
*
* @param filename
* @param indexFileName
* @throws IOException
*/
public TabixReader(final String filename, final String indexFileName) throws IOException {
this.filename = filename;
mFp = new BlockCompressedInputStream(new File(filename));
BlockCompressedInputStream is = new BlockCompressedInputStream(new File(filename + ".tbi"));
// readIndex
byte[] buf = new byte[4];
is.read(buf, 0, 4); // read "TBI\1"
mSeq = new String[readInt(is)]; // # sequences
mChr2tid = new HashMap<String, Integer>();
mPreset = readInt(is);
sequenceColumn = readInt(is);
beginColumn = readInt(is);
endColumn = readInt(is);
metaCharacter = readInt(is);
meta = String.valueOf(metaCharacter);
linesToSkip = readInt(is);
// TODO - everything final has been assigned by now, could move the rest out of the constructor
// read sequence dictionary
int i, j, k, l = readInt(is);
buf = new byte[l];
is.read(buf);
for (i = j = k = 0; i < buf.length; ++i) {
if (buf[i] == 0) {
byte[] b = new byte[i - j];
System.arraycopy(buf, j, b, 0, b.length);
String s = new String(b);
mChr2tid.put(s, k);
mSeq[k++] = s;
j = i + 1;
}
}
// read the index
mIndex = new TIndex[mSeq.length];
for (i = 0; i < mSeq.length; ++i) {
// the binning index
int n_bin = readInt(is);
mIndex[i] = new TIndex();
mIndex[i].b = new HashMap<Integer, TPair64[]>();
for (j = 0; j < n_bin; ++j) {
int bin = readInt(is);
TPair64[] chunks = new TPair64[readInt(is)];
for (k = 0; k < chunks.length; ++k) {
long u = readLong(is);
long v = readLong(is);
chunks[k] = new TPair64(u, v); // in C, this is inefficient
}
mIndex[i].b.put(bin, chunks);
}
// the linear index
mIndex[i].l = new long[readInt(is)];
for (k = 0; k < mIndex[i].l.length; ++k)
mIndex[i].l[k] = readLong(is);
}
// close
is.close();
}
/**
* Calculates the bins that overlap a given region.
*
* Although this is an implementation detail, it may be more useful in general since the
* same binning index is used elsewhere (in bam files, for instance). Heng Li's reg2bin had
* used an int[37450] which was allocated for each query. While this results in more object
* allocations (for the ArrayList and Integer objects), it actually works faster (with my
* testing) for the common case where there are not many overlapped regions).
*
* @param beg Start coordinate (0 based, inclusive)
* @param end End coordinate (0 based, exclusive)
* @return A list of bins
*/
public static ArrayList<Integer> reg2bins(int beg, int end) {
if (beg >= end) { return new ArrayList<Integer>(0); }
// any given point will overlap 6 regions, go ahead and allocate a few extra spots by default
ArrayList<Integer> bins = new ArrayList<Integer>(8);
int k;
if (end >= 1<<29) end = 1<<29;
--end;
bins.add(0); // everything can overlap the 0th bin!
for (k = 1 + (beg>>26); k <= 1 + (end>>26); ++k) bins.add(k);
for (k = 9 + (beg>>23); k <= 9 + (end>>23); ++k) bins.add(k);
for (k = 73 + (beg>>20); k <= 73 + (end>>20); ++k) bins.add(k);
for (k = 585 + (beg>>17); k <= 585 + (end>>17); ++k) bins.add(k);
for (k = 4681 + (beg>>14); k <= 4681 + (end>>14); ++k) bins.add(k);
return bins;
}
public static int readInt(final InputStream is) throws IOException {
byte[] buf = new byte[4];
is.read(buf);
return ByteBuffer.wrap(buf).order(ByteOrder.LITTLE_ENDIAN).getInt();
}
public static long readLong(final InputStream is) throws IOException {
byte[] buf = new byte[8];
is.read(buf);
return ByteBuffer.wrap(buf).order(ByteOrder.LITTLE_ENDIAN).getLong();
}
/**
* Read one line from the data file.
*/
public String readLine() throws IOException {
return mFp.readLine();
}
public Integer getIdForChromosome(final String chromosome) {
return mChr2tid.get(chromosome);
}
/**
* Parse a region in the format of "chr1", "chr1:100" or "chr1:100-1000"
*
* @param reg Region string
* @return An array where the three elements are sequence_id,
* region_begin and region_end. On failure, sequence_id==-1.
*/
public int[] parseReg(final String reg) { // FIXME: NOT working when the sequence name contains : or -.
String chr;
int colon, hyphen;
int[] ret = new int[3];
colon = reg.lastIndexOf(':'); hyphen = reg.lastIndexOf('-');
chr = colon >= 0? reg.substring(0, colon) : reg;
ret[1] = colon >= 0? Integer.parseInt(reg.substring(colon+1, hyphen >= 0? hyphen : reg.length())) - 1 : 0;
ret[2] = hyphen >= 0? Integer.parseInt(reg.substring(hyphen+1)) : 0x7fffffff;
Integer tid = getIdForChromosome(chr);
ret[0] = tid == null? -1 : tid.intValue();
return ret;
}
private TIntv getIntv(final String s[]) {
TIntv intv = new TIntv();
intv.tid = getIdForChromosome(s[sequenceColumn-1]);
// begin
intv.beg = Integer.parseInt(s[beginColumn-1]);
intv.end = intv.beg;
if ((mPreset&0x10000) != 0) ++intv.end;
else --intv.beg;
if (intv.beg < 0) intv.beg = 0;
if (intv.end < 1) intv.end = 1;
if ((mPreset&0xffff) == 0) { // generic
intv.end = Integer.parseInt(s[endColumn-1]);
} else if ((mPreset&0xffff) == 1) { // SAM
String cigar = s[5];
int cigarLen = 0, i, j;
for (i = j = 0; i < cigar.length(); ++i) {
if (cigar.charAt(i) > '9') {
int op = cigar.charAt(i);
if (op == 'M' || op == 'D' || op == 'N')
cigarLen += Integer.parseInt(cigar.substring(j, i));
}
}
intv.end = intv.beg + cigarLen;
} else if ((mPreset&0xffff) == 2) { // VCF
String ref = s[3];
if (ref.length() > 0) intv.end = intv.beg + ref.length();
// check in the INFO field for an END
String info = s[7];
int endOffsetInInfo = -1;
if (info.startsWith("END=")) {
endOffsetInInfo = 4;
intv.end = Integer.parseInt(info.substring(endOffsetInInfo).split(";",2)[0]);
} else if ((endOffsetInInfo = info.indexOf(";END=")) > 0){
intv.end = Integer.parseInt(info.substring(endOffsetInInfo+5).split(";",2)[0]);
}
}
return intv;
}
public List<String> readHeaders() throws IOException {
if (headers == null) {
ArrayList<String> tmpHeaders = new ArrayList<String>(linesToSkip);
int skiplinesRemaining = linesToSkip;
mFp.seek(0);
String line;
while ((line = mFp.readLine()) != null) {
skiplinesRemaining--;
if (skiplinesRemaining >= 0 || line.charAt(0) == metaCharacter) {
tmpHeaders.add(line);
} else {
break;
}
}
headers = tmpHeaders;
}
return Collections.unmodifiableList(headers);
}
public class Iterator {
private int i, n_seeks;
private int tid, beg, end;
private TPair64[] off;
private long curr_off;
private boolean iseof;
public Iterator(final int _tid, final int _beg, final int _end, final TPair64[] _off) {
i = -1; n_seeks = 0; curr_off = 0; iseof = false;
off = _off; tid = _tid; beg = _beg; end = _end;
}
public String [] next() throws IOException {
if (iseof) return null;
for (;;) {
if (curr_off == 0 || !less64(curr_off, off[i].v)) { // then jump to the next chunk
if (i == off.length - 1) break; // no more chunks
if (i >= 0) assert(curr_off == off[i].v); // otherwise bug
if (i < 0 || off[i].v != off[i+1].u) { // not adjacent chunks; then seek
mFp.seek(off[i+1].u);
curr_off = mFp.getFilePointer();
++n_seeks;
}
++i;
}
String s;
if ((s = readLine()) != null) {
curr_off = mFp.getFilePointer();
if (s.length() == 0 || s.startsWith(meta)) continue;
String [] row = s.split("\t");
TIntv intv;
intv = getIntv(row);
if (intv.tid != tid || intv.beg >= end) break; // no need to proceed
else if (intv.end > beg && intv.beg < end) return row; // overlap; return
} else break; // end of file
}
iseof = true;
return null;
}
};
public Iterator query(final int tid, final int beg, final int end) {
TPair64[] off, chunks;
long min_off;
TIndex idx = mIndex[tid];
List<Integer> bins = reg2bins(beg, end);
int i, l, n_off;
if (idx.l.length > 0)
min_off = (beg>>TAD_LIDX_SHIFT >= idx.l.length)? idx.l[idx.l.length-1] : idx.l[beg>>TAD_LIDX_SHIFT];
else min_off = 0;
ArrayList<TPair64> offList = new ArrayList<TPair64>();
for (Integer bin : bins) {
if ((chunks = idx.b.get(bin)) != null ) {
for (TPair64 chunk : chunks) {
if (less64(min_off, chunk.v)) offList.add(chunk);
}
}
}
if (offList.isEmpty()) return new Iterator(tid, beg, end, new TPair64[0]);
n_off = offList.size();
off = (TPair64 []) offList.toArray(new TPair64 [n_off]);
// resolve completely contained adjacent blocks
for (i = 1, l = 0; i < n_off; ++i) {
if (less64(off[l].v, off[i].v)) {
++l;
off[l] = off[i];
}
}
n_off = l + 1;
// resolve overlaps between adjacent blocks; this may happen due to the merge in indexing
for (i = 1; i < n_off; ++i)
if (!less64(off[i-1].v, off[i].u)) off[i-1] = new TPair64(off[i-1].u, off[i].u);
// merge adjacent blocks
for (i = 1, l = 0; i < n_off; ++i) {
if (off[l].v>>16 == off[i].u>>16) off[l] = new TPair64(off[l].u, off[i].v);
else {
++l;
off[l] = off[i];
}
}
n_off = l + 1;
// return
TPair64[] ret = Arrays.copyOf(off, n_off);
if (ret.length == 1 && ret[0] == null) ret = new TPair64[0]; // not sure how this would happen
return new TabixReader.Iterator(tid, beg, end, ret);
}
public Iterator query(final String reg) {
int[] x = parseReg(reg);
return query(x[0], x[1], x[2]);
}
public static String join(String [] strings, String delimiter) {
// the most-rewritten function in the java language
if (strings.length == 0) return "";
StringBuilder sb = new StringBuilder(strings[0]);
for (int i = 1; i < strings.length; i++) {
sb.append(delimiter).append(strings[i]);
}
return sb.toString();
}
public static void main(String[] args) {
if (args.length < 1) {
System.out.println("Usage: java -cp .:sam.jar TabixReader <in.gz> [region]");
System.exit(1);
}
try {
TabixReader tr = new TabixReader(args[0]);
String s;
if (args.length == 1) { // no region is specified; print the whole file
while ((s = tr.readLine()) != null)
System.out.println(s);
} else { // a region is specified; random access
String [] row;
TabixReader.Iterator iter = tr.query(args[1]); // get the iterator
while (iter != null && (row = iter.next()) != null)
System.out.println(join(row, "\t"));
}
} catch (IOException e) {
}
}
}
| catch NumberFormatException (for dbNSFP, which gives "NA" for some hg19 coordinates
| src/org/drpowell/grandannotator/TabixReader.java | catch NumberFormatException (for dbNSFP, which gives "NA" for some hg19 coordinates | <ide><path>rc/org/drpowell/grandannotator/TabixReader.java
<ide> if (s.length() == 0 || s.startsWith(meta)) continue;
<ide> String [] row = s.split("\t");
<ide> TIntv intv;
<del> intv = getIntv(row);
<add> try {
<add> intv = getIntv(row);
<add> } catch (NumberFormatException nfe) {
<add> nfe.printStackTrace();
<add> System.err.println("Skipping...");
<add> continue;
<add> }
<ide> if (intv.tid != tid || intv.beg >= end) break; // no need to proceed
<ide> else if (intv.end > beg && intv.beg < end) return row; // overlap; return
<ide> } else break; // end of file |
|
Java | apache-2.0 | f668dbe17064c0d177413ce01655b4233fefe739 | 0 | cpollet/itinerants,cpollet/itinerants,cpollet/itinerants,cpollet/itinerants,cpollet/itinerants | package net.cpollet.itinerants.web.rest.resource;
import lombok.extern.slf4j.Slf4j;
import net.cpollet.itinerants.core.domain.Person;
import net.cpollet.itinerants.core.service.PersonService;
import net.cpollet.itinerants.web.authentication.AuthenticationPrincipal;
import net.cpollet.itinerants.web.authentication.TokenService;
import net.cpollet.itinerants.web.rest.data.LoginPayload;
import net.cpollet.itinerants.web.rest.data.LoginResponse;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.UUID;
import java.util.stream.Collectors;
/**
* Created by cpollet on 14.03.17.
*/
@RestController
@RequestMapping("/sessions")
@Slf4j
public class SessionController {
private final TokenService tokenService;
private final PersonService personService;
public SessionController(TokenService tokenService, PersonService personService) {
this.tokenService = tokenService;
this.personService = personService;
}
@PutMapping(value = "")
public ResponseEntity<LoginResponse> create(@RequestBody LoginPayload credentials) {
log.info("Creating session for username={}", credentials.getUsername());
Person person = personService.getByUsername(credentials.getUsername());
if (person == null) {
return new ResponseEntity<>(LoginResponse.INVALID_CREDENTIALS, HttpStatus.UNAUTHORIZED);
}
if (!person.password().matches(credentials.getPassword())) {
return new ResponseEntity<>(LoginResponse.INVALID_CREDENTIALS, HttpStatus.UNAUTHORIZED);
}
String token = UUID.randomUUID().toString();
Authentication authentication = new UsernamePasswordAuthenticationToken(
new AuthenticationPrincipal(credentials.getUsername(), person.id()),
credentials.getPassword(),
person.roles().stream()
.map(r -> new SimpleGrantedAuthority("ROLE_" + r.toUpperCase()))
.collect(Collectors.toList())
);
tokenService.store(token, authentication);
return new ResponseEntity<>(new LoginResponse(token, person.id(), person.roles()), HttpStatus.OK);
}
}
| webservice/web/src/main/java/net/cpollet/itinerants/web/rest/resource/SessionController.java | package net.cpollet.itinerants.web.rest.resource;
import lombok.extern.slf4j.Slf4j;
import net.cpollet.itinerants.core.domain.Person;
import net.cpollet.itinerants.core.service.PersonService;
import net.cpollet.itinerants.web.authentication.AuthenticationPrincipal;
import net.cpollet.itinerants.web.authentication.TokenService;
import net.cpollet.itinerants.web.rest.data.LoginPayload;
import net.cpollet.itinerants.web.rest.data.LoginResponse;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.UUID;
import java.util.stream.Collectors;
/**
* Created by cpollet on 14.03.17.
*/
@RestController
@RequestMapping("/sessions")
@Slf4j
public class SessionController {
private final TokenService tokenService;
private final PersonService personService;
public SessionController(TokenService tokenService, PersonService personService) {
this.tokenService = tokenService;
this.personService = personService;
}
@PutMapping(value = "")
public ResponseEntity<LoginResponse> create(@RequestBody LoginPayload credentials) {
log.info("Creating session for {}", credentials.getUsername());
Person person = personService.getByUsername(credentials.getUsername());
if (person == null) {
return new ResponseEntity<>(LoginResponse.INVALID_CREDENTIALS, HttpStatus.UNAUTHORIZED);
}
if (!person.password().matches(credentials.getPassword())) {
return new ResponseEntity<>(LoginResponse.INVALID_CREDENTIALS, HttpStatus.UNAUTHORIZED);
}
String token = UUID.randomUUID().toString();
Authentication authentication = new UsernamePasswordAuthenticationToken(
new AuthenticationPrincipal(credentials.getUsername(), person.id()),
credentials.getPassword(),
person.roles().stream()
.map(r -> new SimpleGrantedAuthority("ROLE_" + r.toUpperCase()))
.collect(Collectors.toList())
);
tokenService.store(token, authentication);
return new ResponseEntity<>(new LoginResponse(token, person.id(), person.roles()), HttpStatus.OK);
}
}
| Better logging
| webservice/web/src/main/java/net/cpollet/itinerants/web/rest/resource/SessionController.java | Better logging | <ide><path>ebservice/web/src/main/java/net/cpollet/itinerants/web/rest/resource/SessionController.java
<ide>
<ide> @PutMapping(value = "")
<ide> public ResponseEntity<LoginResponse> create(@RequestBody LoginPayload credentials) {
<del> log.info("Creating session for {}", credentials.getUsername());
<add> log.info("Creating session for username={}", credentials.getUsername());
<ide> Person person = personService.getByUsername(credentials.getUsername());
<ide>
<ide> if (person == null) { |
|
Java | apache-2.0 | f89ac63104ac0b8e8dfbfffb65e4fef6f74af593 | 0 | jinahya/simple-file-front | /*
* Copyright 2014 Jin Kwon.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.jinahya.simple.file.front;
import com.github.jinahya.simple.file.back.DefaultFileContext;
import com.github.jinahya.simple.file.back.FileBack;
import com.github.jinahya.simple.file.back.FileBackException;
import com.github.jinahya.simple.file.back.FileContext;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import static java.lang.invoke.MethodHandles.lookup;
import java.net.URI;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.util.List;
import java.util.Optional;
import javax.annotation.PreDestroy;
import javax.inject.Inject;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.ProcessingException;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.StreamingOutput;
import javax.ws.rs.core.UriInfo;
import org.glassfish.jersey.client.ClientProperties;
import org.slf4j.Logger;
import static org.slf4j.LoggerFactory.getLogger;
/**
*
* @author Jin Kwon <jinahya_at_gmail.com>
*/
@Path("locators")
public class LocatorsResource {
private static final String PROPERTY_PREFIX
= "http://jinahya.github.com/simple/file/front";
private static final String PROPERTY_TEMP_PATH
= PROPERTY_PREFIX + "/temp_path";
private static final String PROPERTY_MEDIA_TYPE
= PROPERTY_PREFIX + "/media_type";
public static void updateSingleDistribute(final FileContext fileContext,
final UriInfo uriInfo,
final List<URI> fileFronts) {
final Logger logger = getLogger(lookup().lookupClass());
final URI baseUri = uriInfo.getBaseUri();
logger.debug("baseUri: {}", baseUri);
final String path = uriInfo.getPath();
logger.debug("path: {}", path);
final java.nio.file.Path tempPath = fileContext.property(
PROPERTY_TEMP_PATH, java.nio.file.Path.class).orElse(null);
logger.debug("tempPath: {}", tempPath);
if (tempPath == null) {
logger.error("no tempPath supplied");
return;
}
final MediaType mediaType = fileContext.property(
PROPERTY_MEDIA_TYPE, MediaType.class)
.orElse(MediaType.APPLICATION_OCTET_STREAM_TYPE);
logger.debug("mediaType: {}", mediaType);
for (final URI fileFront : fileFronts) {
if (baseUri.equals(fileFront)) {
logger.debug("skipping self: " + fileFront);
continue;
}
final Client client = ClientBuilder.newClient();
WebTarget target = client.target(fileFront).path(path)
.queryParam("distribute", Boolean.FALSE.toString());
final String suffix = Optional.ofNullable(
fileContext.fileSuffixSupplier()).orElse(() -> null)
.get();
if (suffix != null && !suffix.trim().isEmpty()) {
target = target.queryParam("suffix", suffix);
}
logger.debug("target: {}", target.getUri().toString());
try {
final Entity<File> entity
= Entity.entity(tempPath.toFile(), mediaType);
final Response response = target.request().put(entity);
logger.debug("status: {}", response.getStatusInfo());
} catch (ProcessingException pe) {
logger.error("failed to distribute to " + fileFront, pe);
}
}
}
public static void deleteSingleDistribute(final FileContext fileContext,
final UriInfo uriInfo,
final List<URI> fileFronts) {
final Logger logger = getLogger(lookup().lookupClass());
final URI baseUri = uriInfo.getBaseUri();
logger.debug("baseUri: {}", baseUri);
final String path = uriInfo.getPath();
logger.debug("path: {}", path);
for (final URI fileFront : fileFronts) {
if (baseUri.equals(fileFront)) {
logger.debug("skipping self: " + fileFront);
continue;
}
final Client client = ClientBuilder.newClient()
.property(ClientProperties.CONNECT_TIMEOUT, 1000)
.property(ClientProperties.READ_TIMEOUT, 1000);
WebTarget target = client.target(fileFront).path(path)
.queryParam("distribute", Boolean.FALSE.toString());
final String suffix = Optional.ofNullable(
fileContext.fileSuffixSupplier()).orElse(() -> null)
.get();
if (suffix != null && !suffix.trim().isEmpty()) {
target = target.queryParam("suffix", suffix);
}
logger.debug("target: {}", target.getUri().toString());
try {
final Response response = target.request().delete();
logger.debug("status: {}", response.getStatusInfo());
} catch (final ProcessingException pe) {
logger.error("failed to distribute to " + fileFront, pe);
}
}
}
@PreDestroy
public void preDestoy() {
if (tempPath != null) {
try {
Files.deleteIfExists(tempPath);
} catch (final IOException ioe) {
logger.error("failed to delete tempPath: " + tempPath, ioe);
}
}
}
/**
* Reads file content mapped to specified {@code locator}.
*
* @param locator the locator of file.
* @param suffix an optional file name suffix
*
* @return a response.
*/
@Produces(MediaType.WILDCARD)
@GET
@Path("{locator: .+}")
public Response readSingle(
@PathParam("locator") final String locator,
@QueryParam("suffix") final String suffix) {
final FileContext fileContext = new DefaultFileContext();
fileContext.keyBufferSupplier(
() -> ByteBuffer.wrap(locator.getBytes(StandardCharsets.UTF_8)));
if (suffix != null && !suffix.trim().isEmpty()) {
fileContext.fileSuffixSupplier(() -> suffix.trim());
}
fileContext.targetChannelSupplier(() -> {
try {
tempPath = Files.createTempFile("prefix", "suffix");
return FileChannel.open(tempPath, StandardOpenOption.READ,
StandardOpenOption.WRITE);
} catch (final IOException ioe) {
throw new RuntimeException(ioe);
}
});
final Holder<Long> targetCopiedHolder = new Holder<>(-1L);
fileContext.targetCopiedConsumer(targetCopied -> {
targetCopiedHolder.value(targetCopied);
});
final Holder<String> pathNameHolder = new Holder<>();
fileContext.pathNameConsumer(pathName -> {
pathNameHolder.value(pathName);
});
try {
fileBack.read(fileContext);
} catch (final IOException | FileBackException e) {
throw new WebApplicationException(e);
}
if (targetCopiedHolder.value() < 0L) {
throw new NotFoundException();
}
return Response.ok((StreamingOutput) output -> {
Files.copy(tempPath, output);
})
.header("Content-Length", targetCopiedHolder.value())
.header(FileFrontConstants.HEADER_PATH_NAME, pathNameHolder.value())
.build();
}
/**
* Updates a file content located by specified {@code locator}.
*
* @param locator the locator of file.
* @param suffix file suffix
* @param distribute a flag for distributing to siblings.
* @param entity
*
* @return a response.
*/
@Consumes(MediaType.WILDCARD)
@PUT
@Path("{locator: .+}")
public Response updateSingle(
@PathParam("locator") final String locator,
@QueryParam("suffix") final String suffix,
@QueryParam("distribute")
@DefaultValue("true") final boolean distribute,
final InputStream entity) {
final FileContext fileContext = new DefaultFileContext();
fileContext.keyBufferSupplier(
() -> ByteBuffer.wrap(locator.getBytes(StandardCharsets.UTF_8)));
if (suffix != null && !suffix.trim().isEmpty()) {
fileContext.fileSuffixSupplier(() -> suffix.trim());
}
final Holder<String> pathNameHolder = new Holder<>();
fileContext.pathNameConsumer(pathName -> {
pathNameHolder.value(pathName);
});
try {
tempPath = Files.createTempFile("prefix", "suffix");
Files.copy(entity, tempPath, StandardCopyOption.REPLACE_EXISTING);
} catch (final IOException ioe) {
throw new WebApplicationException(ioe);
}
fileContext.sourceChannelSupplier(() -> {
try {
return FileChannel.open(tempPath, StandardOpenOption.READ);
} catch (final IOException ioe) {
throw new RuntimeException(ioe);
}
});
final Holder<Long> sourceCopiedHolder = new Holder<>();
fileContext.sourceCopiedConsumer(
sourceCopied -> sourceCopiedHolder.value(sourceCopied)
);
try {
fileBack.update(fileContext);
} catch (IOException | FileBackException e) {
logger.error("failed to write", e);
throw new WebApplicationException(e); // 500
}
if (distribute) {
logger.debug("distrubuting...");
fileContext.property(PROPERTY_TEMP_PATH, tempPath);
fileContext.property(PROPERTY_MEDIA_TYPE, contentType);
updateSingleDistribute(fileContext, uriInfo, fileFronts);
}
return Response.noContent().build();
}
/**
* Deletes a file content located by given {@code locator}.
*
* @param locator the file locator
* @param suffix an optional file name suffix such as "png" or "txt"
* @param distribute
*
* @return response
*/
@DELETE
@Path("{locator: .+}")
public Response deleteSingle(
@PathParam("locator") final String locator,
@QueryParam("suffix") final String suffix,
@QueryParam("distribute") @DefaultValue("true")
final boolean distribute) {
final FileContext fileContext = new DefaultFileContext();
fileContext.keyBufferSupplier(
() -> ByteBuffer.wrap(locator.getBytes(StandardCharsets.UTF_8)));
if (suffix != null && !suffix.trim().isEmpty()) {
fileContext.fileSuffixSupplier(() -> suffix.trim());
}
try {
fileBack.delete(fileContext);
} catch (IOException | FileBackException e) {
logger.error("failed to delete", e);
throw new WebApplicationException(e);
}
if (distribute) {
logger.debug("distributing..");
deleteSingleDistribute(fileContext, uriInfo, fileFronts);
}
return Response.noContent().build();
}
private transient final Logger logger = getLogger(getClass());
private transient java.nio.file.Path tempPath;
/**
* A file back injected.
*/
@Inject
@Backing
private FileBack fileBack;
/**
* A list of sibling file fronts to distribute files and commands.
*/
@Inject
@Siblings
private List<URI> fileFronts;
@Context
private UriInfo uriInfo;
@HeaderParam("Content-Type")
private MediaType contentType;
}
| src/main/java/com/github/jinahya/simple/file/front/LocatorsResource.java | /*
* Copyright 2014 Jin Kwon.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.jinahya.simple.file.front;
import com.github.jinahya.simple.file.back.DefaultFileContext;
import com.github.jinahya.simple.file.back.FileBack;
import com.github.jinahya.simple.file.back.FileBackException;
import com.github.jinahya.simple.file.back.FileContext;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import static java.lang.invoke.MethodHandles.lookup;
import java.net.URI;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.util.List;
import java.util.Optional;
import javax.annotation.PreDestroy;
import javax.inject.Inject;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.NotFoundException;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.ProcessingException;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.StreamingOutput;
import javax.ws.rs.core.UriInfo;
import org.glassfish.jersey.client.ClientProperties;
import org.slf4j.Logger;
import static org.slf4j.LoggerFactory.getLogger;
/**
*
* @author Jin Kwon <jinahya_at_gmail.com>
*/
@Path("/locators")
public class LocatorsResource {
private static final String PROPERTY_PREFIX
= "http://jinahya.github.com/simple/file/front";
private static final String PROPERTY_TEMP_PATH
= PROPERTY_PREFIX + "/temp_path";
private static final String PROPERTY_MEDIA_TYPE
= PROPERTY_PREFIX + "/media_type";
public static void updateSingleDistribute(final FileContext fileContext,
final UriInfo uriInfo,
final List<URI> fileFronts) {
final Logger logger = getLogger(lookup().lookupClass());
final URI baseUri = uriInfo.getBaseUri();
logger.debug("baseUri: {}", baseUri);
final String path = uriInfo.getPath();
logger.debug("path: {}", path);
final java.nio.file.Path tempPath = fileContext.property(
PROPERTY_TEMP_PATH, java.nio.file.Path.class).orElse(null);
logger.debug("tempPath: {}", tempPath);
if (tempPath == null) {
logger.error("no tempPath supplied");
return;
}
final MediaType mediaType = fileContext.property(
PROPERTY_MEDIA_TYPE, MediaType.class)
.orElse(MediaType.APPLICATION_OCTET_STREAM_TYPE);
logger.debug("mediaType: {}", mediaType);
for (final URI fileFront : fileFronts) {
if (baseUri.equals(fileFront)) {
logger.debug("skipping self: " + fileFront);
continue;
}
final Client client = ClientBuilder.newClient();
WebTarget target = client.target(fileFront).path(path)
.queryParam("distribute", Boolean.FALSE.toString());
final String suffix = Optional.ofNullable(
fileContext.fileSuffixSupplier()).orElse(() -> null)
.get();
if (suffix != null && !suffix.trim().isEmpty()) {
target = target.queryParam("suffix", suffix);
}
logger.debug("target: {}", target.getUri().toString());
try {
final Entity<File> entity
= Entity.entity(tempPath.toFile(), mediaType);
final Response response = target.request().put(entity);
logger.debug("status: {}", response.getStatusInfo());
} catch (ProcessingException pe) {
logger.error("failed to distribute to " + fileFront, pe);
}
}
}
public static void deleteSingleDistribute(final FileContext fileContext,
final UriInfo uriInfo,
final List<URI> fileFronts) {
final Logger logger = getLogger(lookup().lookupClass());
final URI baseUri = uriInfo.getBaseUri();
logger.debug("baseUri: {}", baseUri);
final String path = uriInfo.getPath();
logger.debug("path: {}", path);
for (final URI fileFront : fileFronts) {
if (baseUri.equals(fileFront)) {
logger.debug("skipping self: " + fileFront);
continue;
}
final Client client = ClientBuilder.newClient()
.property(ClientProperties.CONNECT_TIMEOUT, 1000)
.property(ClientProperties.READ_TIMEOUT, 1000);
WebTarget target = client.target(fileFront).path(path)
.queryParam("distribute", Boolean.FALSE.toString());
final String suffix = Optional.ofNullable(
fileContext.fileSuffixSupplier()).orElse(() -> null)
.get();
if (suffix != null && !suffix.trim().isEmpty()) {
target = target.queryParam("suffix", suffix);
}
logger.debug("target: {}", target.getUri().toString());
try {
final Response response = target.request().delete();
logger.debug("status: {}", response.getStatusInfo());
} catch (final ProcessingException pe) {
logger.error("failed to distribute to " + fileFront, pe);
}
}
}
@PreDestroy
public void preDestoy() {
if (tempPath != null) {
try {
Files.deleteIfExists(tempPath);
} catch (final IOException ioe) {
logger.error("failed to delete tempPath: " + tempPath, ioe);
}
}
}
/**
* Reads file content mapped to specified {@code locator}.
*
* @param locator the locator of file.
* @param suffix an optional file name suffix
*
* @return a response.
*/
@Produces(MediaType.WILDCARD)
@GET
@Path("/{locator: .+}")
public Response readSingle(
@PathParam("locator") final String locator,
@QueryParam("suffix") final String suffix) {
final FileContext fileContext = new DefaultFileContext();
fileContext.keyBufferSupplier(
() -> ByteBuffer.wrap(locator.getBytes(StandardCharsets.UTF_8)));
if (suffix != null && !suffix.trim().isEmpty()) {
fileContext.fileSuffixSupplier(() -> suffix.trim());
}
fileContext.targetChannelSupplier(() -> {
try {
tempPath = Files.createTempFile("prefix", "suffix");
return FileChannel.open(tempPath, StandardOpenOption.READ,
StandardOpenOption.WRITE);
} catch (final IOException ioe) {
throw new RuntimeException(ioe);
}
});
final Holder<Long> targetCopiedHolder = new Holder<>(-1L);
fileContext.targetCopiedConsumer(targetCopied -> {
targetCopiedHolder.value(targetCopied);
});
final Holder<String> pathNameHolder = new Holder<>();
fileContext.pathNameConsumer(pathName -> {
pathNameHolder.value(pathName);
});
try {
fileBack.read(fileContext);
} catch (final IOException | FileBackException e) {
throw new WebApplicationException(e);
}
if (targetCopiedHolder.value() < 0L) {
throw new NotFoundException();
}
return Response.ok((StreamingOutput) output -> {
Files.copy(tempPath, output);
})
.header("Content-Length", targetCopiedHolder.value())
.header(FileFrontConstants.HEADER_PATH_NAME, pathNameHolder.value())
.build();
}
/**
* Updates a file content located by specified {@code locator}.
*
* @param locator the locator of file.
* @param suffix file suffix
* @param distribute a flag for distributing to siblings.
* @param entity
*
* @return a response.
*/
@Consumes(MediaType.WILDCARD)
@PUT
@Path("/{locator: .+}")
public Response updateSingle(
@PathParam("locator") final String locator,
@QueryParam("suffix") final String suffix,
@QueryParam("distribute")
@DefaultValue("true") final boolean distribute,
final InputStream entity) {
final FileContext fileContext = new DefaultFileContext();
fileContext.keyBufferSupplier(
() -> ByteBuffer.wrap(locator.getBytes(StandardCharsets.UTF_8)));
if (suffix != null && !suffix.trim().isEmpty()) {
fileContext.fileSuffixSupplier(() -> suffix.trim());
}
final Holder<java.nio.file.Path> localPathHolder = new Holder<>();
fileContext.localLeafConsumer(
localPath -> localPathHolder.value(localPath)
);
final Holder<String> pathNameHolder = new Holder<>();
fileContext.pathNameConsumer(pathName -> {
pathNameHolder.value(pathName);
});
try {
tempPath = Files.createTempFile("prefix", "suffix");
Files.copy(entity, tempPath, StandardCopyOption.REPLACE_EXISTING);
} catch (final IOException ioe) {
throw new WebApplicationException(ioe);
}
fileContext.sourceChannelSupplier(() -> {
try {
return FileChannel.open(tempPath, StandardOpenOption.READ);
} catch (final IOException ioe) {
throw new RuntimeException(ioe);
}
});
final Holder<Long> sourceCopiedHolder = new Holder<>();
fileContext.sourceCopiedConsumer(
sourceCopied -> sourceCopiedHolder.value(sourceCopied)
);
try {
fileBack.update(fileContext);
} catch (IOException | FileBackException e) {
logger.error("failed to write", e);
throw new WebApplicationException(e); // 500
}
if (distribute) {
logger.debug("distrubuting...");
fileContext.property(PROPERTY_TEMP_PATH, tempPath);
fileContext.property(PROPERTY_MEDIA_TYPE, contentType);
updateSingleDistribute(fileContext, uriInfo, fileFronts);
}
return Response.noContent().build();
}
/**
* Deletes a file content located by given {@code locator}.
*
* @param locator the file locator
* @param suffix an optional file name suffix such as "png" or "txt"
* @param distribute
*
* @return response
*/
@DELETE
@Path("/{locator: .+}")
public Response deleteSingle(
@PathParam("locator") final String locator,
@QueryParam("suffix") final String suffix,
@QueryParam("distribute") @DefaultValue("true")
final boolean distribute) {
final FileContext fileContext = new DefaultFileContext();
fileContext.keyBufferSupplier(
() -> ByteBuffer.wrap(locator.getBytes(StandardCharsets.UTF_8)));
if (suffix != null && !suffix.trim().isEmpty()) {
fileContext.fileSuffixSupplier(() -> suffix.trim());
}
try {
fileBack.delete(fileContext);
} catch (IOException | FileBackException e) {
logger.error("failed to delete", e);
throw new WebApplicationException(e);
}
if (distribute) {
logger.debug("distributing..");
deleteSingleDistribute(fileContext, uriInfo, fileFronts);
}
return Response.noContent().build();
}
private transient final Logger logger = getLogger(getClass());
private transient java.nio.file.Path tempPath;
/**
* A file back injected.
*/
@Inject
@Backing
private FileBack fileBack;
/**
* A list of sibling file fronts to distribute files and commands.
*/
@Inject
@Siblings
private List<URI> fileFronts;
@Context
private UriInfo uriInfo;
@HeaderParam("Content-Type")
private MediaType contentType;
}
| updated
| src/main/java/com/github/jinahya/simple/file/front/LocatorsResource.java | updated | <ide><path>rc/main/java/com/github/jinahya/simple/file/front/LocatorsResource.java
<ide> *
<ide> * @author Jin Kwon <jinahya_at_gmail.com>
<ide> */
<del>@Path("/locators")
<add>@Path("locators")
<ide> public class LocatorsResource {
<ide>
<ide>
<ide> */
<ide> @Produces(MediaType.WILDCARD)
<ide> @GET
<del> @Path("/{locator: .+}")
<add> @Path("{locator: .+}")
<ide> public Response readSingle(
<ide> @PathParam("locator") final String locator,
<ide> @QueryParam("suffix") final String suffix) {
<ide> */
<ide> @Consumes(MediaType.WILDCARD)
<ide> @PUT
<del> @Path("/{locator: .+}")
<add> @Path("{locator: .+}")
<ide> public Response updateSingle(
<ide> @PathParam("locator") final String locator,
<ide> @QueryParam("suffix") final String suffix,
<ide> fileContext.fileSuffixSupplier(() -> suffix.trim());
<ide> }
<ide>
<del> final Holder<java.nio.file.Path> localPathHolder = new Holder<>();
<del> fileContext.localLeafConsumer(
<del> localPath -> localPathHolder.value(localPath)
<del> );
<del>
<ide> final Holder<String> pathNameHolder = new Holder<>();
<ide> fileContext.pathNameConsumer(pathName -> {
<ide> pathNameHolder.value(pathName);
<ide> * @return response
<ide> */
<ide> @DELETE
<del> @Path("/{locator: .+}")
<add> @Path("{locator: .+}")
<ide> public Response deleteSingle(
<ide> @PathParam("locator") final String locator,
<ide> @QueryParam("suffix") final String suffix, |
|
Java | apache-2.0 | dcbf002757aa7cf8d526776353a150d1d165649a | 0 | monetate/closure-compiler,google/closure-compiler,ChadKillingsworth/closure-compiler,monetate/closure-compiler,nawawi/closure-compiler,nawawi/closure-compiler,monetate/closure-compiler,google/closure-compiler,ChadKillingsworth/closure-compiler,ChadKillingsworth/closure-compiler,google/closure-compiler,google/closure-compiler,nawawi/closure-compiler,monetate/closure-compiler,ChadKillingsworth/closure-compiler,nawawi/closure-compiler | /*
* Copyright 2008 The Closure Compiler Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.javascript.jscomp;
import static com.google.common.truth.Truth.assertWithMessage;
import static com.google.javascript.jscomp.testing.JSCompCorrespondences.DESCRIPTION_EQUALITY;
import static com.google.javascript.rhino.jstype.JSTypeNative.BOOLEAN_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.NUMBER_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.OBJECT_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.STRING_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.SYMBOL_TYPE;
import static com.google.javascript.rhino.testing.TypeSubject.assertType;
import static com.google.javascript.rhino.testing.TypeSubject.types;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.google.javascript.jscomp.CompilerOptions.LanguageMode;
import com.google.javascript.jscomp.parsing.parser.FeatureSet.Feature;
import com.google.javascript.rhino.JSTypeExpression;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.jstype.FunctionType;
import com.google.javascript.rhino.jstype.JSType;
import com.google.javascript.rhino.jstype.JSTypeNative;
import com.google.javascript.rhino.jstype.JSTypeRegistry;
import com.google.javascript.rhino.jstype.ObjectType;
import com.google.javascript.rhino.jstype.RecordTypeBuilder;
import com.google.javascript.rhino.jstype.TemplatizedType;
import com.google.javascript.rhino.testing.TestErrorReporter;
import org.junit.After;
import org.junit.Before;
/** This class is mostly used by passes testing {@link TypeCheck}. */
abstract class CompilerTypeTestCase {
protected static final Joiner LINE_JOINER = Joiner.on('\n');
static final String CLOSURE_DEFS =
LINE_JOINER.join(
"goog.inherits = function(x, y) {};",
"/** @type {!Function} */ goog.abstractMethod = function() {};",
"goog.isFunction = function(x) {};",
"goog.isObject = function(x) {};",
"/** @const */ goog.array = {};",
// simplified ArrayLike definition
"/**",
" * @typedef {Array|{length: number}}",
" */",
"goog.array.ArrayLike;",
"/**",
" * @param {Array<T>|{length:number}} arr",
" * @param {function(this:S, T, number, goog.array.ArrayLike):boolean} f",
" * @param {S=} obj",
" * @return {!Array<T>}",
" * @template T,S",
" */",
// return empty array to satisfy return type
"goog.array.filter = function(arr, f, obj){ return []; };",
"goog.asserts = {};",
"/** @return {*} */ goog.asserts.assert = function(obj, msg = undefined) { return obj;"
+ " };",
"goog.loadModule = function(mod) {};");
/**
* A default set of externs for testing.
*
* TODO(bradfordcsmith): Replace this with externs built by TestExternsBuilder.
*/
static final String DEFAULT_EXTERNS = CompilerTestCase.DEFAULT_EXTERNS;
protected Compiler compiler;
protected JSTypeRegistry registry;
protected TestErrorReporter errorReporter;
protected CompilerOptions getDefaultOptions() {
CompilerOptions options = new CompilerOptions();
options.setCodingConvention(getCodingConvention());
options.setLanguage(LanguageMode.UNSUPPORTED);
options.setWarningLevel(
DiagnosticGroups.MISSING_PROPERTIES, CheckLevel.WARNING);
options.setWarningLevel(
DiagnosticGroups.MISPLACED_TYPE_ANNOTATION, CheckLevel.WARNING);
options.setWarningLevel(
DiagnosticGroups.INVALID_CASTS, CheckLevel.WARNING);
options.setWarningLevel(DiagnosticGroups.LINT_CHECKS, CheckLevel.WARNING);
options.setWarningLevel(DiagnosticGroups.JSDOC_MISSING_TYPE, CheckLevel.WARNING);
options.setWarningLevel(DiagnosticGroups.BOUNDED_GENERICS, CheckLevel.WARNING);
return options;
}
protected CodingConvention getCodingConvention() {
return new GoogleCodingConvention();
}
protected void checkReportedWarningsHelper(String[] expected) {
if (expected == null) {
expected = new String[0];
}
assertWithMessage("Regarding warnings:")
.that(compiler.getWarnings())
.comparingElementsUsing(DESCRIPTION_EQUALITY)
.containsExactlyElementsIn(expected)
.inOrder();
}
@Before
public void setUp() throws Exception {
errorReporter = new TestErrorReporter();
initializeNewCompiler(getDefaultOptions());
}
@After
public void validateWarningsAndErrors() {
errorReporter.verifyHasEncounteredAllWarningsAndErrors();
}
protected static String lines(String line) {
return line;
}
protected static String lines(String... lines) {
return LINE_JOINER.join(lines);
}
protected void initializeNewCompiler(CompilerOptions options) {
compiler = new Compiler();
compiler.initOptions(options);
compiler.setFeatureSet(compiler.getFeatureSet().without(Feature.MODULES));
registry = compiler.getTypeRegistry();
}
protected JSType createUnionType(JSType... variants) {
return registry.createUnionType(variants);
}
protected RecordTypeBuilder createRecordTypeBuilder() {
return new RecordTypeBuilder(registry);
}
protected JSType createNullableType(JSType type) {
return registry.createNullableType(type);
}
protected JSType createOptionalType(JSType type) {
return registry.createOptionalType(type);
}
protected TemplatizedType createTemplatizedType(
ObjectType baseType, ImmutableList<JSType> templatizedTypes) {
return registry.createTemplatizedType(baseType, templatizedTypes);
}
protected TemplatizedType createTemplatizedType(ObjectType baseType, JSType... templatizedType) {
return createTemplatizedType(baseType, ImmutableList.copyOf(templatizedType));
}
/** Asserts that a Node representing a type expression resolves to the correct {@code JSType}. */
protected void assertTypeEquals(JSType expected, Node actual) {
assertTypeEquals(expected, new JSTypeExpression(actual, "<BaseJSTypeTestCase.java>"));
}
/** Asserts that a a type expression resolves to the correct {@code JSType}. */
protected void assertTypeEquals(JSType expected, JSTypeExpression actual) {
assertTypeEquals(expected, resolve(actual));
}
protected final void assertTypeEquals(JSType a, JSType b) {
assertType(b).isEqualTo(a);
}
protected final void assertTypeEquals(String msg, JSType a, JSType b) {
assertWithMessage(msg).about(types()).that(b).isEqualTo(a);
}
/** Resolves a type expression, expecting the given warnings. */
protected JSType resolve(JSTypeExpression n, String... warnings) {
errorReporter.expectAllWarnings(warnings);
return n.evaluate(null, registry);
}
protected ObjectType getNativeNoObjectType() {
return getNativeObjectType(JSTypeNative.NO_OBJECT_TYPE);
}
protected ObjectType getNativeArrayType() {
return getNativeObjectType(JSTypeNative.ARRAY_TYPE);
}
protected ObjectType getNativeStringObjectType() {
return getNativeObjectType(JSTypeNative.STRING_OBJECT_TYPE);
}
protected ObjectType getNativeNumberObjectType() {
return getNativeObjectType(JSTypeNative.NUMBER_OBJECT_TYPE);
}
protected ObjectType getNativeBooleanObjectType() {
return getNativeObjectType(JSTypeNative.BOOLEAN_OBJECT_TYPE);
}
protected ObjectType getNativeNoType() {
return getNativeObjectType(JSTypeNative.NO_TYPE);
}
protected ObjectType getNativeUnknownType() {
return getNativeObjectType(JSTypeNative.UNKNOWN_TYPE);
}
protected ObjectType getNativeCheckedUnknownType() {
return getNativeObjectType(JSTypeNative.CHECKED_UNKNOWN_TYPE);
}
protected ObjectType getNativeObjectType() {
return getNativeObjectType(JSTypeNative.OBJECT_TYPE);
}
ObjectType getNativeObjectType(JSTypeNative jsTypeNative) {
return registry.getNativeObjectType(jsTypeNative);
}
protected FunctionType getNativeObjectConstructorType() {
return getNativeFunctionType(JSTypeNative.OBJECT_FUNCTION_TYPE);
}
protected FunctionType getNativeArrayConstructorType() {
return getNativeFunctionType(JSTypeNative.ARRAY_FUNCTION_TYPE);
}
protected FunctionType getNativeBooleanObjectConstructorType() {
return getNativeFunctionType(JSTypeNative.BOOLEAN_OBJECT_FUNCTION_TYPE);
}
protected FunctionType getNativeNumberObjectConstructorType() {
return getNativeFunctionType(JSTypeNative.NUMBER_OBJECT_FUNCTION_TYPE);
}
protected FunctionType getNativeStringObjectConstructorType() {
return getNativeFunctionType(JSTypeNative.STRING_OBJECT_FUNCTION_TYPE);
}
protected FunctionType getNativeDateConstructorType() {
return getNativeFunctionType(JSTypeNative.DATE_FUNCTION_TYPE);
}
protected FunctionType getNativeRegexpConstructorType() {
return getNativeFunctionType(JSTypeNative.REGEXP_FUNCTION_TYPE);
}
protected FunctionType getNativeFunctionType() {
return getNativeFunctionType(JSTypeNative.FUNCTION_TYPE);
}
FunctionType getNativeFunctionType(JSTypeNative jsTypeNative) {
return registry.getNativeFunctionType(jsTypeNative);
}
protected JSType getNativeVoidType() {
return getNativeType(JSTypeNative.VOID_TYPE);
}
protected JSType getNativeNullType() {
return getNativeType(JSTypeNative.NULL_TYPE);
}
protected JSType getNativeNullVoidType() {
return getNativeType(JSTypeNative.NULL_VOID);
}
protected JSType getNativeNumberType() {
return getNativeType(JSTypeNative.NUMBER_TYPE);
}
protected JSType getNativeBooleanType() {
return getNativeType(JSTypeNative.BOOLEAN_TYPE);
}
protected JSType getNativeStringType() {
return getNativeType(JSTypeNative.STRING_TYPE);
}
protected JSType getNativeObjectNumberStringBooleanType() {
return registry.createUnionType(OBJECT_TYPE, NUMBER_TYPE, STRING_TYPE, BOOLEAN_TYPE);
}
protected JSType getNativeNumberStringBooleanType() {
return getNativeType(JSTypeNative.NUMBER_STRING_BOOLEAN);
}
protected JSType getNativeObjectNumberStringBooleanSymbolType() {
return registry.createUnionType(
OBJECT_TYPE, NUMBER_TYPE, STRING_TYPE, BOOLEAN_TYPE, SYMBOL_TYPE);
}
protected JSType getNativeValueTypes() {
return getNativeType(JSTypeNative.VALUE_TYPES);
}
JSType getNativeAllType() {
return getNativeType(JSTypeNative.ALL_TYPE);
}
JSType getNativeType(JSTypeNative jsTypeNative) {
return registry.getNativeType(jsTypeNative);
}
}
| test/com/google/javascript/jscomp/CompilerTypeTestCase.java | /*
* Copyright 2008 The Closure Compiler Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.javascript.jscomp;
import static com.google.common.truth.Truth.assertWithMessage;
import static com.google.javascript.jscomp.testing.JSCompCorrespondences.DESCRIPTION_EQUALITY;
import static com.google.javascript.rhino.jstype.JSTypeNative.BOOLEAN_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.NUMBER_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.OBJECT_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.STRING_TYPE;
import static com.google.javascript.rhino.jstype.JSTypeNative.SYMBOL_TYPE;
import static com.google.javascript.rhino.testing.TypeSubject.assertType;
import static com.google.javascript.rhino.testing.TypeSubject.types;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.google.javascript.jscomp.parsing.parser.FeatureSet.Feature;
import com.google.javascript.rhino.JSTypeExpression;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.jstype.FunctionType;
import com.google.javascript.rhino.jstype.JSType;
import com.google.javascript.rhino.jstype.JSTypeNative;
import com.google.javascript.rhino.jstype.JSTypeRegistry;
import com.google.javascript.rhino.jstype.ObjectType;
import com.google.javascript.rhino.jstype.RecordTypeBuilder;
import com.google.javascript.rhino.jstype.TemplatizedType;
import com.google.javascript.rhino.testing.TestErrorReporter;
import org.junit.After;
import org.junit.Before;
/** This class is mostly used by passes testing {@link TypeCheck}. */
abstract class CompilerTypeTestCase {
protected static final Joiner LINE_JOINER = Joiner.on('\n');
static final String CLOSURE_DEFS =
LINE_JOINER.join(
"goog.inherits = function(x, y) {};",
"/** @type {!Function} */ goog.abstractMethod = function() {};",
"goog.isFunction = function(x) {};",
"goog.isObject = function(x) {};",
"/** @const */ goog.array = {};",
// simplified ArrayLike definition
"/**",
" * @typedef {Array|{length: number}}",
" */",
"goog.array.ArrayLike;",
"/**",
" * @param {Array<T>|{length:number}} arr",
" * @param {function(this:S, T, number, goog.array.ArrayLike):boolean} f",
" * @param {S=} obj",
" * @return {!Array<T>}",
" * @template T,S",
" */",
// return empty array to satisfy return type
"goog.array.filter = function(arr, f, obj){ return []; };",
"goog.asserts = {};",
"/** @return {*} */ goog.asserts.assert = function(obj, msg = undefined) { return obj;"
+ " };",
"goog.loadModule = function(mod) {};");
/**
* A default set of externs for testing.
*
* TODO(bradfordcsmith): Replace this with externs built by TestExternsBuilder.
*/
static final String DEFAULT_EXTERNS = CompilerTestCase.DEFAULT_EXTERNS;
protected Compiler compiler;
protected JSTypeRegistry registry;
protected TestErrorReporter errorReporter;
protected CompilerOptions getDefaultOptions() {
CompilerOptions options = new CompilerOptions();
options.setCodingConvention(getCodingConvention());
options.setWarningLevel(
DiagnosticGroups.MISSING_PROPERTIES, CheckLevel.WARNING);
options.setWarningLevel(
DiagnosticGroups.MISPLACED_TYPE_ANNOTATION, CheckLevel.WARNING);
options.setWarningLevel(
DiagnosticGroups.INVALID_CASTS, CheckLevel.WARNING);
options.setWarningLevel(DiagnosticGroups.LINT_CHECKS, CheckLevel.WARNING);
options.setWarningLevel(DiagnosticGroups.JSDOC_MISSING_TYPE, CheckLevel.WARNING);
options.setWarningLevel(DiagnosticGroups.BOUNDED_GENERICS, CheckLevel.WARNING);
return options;
}
protected CodingConvention getCodingConvention() {
return new GoogleCodingConvention();
}
protected void checkReportedWarningsHelper(String[] expected) {
if (expected == null) {
expected = new String[0];
}
assertWithMessage("Regarding warnings:")
.that(compiler.getWarnings())
.comparingElementsUsing(DESCRIPTION_EQUALITY)
.containsExactlyElementsIn(expected)
.inOrder();
}
@Before
public void setUp() throws Exception {
errorReporter = new TestErrorReporter();
initializeNewCompiler(getDefaultOptions());
}
@After
public void validateWarningsAndErrors() {
errorReporter.verifyHasEncounteredAllWarningsAndErrors();
}
protected static String lines(String line) {
return line;
}
protected static String lines(String... lines) {
return LINE_JOINER.join(lines);
}
protected void initializeNewCompiler(CompilerOptions options) {
compiler = new Compiler();
compiler.initOptions(options);
compiler.setFeatureSet(compiler.getFeatureSet().without(Feature.MODULES));
registry = compiler.getTypeRegistry();
}
protected JSType createUnionType(JSType... variants) {
return registry.createUnionType(variants);
}
protected RecordTypeBuilder createRecordTypeBuilder() {
return new RecordTypeBuilder(registry);
}
protected JSType createNullableType(JSType type) {
return registry.createNullableType(type);
}
protected JSType createOptionalType(JSType type) {
return registry.createOptionalType(type);
}
protected TemplatizedType createTemplatizedType(
ObjectType baseType, ImmutableList<JSType> templatizedTypes) {
return registry.createTemplatizedType(baseType, templatizedTypes);
}
protected TemplatizedType createTemplatizedType(ObjectType baseType, JSType... templatizedType) {
return createTemplatizedType(baseType, ImmutableList.copyOf(templatizedType));
}
/** Asserts that a Node representing a type expression resolves to the correct {@code JSType}. */
protected void assertTypeEquals(JSType expected, Node actual) {
assertTypeEquals(expected, new JSTypeExpression(actual, "<BaseJSTypeTestCase.java>"));
}
/** Asserts that a a type expression resolves to the correct {@code JSType}. */
protected void assertTypeEquals(JSType expected, JSTypeExpression actual) {
assertTypeEquals(expected, resolve(actual));
}
protected final void assertTypeEquals(JSType a, JSType b) {
assertType(b).isEqualTo(a);
}
protected final void assertTypeEquals(String msg, JSType a, JSType b) {
assertWithMessage(msg).about(types()).that(b).isEqualTo(a);
}
/** Resolves a type expression, expecting the given warnings. */
protected JSType resolve(JSTypeExpression n, String... warnings) {
errorReporter.expectAllWarnings(warnings);
return n.evaluate(null, registry);
}
protected ObjectType getNativeNoObjectType() {
return getNativeObjectType(JSTypeNative.NO_OBJECT_TYPE);
}
protected ObjectType getNativeArrayType() {
return getNativeObjectType(JSTypeNative.ARRAY_TYPE);
}
protected ObjectType getNativeStringObjectType() {
return getNativeObjectType(JSTypeNative.STRING_OBJECT_TYPE);
}
protected ObjectType getNativeNumberObjectType() {
return getNativeObjectType(JSTypeNative.NUMBER_OBJECT_TYPE);
}
protected ObjectType getNativeBooleanObjectType() {
return getNativeObjectType(JSTypeNative.BOOLEAN_OBJECT_TYPE);
}
protected ObjectType getNativeNoType() {
return getNativeObjectType(JSTypeNative.NO_TYPE);
}
protected ObjectType getNativeUnknownType() {
return getNativeObjectType(JSTypeNative.UNKNOWN_TYPE);
}
protected ObjectType getNativeCheckedUnknownType() {
return getNativeObjectType(JSTypeNative.CHECKED_UNKNOWN_TYPE);
}
protected ObjectType getNativeObjectType() {
return getNativeObjectType(JSTypeNative.OBJECT_TYPE);
}
ObjectType getNativeObjectType(JSTypeNative jsTypeNative) {
return registry.getNativeObjectType(jsTypeNative);
}
protected FunctionType getNativeObjectConstructorType() {
return getNativeFunctionType(JSTypeNative.OBJECT_FUNCTION_TYPE);
}
protected FunctionType getNativeArrayConstructorType() {
return getNativeFunctionType(JSTypeNative.ARRAY_FUNCTION_TYPE);
}
protected FunctionType getNativeBooleanObjectConstructorType() {
return getNativeFunctionType(JSTypeNative.BOOLEAN_OBJECT_FUNCTION_TYPE);
}
protected FunctionType getNativeNumberObjectConstructorType() {
return getNativeFunctionType(JSTypeNative.NUMBER_OBJECT_FUNCTION_TYPE);
}
protected FunctionType getNativeStringObjectConstructorType() {
return getNativeFunctionType(JSTypeNative.STRING_OBJECT_FUNCTION_TYPE);
}
protected FunctionType getNativeDateConstructorType() {
return getNativeFunctionType(JSTypeNative.DATE_FUNCTION_TYPE);
}
protected FunctionType getNativeRegexpConstructorType() {
return getNativeFunctionType(JSTypeNative.REGEXP_FUNCTION_TYPE);
}
protected FunctionType getNativeFunctionType() {
return getNativeFunctionType(JSTypeNative.FUNCTION_TYPE);
}
FunctionType getNativeFunctionType(JSTypeNative jsTypeNative) {
return registry.getNativeFunctionType(jsTypeNative);
}
protected JSType getNativeVoidType() {
return getNativeType(JSTypeNative.VOID_TYPE);
}
protected JSType getNativeNullType() {
return getNativeType(JSTypeNative.NULL_TYPE);
}
protected JSType getNativeNullVoidType() {
return getNativeType(JSTypeNative.NULL_VOID);
}
protected JSType getNativeNumberType() {
return getNativeType(JSTypeNative.NUMBER_TYPE);
}
protected JSType getNativeBooleanType() {
return getNativeType(JSTypeNative.BOOLEAN_TYPE);
}
protected JSType getNativeStringType() {
return getNativeType(JSTypeNative.STRING_TYPE);
}
protected JSType getNativeObjectNumberStringBooleanType() {
return registry.createUnionType(OBJECT_TYPE, NUMBER_TYPE, STRING_TYPE, BOOLEAN_TYPE);
}
protected JSType getNativeNumberStringBooleanType() {
return getNativeType(JSTypeNative.NUMBER_STRING_BOOLEAN);
}
protected JSType getNativeObjectNumberStringBooleanSymbolType() {
return registry.createUnionType(
OBJECT_TYPE, NUMBER_TYPE, STRING_TYPE, BOOLEAN_TYPE, SYMBOL_TYPE);
}
protected JSType getNativeValueTypes() {
return getNativeType(JSTypeNative.VALUE_TYPES);
}
JSType getNativeAllType() {
return getNativeType(JSTypeNative.ALL_TYPE);
}
JSType getNativeType(JSTypeNative jsTypeNative) {
return registry.getNativeType(jsTypeNative);
}
}
| Internal change
PiperOrigin-RevId: 379486155
| test/com/google/javascript/jscomp/CompilerTypeTestCase.java | Internal change | <ide><path>est/com/google/javascript/jscomp/CompilerTypeTestCase.java
<ide>
<ide> import com.google.common.base.Joiner;
<ide> import com.google.common.collect.ImmutableList;
<add>import com.google.javascript.jscomp.CompilerOptions.LanguageMode;
<ide> import com.google.javascript.jscomp.parsing.parser.FeatureSet.Feature;
<ide> import com.google.javascript.rhino.JSTypeExpression;
<ide> import com.google.javascript.rhino.Node;
<ide> protected CompilerOptions getDefaultOptions() {
<ide> CompilerOptions options = new CompilerOptions();
<ide> options.setCodingConvention(getCodingConvention());
<del>
<add> options.setLanguage(LanguageMode.UNSUPPORTED);
<ide> options.setWarningLevel(
<ide> DiagnosticGroups.MISSING_PROPERTIES, CheckLevel.WARNING);
<ide> options.setWarningLevel( |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.